Commit 5440ac1f66a for nodejs

commit 5440ac1f66a0986e08519ace929634cfff2a1e82
Author: Matteo Collina <hello@matteocollina.com>
Date:   Wed Nov 25 07:43:21 2026 +0100

    sqlite: enforce permission model in Database

    Database opened database files without consulting the permission
    model, so code running with --permission could read and write any
    database regardless of --allow-fs-read and --allow-fs-write.

    Check read access, and write access unless the database is read-only,
    before opening a file-backed database. In-memory databases are exempt.
    SQLite also opens journal, WAL and temporary files, and ATTACH and
    backup() open further databases, so route every connection through a
    VFS shim that checks each path SQLite opens, deletes or probes.

    Reject URI filenames that select a VFS, since that would bypass the
    shim, and deny ATTACH when SQLite does not pass the filename to the
    authorizer.

    Refs: https://hackerone.com/reports/3686625
    Co-authored-by: Guilherme Araújo <arauujogui@gmail.com>
    Assisted-by: Claude Code
    Signed-off-by: Guilherme Araújo <arauujogui@gmail.com>
    PR-URL: https://github.com/nodejs/node/pull/62957
    Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com>
    Reviewed-By: James M Snell <jasnell@gmail.com>

diff --git a/doc/api/permissions.md b/doc/api/permissions.md
index 4648c441769..45e2c7679ae 100644
--- a/doc/api/permissions.md
+++ b/doc/api/permissions.md
@@ -517,6 +517,9 @@ There are constraints you need to know before using this system:
   than vulnerabilities. Please report them through the regular issue tracker.
 * Run-Time Loadable Extensions cannot be loaded when the Permission Model is
   enabled, affecting the sqlite module.
+* SQLite [URI filenames][] are disabled when the Permission Model is enabled.
+  The `node:sqlite` module rejects {URL} objects and paths starting with
+  `file:`, and `ATTACH DATABASE` treats such names as plain file paths.
 * Using existing file descriptors via the `node:fs` module bypasses the
   Permission Model.

@@ -553,6 +556,7 @@ Developers relying on --permission to sandbox untrusted code should be aware tha
   been granted contain relative symbolic links.

 [Security Policy]: https://github.com/nodejs/node/blob/main/SECURITY.md
+[URI filenames]: https://www.sqlite.org/uri.html
 [`--allow-addons`]: cli.md#--allow-addons
 [`--allow-child-process`]: cli.md#--allow-child-process
 [`--allow-env`]: cli.md#--allow-env
diff --git a/doc/api/sqlite.md b/doc/api/sqlite.md
index 422df94ea54..05a5d27040e 100644
--- a/doc/api/sqlite.md
+++ b/doc/api/sqlite.md
@@ -218,7 +218,9 @@ changes:
 * `path` {string | Buffer | URL} The path of the database. A SQLite database can be
   stored in a file or completely [in memory][]. To use a file-backed database,
   the path should be a file path. To use an in-memory database, the path
-  should be the special name `':memory:'`.
+  should be the special name `':memory:'`. When the [Permission Model][] is
+  enabled, {URL} objects and [URI filenames][] (paths starting with `file:`)
+  are not supported and an exception is thrown.
 * `options` {Object} Configuration options for the database connection. The
   following options are supported:
   * `open` {boolean} If `true`, the database is opened by the constructor. When
@@ -1856,7 +1858,8 @@ changes:

 * `sourceDb` {Database} The database to backup. The source database must be open.
 * `path` {string | Buffer | URL} The path where the backup will be created. If the file already exists,
-  the contents will be overwritten.
+  the contents will be overwritten. When the [Permission Model][] is enabled, {URL} objects and
+  [URI filenames][] (paths starting with `file:`) are not supported and an exception is thrown.
 * `options` {Object} Optional configuration for the backup. The
   following properties are supported:
   * `source` {string} Name of the source database. This can be `'main'` (the default primary database) or any other
@@ -2160,9 +2163,11 @@ callback function to indicate what type of operation is being authorized.
 [Constants Passed To The Conflict Handler]: https://www.sqlite.org/session/c_changeset_conflict.html
 [Constants Returned From The Conflict Handler]: https://www.sqlite.org/session/c_changeset_abort.html
 [Limit Constants]: https://www.sqlite.org/c3ref/c_limit_attached.html
+[Permission Model]: permissions.md#permission-model
 [Run-Time Limits]: https://www.sqlite.org/c3ref/limit.html
 [SQL injection]: https://en.wikipedia.org/wiki/SQL_injection
 [Type conversion between JavaScript and SQLite]: #type-conversion-between-javascript-and-sqlite
+[URI filenames]: https://www.sqlite.org/uri.html
 [Writing numbers and BigInts]: #writing-numbers-and-bigints
 [`'sqlite.db.query'`]: diagnostics_channel.md#event-sqlitedbquery
 [`ATTACH DATABASE`]: https://www.sqlite.org/lang_attach.html
diff --git a/node.gyp b/node.gyp
index 8dc598dc402..009c3f7b36f 100644
--- a/node.gyp
+++ b/node.gyp
@@ -501,8 +501,10 @@
     ],
     'node_sqlite_sources': [
       'src/node_sqlite.cc',
+      'src/node_sqlite_vfs.cc',
       'src/node_webstorage.cc',
       'src/node_sqlite.h',
+      'src/node_sqlite_vfs.h',
       'src/node_webstorage.h',
     ],
     'node_ffi_sources': [
diff --git a/src/node_sqlite.cc b/src/node_sqlite.cc
index c69975b701a..59f7dd5818b 100644
--- a/src/node_sqlite.cc
+++ b/src/node_sqlite.cc
@@ -374,6 +374,8 @@ inline void THROW_ERR_SQLITE_ERROR(Isolate* isolate, Database* db) {
     }
   }

+  if (db->ThrowIfPermissionDenied()) return;
+
   Local<Object> e;
   if (CreateSQLiteError(isolate, db->Connection()).ToLocal(&e)) {
     isolate->ThrowException(e);
@@ -625,6 +627,7 @@ class BackupJob : public ThreadPoolWork {
                      std::string source_db,
                      std::string destination_name,
                      std::string dest_db,
+                     std::shared_ptr<SQLitePermissionVFS> permission_vfs,
                      int pages,
                      Local<Function> progressFunc)
       : ThreadPoolWork(env, ThreadPoolWorkType::kSQLiteBackup),
@@ -633,7 +636,8 @@ class BackupJob : public ThreadPoolWork {
         pages_(pages),
         source_db_(std::move(source_db)),
         destination_name_(std::move(destination_name)),
-        dest_db_(std::move(dest_db)) {
+        dest_db_(std::move(dest_db)),
+        permission_vfs_(std::move(permission_vfs)) {
     resolver_.Reset(env->isolate(), resolver);
     progressFunc_.Reset(env->isolate(), progressFunc);
   }
@@ -645,13 +649,16 @@ class BackupJob : public ThreadPoolWork {
     backup_status_ = sqlite3_open_v2(
         destination_name_.c_str(),
         &dest_raw,
-        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI,
-        nullptr);
+        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
+            (permission_vfs_ == nullptr ? SQLITE_OPEN_URI : 0),
+        permission_vfs_ == nullptr ? nullptr : permission_vfs_->name().c_str());
     dest_.reset(dest_raw);
     Local<Promise::Resolver> resolver =
         Local<Promise::Resolver>::New(env()->isolate(), resolver_);
     if (backup_status_ != SQLITE_OK) {
-      Settle(resolver, CreateSQLiteError(isolate, dest_.get()), {});
+      Settle(resolver,
+             PermissionErrorOr(CreateSQLiteError(isolate, dest_.get())),
+             {});
       return;
     }

@@ -682,7 +689,9 @@ class BackupJob : public ThreadPoolWork {

     if (!(backup_status_ == SQLITE_OK || backup_status_ == SQLITE_DONE ||
           backup_status_ == SQLITE_BUSY || backup_status_ == SQLITE_LOCKED)) {
-      Settle(resolver, CreateSQLiteError(isolate, backup_status_), {});
+      Settle(resolver,
+             PermissionErrorOr(CreateSQLiteError(isolate, backup_status_)),
+             {});
       return;
     }

@@ -749,9 +758,21 @@ class BackupJob : public ThreadPoolWork {
       backup_status_ = sqlite3_errcode(dest_.get());
       dest_.reset();
     }
+
+    permission_vfs_.reset();
   }

  private:
+  MaybeLocal<Value> PermissionErrorOr(MaybeLocal<Object> sqlite_error) {
+    if (permission_vfs_ != nullptr) {
+      if (auto denied = permission_vfs_->TakeDenied(backup_status_)) {
+        return permission::CreateAccessDeniedError(
+            env(), denied->scope, denied->path);
+      }
+    }
+    return sqlite_error;
+  }
+
   // The single exit point of a backup. Rejects with `error` if it is set,
   // otherwise resolves with `value` if it is set. Neither being set means an
   // exception is already pending. Deletes the job.
@@ -781,6 +802,7 @@ class BackupJob : public ThreadPoolWork {
   std::string source_db_;
   std::string destination_name_;
   std::string dest_db_;
+  std::shared_ptr<SQLitePermissionVFS> permission_vfs_;
 };

 UserDefinedFunction::UserDefinedFunction(Environment* env,
@@ -1620,12 +1642,47 @@ void Database::MemoryInfo(MemoryTracker* tracker) const {
       "open_config", sizeof(open_config_), "DatabaseOpenConfiguration");
 }

+bool Database::ThrowIfPermissionDenied() {
+  if (permission_vfs_ == nullptr) return false;
+  auto denied = permission_vfs_->TakeDenied(sqlite3_errcode(connection_.get()));
+  if (!denied) return false;
+  permission::Permission::ThrowAccessDenied(env(), denied->scope, denied->path);
+  return true;
+}
+
 bool Database::Open() {
   if (IsOpen()) {
     THROW_ERR_INVALID_STATE(env(), "database is already open");
     return false;
   }

+  // An anonymous temporary database has no path for the VFS to check.
+  if (open_config_.location().empty()) {
+    THROW_IF_INSUFFICIENT_PERMISSIONS(
+        env(), permission::PermissionScope::kFileSystemRead, "", false);
+    if (!open_config_.get_read_only()) {
+      THROW_IF_INSUFFICIENT_PERMISSIONS(
+          env(), permission::PermissionScope::kFileSystemWrite, "", false);
+    }
+  }
+
+  if (env()->permission()->enabled()) {
+    // Connections of the same Environment share one permission VFS.
+    BindingData* binding =
+        env()->principal_realm()->GetBindingData<BindingData>();
+    if (binding != nullptr) permission_vfs_ = binding->permission_vfs.lock();
+    if (permission_vfs_ == nullptr) {
+      permission_vfs_ = std::make_shared<SQLitePermissionVFS>(env());
+      if (!permission_vfs_->Register()) {
+        THROW_ERR_SQLITE_ERROR(env()->isolate(),
+                               "Unable to register the SQLite permission VFS");
+        permission_vfs_.reset();
+        return false;
+      }
+      if (binding != nullptr) binding->permission_vfs = permission_vfs_;
+    }
+  }
+
   // sqlite3_open_v2() assigns a database handle even when it fails. Such a
   // handle is in a "sick" state and may only be used to retrieve the error
   // and must then be released with sqlite3_close(). Close and reset the
@@ -1635,19 +1692,23 @@ bool Database::Open() {
   auto reset_connection_on_failure = OnScopeLeave([&]() {
     if (!opened) {
       connection_.reset();
+      permission_vfs_.reset();
     }
   });

   // TODO(cjihrig): Support additional flags.
-  int default_flags = SQLITE_OPEN_URI;
+  // TODO(araujogui): Support URI filenames with the permission model. A URI
+  // could select another VFS, bypassing the permission VFS.
+  int default_flags = permission_vfs_ == nullptr ? SQLITE_OPEN_URI : 0;
   int flags = open_config_.get_read_only()
                   ? SQLITE_OPEN_READONLY
                   : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
   sqlite3* raw_conn = nullptr;
-  int r = sqlite3_open_v2(open_config_.location().c_str(),
-                          &raw_conn,
-                          flags | default_flags,
-                          nullptr);
+  int r = sqlite3_open_v2(
+      open_config_.location().c_str(),
+      &raw_conn,
+      flags | default_flags,
+      permission_vfs_ == nullptr ? nullptr : permission_vfs_->name().c_str());
   connection_.reset(raw_conn);
   CHECK_ERROR_OR_THROW(env()->isolate(), this, r, SQLITE_OK, false);

@@ -1881,10 +1942,22 @@ std::optional<std::string> ValidateDatabasePath(Environment* env,
   constexpr auto has_null_bytes = [](std::string_view str) {
     return str.find('\0') != std::string_view::npos;
   };
+  // Without SQLITE_OPEN_URI, SQLite would open a file named "file:...".
+  const auto reject_uri = [&](std::string value) -> std::optional<std::string> {
+    if (env->permission()->enabled() && value.starts_with("file:")) {
+      THROW_ERR_INVALID_ARG_VALUE(
+          env->isolate(),
+          "The \"%s\" argument must not be a URL or SQLite URI filename when "
+          "the permission model is enabled.",
+          field_name);
+      return std::nullopt;
+    }
+    return value;
+  };
   if (path->IsString()) {
     Utf8Value location(env->isolate(), path.As<String>());
     if (!has_null_bytes(location.ToStringView())) {
-      return location.ToString();
+      return reject_uri(location.ToString());
     }
   } else if (path->IsUint8Array()) {
     Local<Uint8Array> buffer = path.As<Uint8Array>();
@@ -1893,7 +1966,8 @@ std::optional<std::string> ValidateDatabasePath(Environment* env,
     auto data =
         static_cast<const uint8_t*>(buffer->Buffer()->Data()) + byteOffset;
     if (std::find(data, data + byteLength, 0) == data + byteLength) {
-      return std::string(reinterpret_cast<const char*>(data), byteLength);
+      return reject_uri(
+          std::string(reinterpret_cast<const char*>(data), byteLength));
     }
   } else if (path->IsObject()) {  // When is URL
     auto url = path.As<Object>();
@@ -1913,7 +1987,7 @@ std::optional<std::string> ValidateDatabasePath(Environment* env,
           return std::nullopt;
         }

-        return location_value.ToString();
+        return reject_uri(location_value.ToString());
       }
     }
   }
@@ -2120,6 +2194,7 @@ void Database::Close(const FunctionCallbackInfo<Value>& args) {
   int r = sqlite3_close_v2(db->connection_.get());
   CHECK_ERROR_OR_THROW(env->isolate(), db, r, SQLITE_OK, void());
   db->connection_.release();
+  db->permission_vfs_.reset();
   // Backups can defer SQLite destruction until after the connection is closed.
   db->user_defined_functions_.clear();
 }
@@ -2963,6 +3038,7 @@ void Backup(const FunctionCallbackInfo<Value>& args) {
                                  std::move(source_db),
                                  dest_path.value(),
                                  std::move(dest_db),
+                                 db->PermissionVFS(),
                                  rate,
                                  progressFunc);
   db->AddBackup(job);
@@ -3249,9 +3325,8 @@ void Database::SetAuthorizer(const FunctionCallbackInfo<Value>& args) {
   Isolate* isolate = env->isolate();

   if (args[0]->IsNull()) {
-    // Clear the authorizer
-    sqlite3_set_authorizer(db->connection_.get(), nullptr, nullptr);
     db->object()->SetInternalField(kAuthorizerCallback, Null(isolate));
+    sqlite3_set_authorizer(db->connection_.get(), nullptr, nullptr);
     return;
   }

diff --git a/src/node_sqlite.h b/src/node_sqlite.h
index a706f7dad6e..460e9a4a8bc 100644
--- a/src/node_sqlite.h
+++ b/src/node_sqlite.h
@@ -6,6 +6,7 @@
 #include "base_object.h"
 #include "lru_cache-inl.h"
 #include "node_mem.h"
+#include "node_sqlite_vfs.h"
 #include "sqlite3.h"
 #include "util.h"

@@ -13,6 +14,7 @@
 #include <array>
 #include <list>
 #include <map>
+#include <memory>
 #include <optional>
 #include <string_view>
 #include <unordered_set>
@@ -212,6 +214,7 @@ class BindingData : public BaseObject {
   SET_SELF_SIZE(BindingData)

   std::unordered_set<Database*> open_databases;
+  std::weak_ptr<SQLitePermissionVFS> permission_vfs;

   static void CreatePerContextProperties(v8::Local<v8::Object> target,
                                          v8::Local<v8::Value> unused,
@@ -290,6 +293,11 @@ class Database : public BaseObject {
   }
   sqlite3* Connection();
   void SetLimit(int sqlite_limit_id, int value);
+  std::shared_ptr<SQLitePermissionVFS> PermissionVFS() const {
+    return permission_vfs_;
+  }
+  // Throws the permission error if the permission VFS caused the last failure.
+  bool ThrowIfPermissionDenied();

   // In some situations, such as when using custom functions, it is possible
   // that SQLite reports an error while JavaScript already has a pending
@@ -356,6 +364,7 @@ class Database : public BaseObject {
   int authorizer_depth_ = 0;
   int trace_suppression_depth_ = 0;
   std::vector<sqlite3_stmt*> stepping_statements_;
+  std::shared_ptr<SQLitePermissionVFS> permission_vfs_;

   // SQLite owns these scalar and aggregate/window function registrations. Its
   // destroy callbacks untrack replaced functions and failed registrations.
diff --git a/src/node_sqlite_vfs.cc b/src/node_sqlite_vfs.cc
new file mode 100644
index 00000000000..5ed919c7c64
--- /dev/null
+++ b/src/node_sqlite_vfs.cc
@@ -0,0 +1,671 @@
+#include "node_sqlite_vfs.h"
+
+#include "env-inl.h"
+#include "path.h"
+#include "permission/permission.h"
+
+#include <algorithm>
+#include <atomic>
+#include <cctype>
+#include <cstring>
+#include <string>
+#include <string_view>
+#include <utility>
+
+namespace node {
+namespace sqlite {
+
+namespace {
+
+std::atomic<uint64_t> next_vfs_id{0};
+
+bool IsSidecarPath(std::string_view path, std::string* database_path) {
+  constexpr std::string_view suffixes[] = {"-journal", "-wal", "-shm"};
+  for (const std::string_view suffix : suffixes) {
+    if (path.size() > suffix.size() && path.ends_with(suffix)) {
+      *database_path = path.substr(0, path.size() - suffix.size());
+      return true;
+    }
+  }
+
+  // SQLite names super-journals as <database>-mjXXXXXX9XX, where X is a hex
+  // digit (see pagerIsSuperJrnlName()). A permission granted for the
+  // database also covers its super-journal.
+  constexpr size_t kSuperJournalSuffixLength = 12;
+  if (path.size() > kSuperJournalSuffixLength) {
+    const std::string_view suffix =
+        path.substr(path.size() - kSuperJournalSuffixLength);
+    if (suffix.starts_with("-mj") && suffix[9] == '9' &&
+        std::all_of(suffix.begin() + 3, suffix.end(), [](char c) {
+          return std::isxdigit(static_cast<unsigned char>(c));
+        })) {
+      *database_path = path.substr(0, path.size() - suffix.size());
+      return true;
+    }
+  }
+
+  return false;
+}
+
+sqlite3_filename CreateReadOnlyShmFilename(sqlite3_filename name) {
+  const char* parameters[] = {"readonly_shm", "1"};
+  return sqlite3_create_filename(sqlite3_filename_database(name),
+                                 sqlite3_filename_journal(name),
+                                 sqlite3_filename_wal(name),
+                                 1,
+                                 parameters);
+}
+
+std::string CanonicalPath(const SQLitePermissionVFS* vfs, const char* path) {
+  // SQLite normally passes a full pathname to xOpen, but xAccess and xDelete
+  // may receive names produced by SQLite itself. Canonicalize those names
+  // before consulting Node's path permission tree.
+  std::string result(static_cast<size_t>(vfs->parent()->mxPathname) + 1, '\0');
+  if (vfs->FullPathname(path, static_cast<int>(result.size()), result.data()) !=
+      SQLITE_OK) {
+    return {};
+  }
+  result.resize(strlen(result.c_str()));
+  return result;
+}
+
+struct PermissionFile {
+  sqlite3_file base;
+  SQLitePermissionVFS* vfs;
+  // Read-only SHM clone of the filename, set when sidecars are not writable.
+  sqlite3_filename parent_name;
+  bool can_write;
+  bool can_write_sidecar;
+  sqlite3_io_methods methods;
+};
+
+sqlite3_file* RealFile(PermissionFile* file) {
+  return reinterpret_cast<sqlite3_file*>(reinterpret_cast<char*>(file) +
+                                         sizeof(PermissionFile));
+}
+
+PermissionFile* PermissionFileFromBase(sqlite3_file* file) {
+  return reinterpret_cast<PermissionFile*>(file);
+}
+
+void ReleaseFile(PermissionFile* file) {
+  sqlite3_free_filename(file->parent_name);
+  file->parent_name = nullptr;
+  file->base.pMethods = nullptr;
+}
+
+int PermissionClose(sqlite3_file* file);
+int PermissionRead(sqlite3_file*, void*, int, sqlite3_int64);
+int PermissionWrite(sqlite3_file*, const void*, int, sqlite3_int64);
+int PermissionTruncate(sqlite3_file*, sqlite3_int64);
+int PermissionSync(sqlite3_file*, int);
+int PermissionFileSize(sqlite3_file*, sqlite3_int64*);
+int PermissionLock(sqlite3_file*, int);
+int PermissionUnlock(sqlite3_file*, int);
+int PermissionCheckReservedLock(sqlite3_file*, int*);
+int PermissionFileControl(sqlite3_file*, int, void*);
+int PermissionSectorSize(sqlite3_file*);
+int PermissionDeviceCharacteristics(sqlite3_file*);
+int PermissionShmMap(sqlite3_file*, int, int, int, void volatile**);
+int PermissionShmLock(sqlite3_file*, int, int, int);
+void PermissionShmBarrier(sqlite3_file*);
+int PermissionShmUnmap(sqlite3_file*, int);
+int PermissionFetch(sqlite3_file*, sqlite3_int64, int, void**);
+int PermissionUnfetch(sqlite3_file*, sqlite3_int64, void*);
+
+const sqlite3_io_methods kPermissionIoMethods = {
+    3,
+    PermissionClose,
+    PermissionRead,
+    PermissionWrite,
+    PermissionTruncate,
+    PermissionSync,
+    PermissionFileSize,
+    PermissionLock,
+    PermissionUnlock,
+    PermissionCheckReservedLock,
+    PermissionFileControl,
+    PermissionSectorSize,
+    PermissionDeviceCharacteristics,
+    PermissionShmMap,
+    PermissionShmLock,
+    PermissionShmBarrier,
+    PermissionShmUnmap,
+    PermissionFetch,
+    PermissionUnfetch,
+};
+
+int PermissionClose(sqlite3_file* file) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  const int result =
+      real->pMethods == nullptr ? SQLITE_OK : real->pMethods->xClose(real);
+  ReleaseFile(permission_file);
+  return result;
+}
+
+int PermissionRead(sqlite3_file* file,
+                   void* buffer,
+                   int amount,
+                   sqlite3_int64 offset) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  return real->pMethods->xRead(real, buffer, amount, offset);
+}
+
+int PermissionWrite(sqlite3_file* file,
+                    const void* buffer,
+                    int amount,
+                    sqlite3_int64 offset) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  if (!permission_file->can_write) return SQLITE_PERM;
+  sqlite3_file* real = RealFile(permission_file);
+  return real->pMethods->xWrite(real, buffer, amount, offset);
+}
+
+int PermissionTruncate(sqlite3_file* file, sqlite3_int64 size) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  if (!permission_file->can_write) return SQLITE_PERM;
+  sqlite3_file* real = RealFile(permission_file);
+  return real->pMethods->xTruncate(real, size);
+}
+
+int PermissionSync(sqlite3_file* file, int flags) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  if (!permission_file->can_write) return SQLITE_PERM;
+  sqlite3_file* real = RealFile(permission_file);
+  return real->pMethods->xSync(real, flags);
+}
+
+int PermissionFileSize(sqlite3_file* file, sqlite3_int64* size) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  return real->pMethods->xFileSize(real, size);
+}
+
+int PermissionLock(sqlite3_file* file, int lock) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  return real->pMethods->xLock(real, lock);
+}
+
+int PermissionUnlock(sqlite3_file* file, int lock) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  return real->pMethods->xUnlock(real, lock);
+}
+
+int PermissionCheckReservedLock(sqlite3_file* file, int* result) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  return real->pMethods->xCheckReservedLock(real, result);
+}
+
+bool FileControlRequiresWrite(int operation) {
+  switch (operation) {
+    case SQLITE_FCNTL_SIZE_HINT:
+    case SQLITE_FCNTL_OVERWRITE:
+    case SQLITE_FCNTL_SYNC:
+    case SQLITE_FCNTL_COMMIT_PHASETWO:
+    case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE:
+    case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE:
+    case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE:
+      return true;
+    default:
+      return false;
+  }
+}
+
+int PermissionFileControl(sqlite3_file* file, int operation, void* argument) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  if (FileControlRequiresWrite(operation) && !permission_file->can_write) {
+    return SQLITE_PERM;
+  }
+
+  if (operation == SQLITE_FCNTL_SET_LOCKPROXYFILE && argument != nullptr) {
+    const char* proxy_path = static_cast<const char*>(argument);
+    const bool allowed =
+        strcmp(proxy_path, ":auto:") == 0
+            ? permission_file->vfs->AllowsTemporaryFile(true, true)
+            : permission_file->vfs->AllowsPath(proxy_path, true, true);
+    if (!allowed) return SQLITE_PERM;
+  }
+
+  sqlite3_file* real = RealFile(permission_file);
+  return real->pMethods->xFileControl(real, operation, argument);
+}
+
+int PermissionSectorSize(sqlite3_file* file) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  return real->pMethods->xSectorSize(real);
+}
+
+int PermissionDeviceCharacteristics(sqlite3_file* file) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  return real->pMethods->xDeviceCharacteristics(real);
+}
+
+int PermissionShmMap(sqlite3_file* file,
+                     int page,
+                     int page_size,
+                     int extend,
+                     void volatile** result) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+
+  // OS VFS implementations can open or create the SHM file read-write even
+  // when extend is false. A read-only clone of the SQLite filename is used
+  // when the caller has no permission to write sidecars.
+  if (!permission_file->can_write_sidecar &&
+      permission_file->parent_name == nullptr) {
+    return SQLITE_PERM;
+  }
+
+  sqlite3_file* real = RealFile(permission_file);
+  if (real->pMethods->xShmMap == nullptr) return SQLITE_NOTFOUND;
+  return real->pMethods->xShmMap(real, page, page_size, extend, result);
+}
+
+int PermissionShmLock(sqlite3_file* file, int offset, int amount, int flags) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  if (real->pMethods->xShmLock == nullptr) return SQLITE_NOTFOUND;
+  return real->pMethods->xShmLock(real, offset, amount, flags);
+}
+
+void PermissionShmBarrier(sqlite3_file* file) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  if (real->pMethods->xShmBarrier != nullptr) {
+    real->pMethods->xShmBarrier(real);
+  }
+}
+
+int PermissionShmUnmap(sqlite3_file* file, int delete_flag) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  if (delete_flag && !permission_file->can_write_sidecar) return SQLITE_PERM;
+  sqlite3_file* real = RealFile(permission_file);
+  if (real->pMethods->xShmUnmap == nullptr) return SQLITE_NOTFOUND;
+  return real->pMethods->xShmUnmap(real, delete_flag);
+}
+
+int PermissionFetch(sqlite3_file* file,
+                    sqlite3_int64 offset,
+                    int amount,
+                    void** result) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  if (real->pMethods->xFetch == nullptr) {
+    *result = nullptr;
+    return SQLITE_OK;
+  }
+  return real->pMethods->xFetch(real, offset, amount, result);
+}
+
+int PermissionUnfetch(sqlite3_file* file, sqlite3_int64 offset, void* page) {
+  PermissionFile* permission_file = PermissionFileFromBase(file);
+  sqlite3_file* real = RealFile(permission_file);
+  if (real->pMethods->xUnfetch == nullptr) return SQLITE_OK;
+  return real->pMethods->xUnfetch(real, offset, page);
+}
+
+SQLitePermissionVFS* Self(sqlite3_vfs* vfs) {
+  return static_cast<SQLitePermissionVFS*>(vfs->pAppData);
+}
+
+int PermissionVfsOpen(sqlite3_vfs* vfs,
+                      sqlite3_filename name,
+                      sqlite3_file* file,
+                      int flags,
+                      int* out_flags) {
+  return Self(vfs)->Open(name, file, flags, out_flags);
+}
+
+int PermissionVfsDelete(sqlite3_vfs* vfs, const char* name, int sync_dir) {
+  return Self(vfs)->Delete(name, sync_dir);
+}
+
+int PermissionVfsAccess(sqlite3_vfs* vfs,
+                        const char* name,
+                        int flags,
+                        int* result) {
+  return Self(vfs)->Access(name, flags, result);
+}
+
+int PermissionVfsFullPathname(sqlite3_vfs* vfs,
+                              const char* name,
+                              int length,
+                              char* output) {
+  return Self(vfs)->FullPathname(name, length, output);
+}
+
+void* PermissionVfsDlOpen(sqlite3_vfs* vfs, const char* name) {
+  return Self(vfs)->DlOpen(name);
+}
+
+void PermissionVfsDlError(sqlite3_vfs* vfs, int length, char* message) {
+  sqlite3_vfs* parent = Self(vfs)->parent();
+  if (parent->xDlError != nullptr) parent->xDlError(parent, length, message);
+}
+
+using DlSymResult = void (*)(void);
+DlSymResult PermissionVfsDlSym(sqlite3_vfs* vfs,
+                               void* handle,
+                               const char* symbol) {
+  sqlite3_vfs* parent = Self(vfs)->parent();
+  return parent->xDlSym == nullptr ? nullptr
+                                   : parent->xDlSym(parent, handle, symbol);
+}
+
+void PermissionVfsDlClose(sqlite3_vfs* vfs, void* handle) {
+  sqlite3_vfs* parent = Self(vfs)->parent();
+  if (parent->xDlClose != nullptr) parent->xDlClose(parent, handle);
+}
+
+int PermissionVfsRandomness(sqlite3_vfs* vfs, int length, char* output) {
+  sqlite3_vfs* parent = Self(vfs)->parent();
+  return parent->xRandomness(parent, length, output);
+}
+
+int PermissionVfsSleep(sqlite3_vfs* vfs, int microseconds) {
+  sqlite3_vfs* parent = Self(vfs)->parent();
+  return parent->xSleep(parent, microseconds);
+}
+
+int PermissionVfsCurrentTime(sqlite3_vfs* vfs, double* time) {
+  sqlite3_vfs* parent = Self(vfs)->parent();
+  return parent->xCurrentTime(parent, time);
+}
+
+int PermissionVfsGetLastError(sqlite3_vfs* vfs, int length, char* message) {
+  sqlite3_vfs* parent = Self(vfs)->parent();
+  return parent->xGetLastError == nullptr
+             ? SQLITE_OK
+             : parent->xGetLastError(parent, length, message);
+}
+
+int PermissionVfsCurrentTimeInt64(sqlite3_vfs* vfs, sqlite3_int64* time) {
+  sqlite3_vfs* parent = Self(vfs)->parent();
+  return parent->xCurrentTimeInt64(parent, time);
+}
+
+int PermissionVfsSetSystemCall(sqlite3_vfs* vfs,
+                               const char* name,
+                               sqlite3_syscall_ptr callback) {
+  sqlite3_vfs* parent = Self(vfs)->parent();
+  return parent->xSetSystemCall(parent, name, callback);
+}
+
+sqlite3_syscall_ptr PermissionVfsGetSystemCall(sqlite3_vfs* vfs,
+                                               const char* name) {
+  sqlite3_vfs* parent = Self(vfs)->parent();
+  return parent->xGetSystemCall(parent, name);
+}
+
+const char* PermissionVfsNextSystemCall(sqlite3_vfs* vfs, const char* name) {
+  sqlite3_vfs* parent = Self(vfs)->parent();
+  return parent->xNextSystemCall(parent, name);
+}
+
+}  // namespace
+
+SQLitePermissionVFS::SQLitePermissionVFS(Environment* env)
+    : parent_(sqlite3_vfs_find(nullptr)),
+      memory_vfs_(sqlite3_vfs_find("memdb")),
+      env_(env),
+      permission_(env->permission()),
+      name_("node-permission-" + std::to_string(++next_vfs_id)) {
+  CHECK_NOT_NULL(parent_);
+  CHECK_NOT_NULL(memory_vfs_);
+
+  vfs_.iVersion = parent_->iVersion;
+  vfs_.szOsFile = sizeof(PermissionFile) +
+                  std::max(parent_->szOsFile, memory_vfs_->szOsFile);
+  vfs_.mxPathname = parent_->mxPathname;
+  vfs_.zName = name_.c_str();
+  vfs_.pAppData = this;
+  vfs_.xOpen = PermissionVfsOpen;
+  vfs_.xDelete = PermissionVfsDelete;
+  vfs_.xAccess = PermissionVfsAccess;
+  vfs_.xFullPathname = PermissionVfsFullPathname;
+  vfs_.xDlOpen = PermissionVfsDlOpen;
+  vfs_.xDlError = PermissionVfsDlError;
+  vfs_.xDlSym = PermissionVfsDlSym;
+  vfs_.xDlClose = PermissionVfsDlClose;
+  vfs_.xRandomness = PermissionVfsRandomness;
+  vfs_.xSleep = PermissionVfsSleep;
+  vfs_.xCurrentTime = PermissionVfsCurrentTime;
+  vfs_.xGetLastError = PermissionVfsGetLastError;
+  vfs_.xCurrentTimeInt64 = parent_->xCurrentTimeInt64 == nullptr
+                               ? nullptr
+                               : PermissionVfsCurrentTimeInt64;
+  vfs_.xSetSystemCall =
+      parent_->xSetSystemCall == nullptr ? nullptr : PermissionVfsSetSystemCall;
+  vfs_.xGetSystemCall =
+      parent_->xGetSystemCall == nullptr ? nullptr : PermissionVfsGetSystemCall;
+  vfs_.xNextSystemCall = parent_->xNextSystemCall == nullptr
+                             ? nullptr
+                             : PermissionVfsNextSystemCall;
+}
+
+SQLitePermissionVFS::~SQLitePermissionVFS() {
+  if (registered_) sqlite3_vfs_unregister(&vfs_);
+}
+
+bool SQLitePermissionVFS::Register() {
+  if (registered_) return true;
+  registered_ = sqlite3_vfs_register(&vfs_, 0) == SQLITE_OK;
+  return registered_;
+}
+
+bool SQLitePermissionVFS::AllowsCanonicalPath(std::string_view path,
+                                              bool read,
+                                              bool write) const {
+  // Called on SQLite worker threads too, so denials are not published.
+  return (!read ||
+          permission_->is_granted_quiet(
+              env_, permission::PermissionScope::kFileSystemRead, path)) &&
+         (!write ||
+          permission_->is_granted_quiet(
+              env_, permission::PermissionScope::kFileSystemWrite, path));
+}
+
+bool SQLitePermissionVFS::AllowsPath(const char* path,
+                                     bool read,
+                                     bool write) const {
+  if (permission_->warning_only()) return true;
+
+  const std::string canonical = CanonicalPath(this, path);
+  return !canonical.empty() && AllowsCanonicalPath(canonical, read, write);
+}
+
+bool SQLitePermissionVFS::AllowsSidecarPath(const char* path,
+                                            bool read,
+                                            bool write) const {
+  if (permission_->warning_only()) return true;
+
+  const std::string canonical = CanonicalPath(this, path);
+  if (canonical.empty()) return false;
+  if (AllowsCanonicalPath(canonical, read, write)) return true;
+
+  std::string database_path;
+  return IsSidecarPath(canonical, &database_path) &&
+         AllowsCanonicalPath(database_path, read, write);
+}
+
+bool SQLitePermissionVFS::AllowsDatabase(const char* path,
+                                         bool read,
+                                         bool write) {
+  using permission::PermissionScope;
+  const std::string canonical = CanonicalPath(this, path);
+  if (!canonical.empty()) {
+    const auto denied = [&](PermissionScope scope) {
+      return !permission_->is_granted_quiet(env_, scope, canonical);
+    };
+    PermissionScope scope;
+    if (read && denied(PermissionScope::kFileSystemRead)) {
+      scope = PermissionScope::kFileSystemRead;
+    } else if (write && denied(PermissionScope::kFileSystemWrite)) {
+      scope = PermissionScope::kFileSystemWrite;
+    } else {
+      return true;
+    }
+
+    if (!permission_->warning_only()) {
+      Mutex::ScopedLock lock(denied_mutex_);
+      denied_ = Denial{scope, canonical};
+    }
+    // SQLite calls the VFS on worker threads and while it must not be
+    // reentered, so the denial is published later, from the main thread.
+    env_->SetImmediateThreadsafe([scope, canonical](Environment* env) {
+      env->permission()->PublishDenied(env, scope, canonical);
+    });
+  }
+  return permission_->warning_only();
+}
+
+std::optional<SQLitePermissionVFS::Denial> SQLitePermissionVFS::TakeDenied(
+    int errcode) {
+  Mutex::ScopedLock lock(denied_mutex_);
+  std::optional<Denial> denied = std::exchange(denied_, std::nullopt);
+  // Dropped on any other error so that it is not reported for a later one.
+  return (errcode & 0xff) == SQLITE_PERM ? denied : std::nullopt;
+}
+
+bool SQLitePermissionVFS::AllowsTemporaryFile(bool read, bool write) const {
+  // SQLite does not provide a pathname for anonymous temporary files. Disk
+  // storage is allowed only with global permissions. Otherwise xOpen uses
+  // SQLite's memory VFS.
+  return permission_->warning_only() || AllowsCanonicalPath("", read, write);
+}
+
+int SQLitePermissionVFS::Open(sqlite3_filename name,
+                              sqlite3_file* file,
+                              int flags,
+                              int* out_flags) {
+  auto* permission_file = reinterpret_cast<PermissionFile*>(file);
+  memset(permission_file, 0, vfs_.szOsFile);
+  permission_file->vfs = this;
+
+  const bool read =
+      (flags & (SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE)) != 0;
+  bool write = (flags & SQLITE_OPEN_READWRITE) != 0;
+  int parent_flags = flags;
+  sqlite3_vfs* selected_vfs = parent_;
+  bool can_write_sidecar = write;
+
+  if (flags & SQLITE_OPEN_MEMORY) {
+    selected_vfs = memory_vfs_;
+  } else if (name == nullptr) {
+    if (!AllowsTemporaryFile(read, write)) selected_vfs = memory_vfs_;
+  } else {
+    const char* permission_name = name;
+    const bool is_journal =
+        flags & (SQLITE_OPEN_MAIN_JOURNAL | SQLITE_OPEN_WAL);
+    if (is_journal) {
+      permission_name = sqlite3_filename_database(name);
+      sqlite3_file* database_file = sqlite3_database_file_object(name);
+      if (database_file != nullptr &&
+          !PermissionFileFromBase(database_file)->can_write_sidecar) {
+        write = false;
+        parent_flags &= ~(SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
+        parent_flags |= SQLITE_OPEN_READONLY;
+      }
+    }
+
+    // A denied journal implies a denied database, which was reported when
+    // the database was opened.
+    const bool allowed =
+        permission_name != nullptr &&
+        ((flags & SQLITE_OPEN_SUPER_JOURNAL)
+             ? AllowsSidecarPath(permission_name, read, write)
+         : is_journal ? AllowsPath(permission_name, read, write)
+                      : AllowsDatabase(permission_name, read, write));
+    if (!allowed) return SQLITE_PERM;
+
+    if (flags & SQLITE_OPEN_MAIN_DB) {
+      can_write_sidecar = write || AllowsPath(permission_name, false, true);
+      if (!can_write_sidecar) {
+        permission_file->parent_name = CreateReadOnlyShmFilename(name);
+        if (permission_file->parent_name == nullptr) return SQLITE_NOMEM;
+      }
+    }
+  }
+
+  sqlite3_filename parent_name = permission_file->parent_name == nullptr
+                                     ? name
+                                     : permission_file->parent_name;
+  sqlite3_file* real = RealFile(permission_file);
+  const int result = selected_vfs->xOpen(
+      selected_vfs, parent_name, real, parent_flags, out_flags);
+  if (real->pMethods == nullptr) {
+    ReleaseFile(permission_file);
+    return result;
+  }
+
+  permission_file->can_write =
+      write &&
+      (out_flags == nullptr || (*out_flags & SQLITE_OPEN_READONLY) == 0);
+  permission_file->can_write_sidecar = can_write_sidecar;
+  permission_file->methods = kPermissionIoMethods;
+  permission_file->methods.iVersion =
+      std::min(permission_file->methods.iVersion, real->pMethods->iVersion);
+  if (permission_file->methods.iVersion < 2) {
+    permission_file->methods.xShmMap = nullptr;
+    permission_file->methods.xShmLock = nullptr;
+    permission_file->methods.xShmBarrier = nullptr;
+    permission_file->methods.xShmUnmap = nullptr;
+  }
+  if (permission_file->methods.iVersion < 3) {
+    permission_file->methods.xFetch = nullptr;
+    permission_file->methods.xUnfetch = nullptr;
+  }
+  file->pMethods = &permission_file->methods;
+  return result;
+}
+
+int SQLitePermissionVFS::Delete(const char* name, int sync_dir) {
+  if (name == nullptr || !AllowsSidecarPath(name, false, true)) {
+    return SQLITE_PERM;
+  }
+  return parent_->xDelete(parent_, name, sync_dir);
+}
+
+int SQLitePermissionVFS::Access(const char* name, int flags, int* result) {
+  if (name == nullptr) {
+    *result = 0;
+    return SQLITE_OK;
+  }
+
+  if (!AllowsSidecarPath(name, true, flags == SQLITE_ACCESS_READWRITE)) {
+    *result = 0;
+    return SQLITE_OK;
+  }
+  return parent_->xAccess(parent_, name, flags, result);
+}
+
+int SQLitePermissionVFS::FullPathname(const char* name,
+                                      int length,
+                                      char* output) const {
+#ifdef _WIN32
+  return parent_->xFullPathname(parent_, name, length, output);
+#else
+  // The parent VFS also resolves symbolic links, but the permission model
+  // checks lexically resolved paths. Resolve the same way so that the path
+  // SQLite opens is the path that was checked.
+  const std::string resolved = PathResolve(env_, {name});
+  if (resolved.size() >= static_cast<size_t>(length)) return SQLITE_CANTOPEN;
+  memcpy(output, resolved.c_str(), resolved.size() + 1);
+  return SQLITE_OK;
+#endif
+}
+
+void* SQLitePermissionVFS::DlOpen(const char* name) {
+  if (!permission_->warning_only()) return nullptr;
+  return parent_->xDlOpen == nullptr ? nullptr
+                                     : parent_->xDlOpen(parent_, name);
+}
+
+}  // namespace sqlite
+}  // namespace node
diff --git a/src/node_sqlite_vfs.h b/src/node_sqlite_vfs.h
new file mode 100644
index 00000000000..23757d8fdfd
--- /dev/null
+++ b/src/node_sqlite_vfs.h
@@ -0,0 +1,77 @@
+#ifndef SRC_NODE_SQLITE_VFS_H_
+#define SRC_NODE_SQLITE_VFS_H_
+
+#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
+
+#include "node_mutex.h"
+#include "permission/permission_base.h"
+#include "sqlite3.h"
+
+#include <optional>
+#include <string>
+#include <string_view>
+
+namespace node {
+
+class Environment;
+
+namespace permission {
+class Permission;
+}
+
+namespace sqlite {
+
+class SQLitePermissionVFS {
+ public:
+  struct Denial {
+    permission::PermissionScope scope;
+    std::string path;
+  };
+
+  explicit SQLitePermissionVFS(Environment* env);
+  ~SQLitePermissionVFS();
+
+  SQLitePermissionVFS(const SQLitePermissionVFS&) = delete;
+  SQLitePermissionVFS& operator=(const SQLitePermissionVFS&) = delete;
+
+  bool Register();
+
+  const std::string& name() const { return name_; }
+  sqlite3_vfs* parent() const { return parent_; }
+
+  int Open(sqlite3_filename name,
+           sqlite3_file* file,
+           int flags,
+           int* out_flags);
+  int Delete(const char* name, int sync_dir);
+  int Access(const char* name, int flags, int* result);
+  int FullPathname(const char* name, int length, char* output) const;
+  void* DlOpen(const char* name);
+
+  // The denial behind a failed SQLite call, if errcode is SQLITE_PERM.
+  std::optional<Denial> TakeDenied(int errcode);
+
+  bool AllowsPath(const char* path, bool read, bool write) const;
+  bool AllowsTemporaryFile(bool read, bool write) const;
+
+ private:
+  bool AllowsSidecarPath(const char* path, bool read, bool write) const;
+  bool AllowsDatabase(const char* path, bool read, bool write);
+  bool AllowsCanonicalPath(std::string_view path, bool read, bool write) const;
+
+  sqlite3_vfs vfs_{};
+  sqlite3_vfs* parent_ = nullptr;
+  sqlite3_vfs* memory_vfs_ = nullptr;
+  Environment* env_ = nullptr;
+  permission::Permission* permission_ = nullptr;
+  std::string name_;
+  bool registered_ = false;
+  Mutex denied_mutex_;
+  std::optional<Denial> denied_;
+};
+
+}  // namespace sqlite
+}  // namespace node
+
+#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
+#endif  // SRC_NODE_SQLITE_VFS_H_
diff --git a/test/fixtures/permission/sqlite.db b/test/fixtures/permission/sqlite.db
new file mode 100644
index 00000000000..2321b9eac82
Binary files /dev/null and b/test/fixtures/permission/sqlite.db differ
diff --git a/test/parallel/test-permission-sqlite.js b/test/parallel/test-permission-sqlite.js
new file mode 100644
index 00000000000..a7c6f45a844
--- /dev/null
+++ b/test/parallel/test-permission-sqlite.js
@@ -0,0 +1,305 @@
+// Flags: --permission --allow-fs-read=* --allow-fs-write=* --allow-child-process
+'use strict';
+
+const common = require('../common');
+common.skipIfSQLiteMissing();
+
+const { isMainThread } = require('node:worker_threads');
+
+if (!isMainThread) {
+  common.skip('This test only works on a main thread');
+}
+
+const assert = require('node:assert');
+const fs = require('node:fs');
+const { DatabaseSync } = require('node:sqlite');
+const { spawnSyncAndAssert } = require('../common/child_process');
+const fixtures = require('../common/fixtures');
+const tmpdir = require('../common/tmpdir');
+
+tmpdir.refresh();
+
+const dbPath = fixtures.path('permission', 'sqlite.db');
+const deniedPath = tmpdir.resolve('denied.sqlite');
+const backupPath = tmpdir.resolve('backup.sqlite');
+const allowedBackupPath = tmpdir.resolve('allowed-backup.sqlite');
+const sidecarDbPath = tmpdir.resolve('sidecars.sqlite');
+const walDbPath = tmpdir.resolve('read-only-wal.sqlite');
+const suffixDbPath = dbPath + '-wal';
+
+fs.rmSync(suffixDbPath, { force: true });
+
+const accessDenied = {
+  status: 1,
+  stderr: /Access to this API has been restricted/,
+};
+
+function readWriteGrant(path) {
+  return ['--allow-fs-read=' + path, '--allow-fs-write=' + path];
+}
+
+function run(code, permissions, expected = {}, env = {}) {
+  spawnSyncAndAssert(
+    process.execPath,
+    [
+      '--permission',
+      '--allow-env=DB_PATH,ATTACH_PATH,BACKUP_PATH',
+      ...permissions,
+      '--eval', code.replace(/\n/g, ' '),
+    ],
+    {
+      env: {
+        ...process.env,
+        DB_PATH: dbPath,
+        ...env,
+      },
+    },
+    expected,
+  );
+}
+
+const readOnly = `const { DatabaseSync } = require('node:sqlite');
+  const db = new DatabaseSync(process.env.DB_PATH, { readOnly: true });
+  db.close();`;
+
+const readWrite = `const { DatabaseSync } = require('node:sqlite');
+  const db = new DatabaseSync(process.env.DB_PATH);
+  db.close();`;
+
+run(readOnly, ['--allow-fs-read=' + deniedPath], accessDenied);
+
+// A read-write database requires both read and write permission.
+for (const flag of ['--allow-fs-read=', '--allow-fs-write=']) {
+  run(readWrite, [flag + dbPath], accessDenied);
+}
+run(readWrite, readWriteGrant(dbPath));
+
+{
+  // Delayed opening performs the same checks as opening in the constructor.
+  const code = `const { DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(process.env.DB_PATH, { open: false });
+    db.open();`;
+  run(code, readWriteGrant(deniedPath), accessDenied);
+}
+
+{
+  // In-memory databases never require filesystem permission.
+  const code = `const { DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(':memory:');
+    db.close();`;
+  run(code, []);
+}
+
+{
+  // TODO(araujogui): Support URI filenames with the permission model.
+  for (const location of [
+    'require("node:url").pathToFileURL(process.env.DB_PATH)',
+    '"file:" + process.env.DB_PATH + "?mode=ro"',
+    'Buffer.from("file::memory:?vfs=memdb")',
+  ]) {
+    const code = `const { DatabaseSync } = require('node:sqlite');
+      new DatabaseSync(${location});`;
+    run(code, ['--allow-fs-read=*'], {
+      status: 1,
+      stderr: /must not be a URL or SQLite URI filename/,
+    });
+  }
+}
+
+{
+  // Backup destinations reject URI filenames too.
+  const code = `const { backup, DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(':memory:');
+    backup(db, 'file:' + process.env.BACKUP_PATH);`;
+  run(
+    code,
+    readWriteGrant('*'),
+    { status: 1, stderr: /must not be a URL or SQLite URI filename/ },
+    { BACKUP_PATH: backupPath },
+  );
+  assert.strictEqual(fs.existsSync(backupPath), false);
+}
+
+{
+  // Attached databases use the permission VFS too. A filename that resembles
+  // a sidecar does not inherit permission when opened as a main database.
+  const code = `const { DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(process.env.DB_PATH);
+    const attachPath = process.env.ATTACH_PATH.replaceAll("'", "''");
+    db.exec("ATTACH DATABASE '" + attachPath + "' AS outside");`;
+  for (const attachPath of [deniedPath, suffixDbPath]) {
+    run(code, readWriteGrant(dbPath), accessDenied, { ATTACH_PATH: attachPath });
+  }
+  assert.strictEqual(fs.existsSync(suffixDbPath), false);
+}
+
+{
+  // ATTACH treats URI filenames as plain paths, so they cannot select a VFS.
+  for (const attach of [
+    "db.exec(\"ATTACH 'file::memory:?vfs=memdb' AS outside\");",
+    "db.prepare('ATTACH ? AS outside').run('file::memory:?vfs=memdb');",
+    "db.exec(\"ATTACH 'file::memory:?vf' || 's=memdb' AS outside\");",
+  ]) {
+    const code = `const { DatabaseSync } = require('node:sqlite');
+      const db = new DatabaseSync(':memory:');
+      ${attach}`;
+    run(code, [], accessDenied);
+  }
+}
+
+{
+  // Bound ATTACH filenames work when the path is granted.
+  const code = `const { DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(':memory:');
+    db.prepare('ATTACH ? AS other').run(process.env.DB_PATH);
+    db.close();`;
+  run(code, readWriteGrant(dbPath));
+}
+
+if (!common.isWindows) {
+  // Granted paths that go through a symbolic link are checked the same way
+  // as the fs module checks them, without resolving the link.
+  const realDir = tmpdir.resolve('sqlite-real');
+  const linkDir = tmpdir.resolve('sqlite-link');
+  fs.mkdirSync(realDir, { recursive: true });
+  fs.rmSync(linkDir, { force: true });
+  fs.symlinkSync(realDir, linkDir, 'dir');
+  const linkedDbPath = tmpdir.resolve('sqlite-link', 'linked.sqlite');
+  const code = `const { DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(process.env.DB_PATH);
+    db.exec('CREATE TABLE t (x)');
+    db.close();`;
+  run(code, readWriteGrant(linkDir), {}, { DB_PATH: linkedDbPath });
+}
+
+{
+  // Backup destinations are opened through the permission VFS. Destinations
+  // that resemble sidecars still require exact access.
+  const code = `(async () => {
+    const { backup, DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(process.env.DB_PATH, { readOnly: true });
+    try {
+      await backup(db, process.env.BACKUP_PATH);
+      process.exitCode = 1;
+    } catch (err) {
+      process.exitCode = err.code === 'ERR_ACCESS_DENIED' ? 0 : 1;
+    }
+  })();`;
+  for (const [permissions, destination] of [
+    [['--allow-fs-read=' + dbPath], backupPath],
+    [readWriteGrant(dbPath), suffixDbPath],
+  ]) {
+    run(code, permissions, {}, { BACKUP_PATH: destination });
+    assert.strictEqual(fs.existsSync(destination), false);
+  }
+}
+
+{
+  // Audit mode reports denied ATTACH and backup paths without denying them.
+  const attachPath = tmpdir.resolve('audit-attach.sqlite');
+  const auditBackupPath = tmpdir.resolve('audit-backup.sqlite');
+  const code = `(async () => {
+    const messages = [];
+    require('node:diagnostics_channel').subscribe(
+      'node:permission-model:fs',
+      (m) => messages.push(m.permission + ' ' + m.resource));
+    const { backup, DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(':memory:');
+    db.prepare('ATTACH ? AS outside').run(process.env.ATTACH_PATH);
+    await backup(db, process.env.BACKUP_PATH);
+    db.close();
+    setImmediate(() => console.log(JSON.stringify(messages)));
+  })();`;
+  spawnSyncAndAssert(
+    process.execPath,
+    ['--permission-audit', '--eval', code.replace(/\n/g, ' ')],
+    {
+      env: {
+        ...process.env,
+        ATTACH_PATH: attachPath,
+        BACKUP_PATH: auditBackupPath,
+      },
+    },
+    {
+      stdout(output) {
+        assert.deepStrictEqual(JSON.parse(output), [
+          'FileSystemRead ' + attachPath,
+          'FileSystemRead ' + auditBackupPath,
+        ]);
+      },
+    },
+  );
+  assert.strictEqual(fs.existsSync(auditBackupPath), true);
+}
+
+{
+  // Backup I/O on worker threads remains available when permissions allow it.
+  const code = `(async () => {
+    const { backup, DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(process.env.DB_PATH, { readOnly: true });
+    await backup(db, process.env.BACKUP_PATH);
+    db.close();
+  })();`;
+  run(
+    code,
+    ['--allow-fs-read=' + dbPath, ...readWriteGrant(allowedBackupPath)],
+    {},
+    { BACKUP_PATH: allowedBackupPath },
+  );
+  assert.strictEqual(fs.existsSync(allowedBackupPath), true);
+}
+
+{
+  // A database grant also covers SQLite-managed journal, WAL, and SHM files.
+  const code = `const { DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(process.env.DB_PATH);
+    db.exec('PRAGMA journal_mode=WAL; CREATE TABLE data(value)');
+    db.close();`;
+  run(code, readWriteGrant(sidecarDbPath), {}, { DB_PATH: sidecarDbPath });
+}
+
+{
+  // A read-only connection can consume an existing WAL without write access.
+  const writer = new DatabaseSync(walDbPath);
+  writer.exec(`
+    PRAGMA journal_mode=WAL;
+    PRAGMA wal_autocheckpoint=0;
+    CREATE TABLE data(value);
+    INSERT INTO data VALUES (1);
+  `);
+
+  const code = `const { DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(process.env.DB_PATH, { readOnly: true });
+    db.prepare('SELECT * FROM data').all();
+    db.close();`;
+  try {
+    run(code, ['--allow-fs-read=' + walDbPath], {}, { DB_PATH: walDbPath });
+  } finally {
+    writer.close();
+  }
+}
+
+{
+  // Internal temporary files fall back to the memory VFS when only
+  // path-specific filesystem permissions are available.
+  const code = `const { DatabaseSync } = require('node:sqlite');
+    const db = new DatabaseSync(process.env.DB_PATH);
+    db.exec(\`PRAGMA temp_store=FILE;
+      PRAGMA temp.cache_size=1;
+      CREATE TEMP TABLE temp_data(value);
+      WITH RECURSIVE counter(value) AS (
+        VALUES(1) UNION ALL
+        SELECT value + 1 FROM counter WHERE value < 1000
+      )
+      INSERT INTO temp_data SELECT randomblob(10000) FROM counter;\`);
+    db.close();`;
+  run(code, readWriteGrant(sidecarDbPath), {}, { DB_PATH: sidecarDbPath });
+}
+
+{
+  // Empty filenames create anonymous temporary databases. A path-specific
+  // grant cannot authorize their initial database location.
+  const code = `const { DatabaseSync } = require('node:sqlite');
+    new DatabaseSync('');`;
+  run(code, readWriteGrant(deniedPath), accessDenied);
+}