Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 6 additions & 1 deletion src/node/internal/filesystem.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,12 @@ export function readLink(
options: { failIfNotSymlink: boolean }
): string;

export function link(from: URL, to: URL, options: { symbolic: boolean }): void;
export function link(
from: URL,
to: URL,
options: { symbolic: boolean },
rawTarget?: string
): void;

export function unlink(path: URL): void;

Expand Down
16 changes: 8 additions & 8 deletions src/node/internal/internal_fs_callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,11 +340,10 @@ export function cp(
// it here just to use it so the compiler doesn't complain.
validateBoolean(exclusive, '');

// We're not current implementing verbatimSymlinks in any meaningful way.
// Our symlinks are always fully qualfied. That is, they always point to
// an absolute path and never to a relative path, so there is no distinction
// between verbatimSymlinks and non-verbatimSymlinks. We validate the option
// value above but otherwise we ignore it.
// We're not currently implementing verbatimSymlinks. A copied symlink
// always points at the source link's absolute target, as Node.js does
// without verbatimSymlinks. We validate the option value above but
// otherwise we ignore it.

src = normalizePath(src);
dest = normalizePath(dest);
Expand Down Expand Up @@ -1197,13 +1196,14 @@ export function symlink(
} else {
type = typeOrCallback;
}
const normalizedTarget = normalizePath(target);
const normalizedPath = normalizePath(path);
// Validate synchronously, but hand symlinkSync the target as written.
normalizePath(target);
normalizePath(path);
if (type != null) {
validateOneOf(type, 'type', ['dir', 'file', 'junction', null]);
}
callWithErrorOnlyCallback(() => {
fssync.symlinkSync(normalizedTarget, normalizedPath, type);
fssync.symlinkSync(target, path, type);
}, callback);
}

Expand Down
19 changes: 13 additions & 6 deletions src/node/internal/internal_fs_sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,11 +269,10 @@ export function cpSync(
// it here just to use it so the compiler doesn't complain.
validateBoolean(exclusive, '');

// We're not currently implementing verbatimSymlinks in any meaningful way.
// Our symlinks are always fully qualfied. That is, they always point to
// an absolute path and never to a relative path, so there is no distinction
// between verbatimSymlinks and non-verbatimSymlinks. We validate the option
// value above but otherwise we ignore it.
// We're not currently implementing verbatimSymlinks. A copied symlink
// always points at the source link's absolute target, as Node.js does
// without verbatimSymlinks. We validate the option value above but
// otherwise we ignore it.

// We're also not currently implementing the preserveTimestamps option.
// Timestamps in our virtual filesystem aren't super meaningful given
Expand Down Expand Up @@ -784,7 +783,15 @@ export function symlinkSync(
): void {
// We don't implement type in any meaningful way but we do validate it.
validateOneOf(type, 'type', ['dir', 'file', 'junction', null]);
cffs.link(normalizePath(path), normalizePath(target), { symbolic: true });
// A relative target resolves from the directory that holds the link.
const raw = Buffer.isBuffer(target) ? target.toString() : target;
const linkUrl = normalizePath(path);
cffs.link(
linkUrl,
normalizePath(raw, 'utf8', linkUrl),
{ symbolic: true },
raw instanceof URL ? undefined : raw
);
}

export function truncateSync(path: FilePath, len: number = 0): void {
Expand Down
13 changes: 10 additions & 3 deletions src/node/internal/internal_fs_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,13 @@ export function getDate(time: RawTime | Date): Date {
);
}

// Normalizes the input file path to a URL object.
export function normalizePath(path: FilePath, encoding: string = 'utf8'): URL {
// Normalizes the input file path to a URL object. A relative path resolves
// against `base` when given, otherwise against the current working directory.
export function normalizePath(
path: FilePath,
encoding: string = 'utf8',
base?: URL
): URL {
// We treat all of our virtual file system paths as file URLs
// as a way of normalizing them. Because our file system is
// fully virtual, we don't need to worry about a number of the
Expand Down Expand Up @@ -169,7 +174,9 @@ export function normalizePath(path: FilePath, encoding: string = 'utf8'): URL {

return new URL(
path,
path.startsWith('/') ? 'file://' : `file://${processImpl.getCwd()}/`
path.startsWith('/')
? 'file://'
: (base ?? `file://${processImpl.getCwd()}/`)
);
}

Expand Down
28 changes: 22 additions & 6 deletions src/workerd/api/filesystem.c++
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,9 @@ kj::String FileSystemModule::readLink(jsg::Lock& js, FilePath path, ReadLinkOpti
return path.toString(true);
}
KJ_CASE_ONEOF(link, kj::Rc<workerd::SymbolicLink>) {
if (options.failIfNotSymlink) {
return link->getRawTarget();
Comment thread
littledivy marked this conversation as resolved.
Resolved
}
return link->getTargetPath().toString(true);
}
KJ_CASE_ONEOF(err, workerd::FsError) {
Expand All @@ -364,7 +367,11 @@ kj::String FileSystemModule::readLink(jsg::Lock& js, FilePath path, ReadLinkOpti
}
}

void FileSystemModule::link(jsg::Lock& js, FilePath from, FilePath to, LinkOptions options) {
void FileSystemModule::link(jsg::Lock& js,
FilePath from,
FilePath to,
LinkOptions options,
jsg::Optional<kj::String> rawTarget) {
// The from argument is where we are creating the link, while the to is the target.
auto& vfs = workerd::VirtualFileSystem::current(js);
NormalizedFilePath normalizedFrom(js, kj::mv(from));
Expand Down Expand Up @@ -397,7 +404,8 @@ void FileSystemModule::link(jsg::Lock& js, FilePath from, FilePath to, LinkOptio

// If we are creating a symbolic link, we do not need to check if the target exists.
if (options.symbolic) {
KJ_IF_SOME(err, dir->add(js, fromRelative.name, vfs.newSymbolicLink(js, toUrl))) {
KJ_IF_SOME(err,
dir->add(js, fromRelative.name, vfs.newSymbolicLink(js, toUrl, kj::mv(rawTarget)))) {
throwFsError(js, err, "link"_kj);
}
return;
Expand Down Expand Up @@ -1360,9 +1368,11 @@ void handleCpLink(jsg::Lock& js,
const workerd::VirtualFileSystem& vfs,
kj::Rc<workerd::SymbolicLink> srcLink,
const jsg::Url& destUrl) {
// Here, we are going to essentially create a hard link (new refcount)
// of srcLink and destUrl, if we are allowed to do so.
// We need to check if the destination exists and is writable.
// Here, we are going to create a new symbolic link at destUrl to the
// absolute target of srcLink, if we are allowed to do so. Like Node.js
// without verbatimSymlinks, a relative target is not kept, since the copy
// can live in a different directory. We need to check if the destination
// exists and is writable.
auto relative = destUrl.getRelative();
// relative.base is the parent directory path.
// relative.name is the name of the link we are creating in the parent.
Expand Down Expand Up @@ -1400,7 +1410,13 @@ void handleCpLink(jsg::Lock& js,
}
}
// Now, we can add the symbolic link to the directory.
KJ_IF_SOME(err, dir->add(js, relative.name, kj::mv(srcLink))) {
auto rawTarget = srcLink->getRawTarget();
kj::Maybe<kj::String> keptTarget;
if (rawTarget.startsWith("/"_kj)) {
keptTarget = kj::mv(rawTarget);
}
auto copy = vfs.newSymbolicLink(js, srcLink->getTargetUrl(), kj::mv(keptTarget));
KJ_IF_SOME(err, dir->add(js, relative.name, kj::mv(copy))) {
// If we got here, an error was reported
throwFsError(js, err, "cp"_kj);
}
Expand Down
10 changes: 8 additions & 2 deletions src/workerd/api/filesystem.h
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ class FileSystemModule final: public jsg::Object {
struct ReadLinkOptions {
// The readLink method is used for both realpath and readlink. The readlink
// API will throw an error if the path is not a symlink. The realpath API
// will return the resolved path either way.
// will return the resolved path either way. For a symlink, readlink gets
// the target as written and realpath gets the absolute target path.
bool failIfNotSymlink = false;
JSG_STRUCT(failIfNotSymlink);
};
Expand All @@ -78,7 +79,12 @@ class FileSystemModule final: public jsg::Object {
JSG_STRUCT(symbolic);
};

void link(jsg::Lock& js, FilePath from, FilePath to, LinkOptions options);
// For a symbolic link, rawTarget is the target as written.
void link(jsg::Lock& js,
FilePath from,
FilePath to,
LinkOptions options,
jsg::Optional<kj::String> rawTarget = kj::none);

void unlink(jsg::Lock& js, FilePath path);

Expand Down
57 changes: 57 additions & 0 deletions src/workerd/api/node/tests/fs-link-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,18 @@ import {
readlinkSync,
realpathSync,
unlinkSync,
cpSync,
mkdirSync,
writeFileSync,
readFileSync,
link,
symlink,
readlink,
realpath,
unlink,
promises,
} from 'node:fs';
import { Buffer } from 'node:buffer';

strictEqual(typeof existsSync, 'function');
strictEqual(typeof statSync, 'function');
Expand Down Expand Up @@ -466,3 +471,55 @@ export const symlinkAndUnlinkPromisesTest = {
ok(existsSync(src));
},
};

export const relativeSymlinkTargetIsKeptAndResolvedFromTheLink = {
async test() {
mkdirSync('/tmp/r/sub', { recursive: true });
writeFileSync('/tmp/r/sub/x.txt', 'x');

// The target is stored as written and resolves from the link's directory.
symlinkSync('sub/x.txt', '/tmp/r/link');
strictEqual(readlinkSync('/tmp/r/link'), 'sub/x.txt');
strictEqual(readFileSync('/tmp/r/link', 'utf8'), 'x');
strictEqual(realpathSync('/tmp/r/link'), '/tmp/r/sub/x.txt');

symlinkSync('../sub/x.txt', '/tmp/r/sub/up');
strictEqual(readlinkSync('/tmp/r/sub/up'), '../sub/x.txt');
strictEqual(readFileSync('/tmp/r/sub/up', 'utf8'), 'x');

// A relative link to a directory can be traversed.
symlinkSync('sub', '/tmp/r/dirlink');
strictEqual(readFileSync('/tmp/r/dirlink/x.txt', 'utf8'), 'x');

// Absolute targets are also kept as written.
symlinkSync('/tmp/r//sub/../sub/x.txt', '/tmp/r/abs');
strictEqual(readlinkSync('/tmp/r/abs'), '/tmp/r//sub/../sub/x.txt');
strictEqual(readFileSync('/tmp/r/abs', 'utf8'), 'x');

// Buffer targets are kept as written.
symlinkSync(Buffer.from('sub/x.txt'), '/tmp/r/buf');
strictEqual(readlinkSync('/tmp/r/buf'), 'sub/x.txt');
strictEqual(readFileSync('/tmp/r/buf', 'utf8'), 'x');

// cp writes the absolute target, so the copy still points at the same
// file from another directory.
mkdirSync('/tmp/r2');
cpSync('/tmp/r/link', '/tmp/r2/link', { dereference: false });
strictEqual(readlinkSync('/tmp/r2/link'), '/tmp/r/sub/x.txt');
strictEqual(readFileSync('/tmp/r2/link', 'utf8'), 'x');
cpSync('/tmp/r/abs', '/tmp/r2/abs', { dereference: false });
strictEqual(readlinkSync('/tmp/r2/abs'), '/tmp/r//sub/../sub/x.txt');

// The callback form.
const { promise, resolve, reject } = Promise.withResolvers();
symlink('sub/x.txt', '/tmp/r/cb', (err) => (err ? reject(err) : resolve()));
await promise;
strictEqual(readlinkSync('/tmp/r/cb'), 'sub/x.txt');
strictEqual(readFileSync('/tmp/r/cb', 'utf8'), 'x');

// The promises form.
await promises.symlink('../sub/x.txt', '/tmp/r/sub/p');
strictEqual(await promises.readlink('/tmp/r/sub/p'), '../sub/x.txt');
strictEqual(readFileSync('/tmp/r/sub/p', 'utf8'), 'x');
},
};
17 changes: 17 additions & 0 deletions src/workerd/api/node/tests/fs-nodejs-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1355,6 +1355,23 @@ export const copyAndRenameAsyncCallbackTest = {
},
};

export const fsRelativeSymlinkIgnoresCwdTest = {
test() {
// A relative target resolves from the link's directory, not the current
// working directory, even when the link path itself is relative.
mkdirSync('/tmp/cwd-link/sub', { recursive: true });
writeFileSync('/tmp/cwd-link/sub/x.txt', 'x');
process.chdir('/tmp/cwd-link');
try {
symlinkSync('x.txt', 'sub/rel');
} finally {
process.chdir('/bundle');
}
strictEqual(readlinkSync('/tmp/cwd-link/sub/rel'), 'x.txt');
strictEqual(readFileSync('/tmp/cwd-link/sub/rel', 'utf8'), 'x');
},
};

export const fsCwdTest = {
test() {
process.chdir('/bundle');
Expand Down
12 changes: 10 additions & 2 deletions src/workerd/io/worker-fs.c++
Original file line number Diff line number Diff line change
Expand Up @@ -1396,6 +1396,13 @@ jsg::Url SymbolicLink::getTargetUrl() const {
return KJ_ASSERT_NONNULL(jsg::Url::tryParse(path, "file:///"_kj));
}

kj::String SymbolicLink::getRawTarget() const {
KJ_IF_SOME(raw, rawTarget) {
return kj::str(raw);
}
return targetPath.toString(true);
}

kj::Maybe<kj::OneOf<FsError, kj::Rc<File>, kj::Rc<Directory>>> SymbolicLink::resolve(
jsg::Lock& js) {
KJ_IF_SOME(ret, root->tryOpen(js, getTargetPath())) {
Expand Down Expand Up @@ -1478,11 +1485,12 @@ kj::Maybe<kj::OneOf<FsError, Stat>> VirtualFileSystem::resolveStat(
return getRoot(js)->stat(js, root.eval(path));
}

kj::Rc<SymbolicLink> VirtualFileSystem::newSymbolicLink(jsg::Lock& js, const jsg::Url& url) const {
kj::Rc<SymbolicLink> VirtualFileSystem::newSymbolicLink(
jsg::Lock& js, const jsg::Url& url, kj::Maybe<kj::String> rawTarget) const {
KJ_REQUIRE(url.getProtocol() == "file:"_kj);
auto path = kj::str(url.getPathname().slice(1));
kj::Path root{};
return kj::rc<SymbolicLink>(getRoot(js), root.eval(path));
return kj::rc<SymbolicLink>(getRoot(js), root.eval(path), kj::mv(rawTarget));
}

SymbolicLinkRecursionGuardScope::SymbolicLinkRecursionGuardScope() {
Expand Down
19 changes: 15 additions & 4 deletions src/workerd/io/worker-fs.h
Original file line number Diff line number Diff line change
Expand Up @@ -494,11 +494,17 @@ class Directory: public kj::Refcounted {
// virtual file system and a target path. The target node may or may not
// exist, can be deleted and recreated at any time and the symlink will
// remain valid.
//
// The target path is always absolute: a relative target is resolved against
// the directory the link was created in. The target as written, when there
// is one, is kept separately for readlink. Links created from a URL, and
// cp copies of relative links, have none.
class SymbolicLink final: public kj::Refcounted {
public:
SymbolicLink(kj::Rc<Directory> root, kj::Path targetPath)
SymbolicLink(kj::Rc<Directory> root, kj::Path targetPath, kj::Maybe<kj::String> rawTarget)
: root(kj::mv(root)),
targetPath(kj::mv(targetPath)) {}
targetPath(kj::mv(targetPath)),
rawTarget(kj::mv(rawTarget)) {}
KJ_DISALLOW_COPY_AND_MOVE(SymbolicLink);

// Gets the stat for the symbolic link itself.
Expand All @@ -515,6 +521,9 @@ class SymbolicLink final: public kj::Refcounted {

jsg::Url getTargetUrl() const KJ_WARN_UNUSED_RESULT;

// Returns the target as written, or the target path if none was kept.
kj::String getRawTarget() const KJ_WARN_UNUSED_RESULT;

// Returns a UUID that uniquely identifies this fs node. The value stable across
// multiple calls to getUniqueId() on the same node, but is not guaranteed to
// be stable across worker restarts. This is primarily useful for implementing
Expand All @@ -529,6 +538,7 @@ class SymbolicLink final: public kj::Refcounted {
private:
kj::Rc<Directory> root;
kj::Path targetPath;
kj::Maybe<kj::String> rawTarget;
mutable kj::Maybe<kj::String> maybeUniqueId;
mutable kj::Maybe<jsg::ExternalMemoryAdjustment> maybeMemoryAdjustment;
};
Expand Down Expand Up @@ -592,8 +602,9 @@ class VirtualFileSystem {

// Creates a new symbolic link to the given target path. The target path
// does not need to exist.
kj::Rc<SymbolicLink> newSymbolicLink(
jsg::Lock& js, const jsg::Url& url) const KJ_WARN_UNUSED_RESULT;
kj::Rc<SymbolicLink> newSymbolicLink(jsg::Lock& js,
const jsg::Url& url,
kj::Maybe<kj::String> rawTarget = kj::none) const KJ_WARN_UNUSED_RESULT;

// Return the configured root paths for the bundle, temp, and dev directories.
virtual const jsg::Url& getBundleRoot() const KJ_WARN_UNUSED_RESULT = 0;
Expand Down
Loading