Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request refactors the JDBC driver's logging infrastructure to support secure, per-connection file logging using NIO SeekableByteChannel directly, preventing lock file creation and enforcing strict POSIX file permissions. It also introduces a typed ConnectionLogContext to avoid parameter collisions during message formatting and ensures proper cleanup of executors and OpenTelemetry resources upon connection failure. The code review feedback identifies critical resource leaks in PerConnectionFileHandler where opened channels could be leaked if setting POSIX permissions or positioning the channel throws an exception. Additionally, a potential NullPointerException was flagged in BigQueryConnection's cleanup block if openTelemetry is null during a failed initialization.
| SeekableByteChannel channel = Files.newByteChannel(file, createNewOpts, attrs); | ||
| if (isPosix) { | ||
| Files.setPosixFilePermissions(file, OWNER_FILE_PERMS); | ||
| } | ||
| return channel; |
There was a problem hiding this comment.
If Files.setPosixFilePermissions throws an IOException or RuntimeException (e.g., due to filesystem restrictions or security managers), the newly opened SeekableByteChannel is leaked because it is never closed. Wrapping the permission setting in a try-catch block that closes the channel on failure prevents resource leaks.
SeekableByteChannel channel = Files.newByteChannel(file, createNewOpts, attrs);
if (isPosix) {
try {
Files.setPosixFilePermissions(file, OWNER_FILE_PERMS);
} catch (IOException | RuntimeException e) {
try {
channel.close();
} catch (IOException closeEx) {
e.addSuppressed(closeEx);
}
throw e;
}
}
return channel;| SeekableByteChannel channel = Files.newByteChannel(file, writeExistingOpts); | ||
| channel.position(channel.size()); | ||
| return channel; |
There was a problem hiding this comment.
If channel.position(channel.size()) throws an IOException (e.g., if the channel is concurrently closed or an I/O error occurs), the opened SeekableByteChannel is leaked. Wrapping the positioning call in a try-catch block that closes the channel on failure prevents resource leaks.
SeekableByteChannel channel = Files.newByteChannel(file, writeExistingOpts);
try {
channel.position(channel.size());
} catch (IOException | RuntimeException e) {
try {
channel.close();
} catch (IOException closeEx) {
e.addSuppressed(closeEx);
}
throw e;
}
return channel;| SeekableByteChannel channel = Files.newByteChannel(file, opts, attrs); | ||
| if (isPosix) { | ||
| Files.setPosixFilePermissions(file, OWNER_FILE_PERMS); | ||
| } | ||
| return channel; |
There was a problem hiding this comment.
If Files.setPosixFilePermissions throws an IOException or RuntimeException, the newly opened SeekableByteChannel is leaked. Wrapping the permission setting in a try-catch block that closes the channel on failure prevents resource leaks.
SeekableByteChannel channel = Files.newByteChannel(file, opts, attrs);
if (isPosix) {
try {
Files.setPosixFilePermissions(file, OWNER_FILE_PERMS);
} catch (IOException | RuntimeException e) {
try {
channel.close();
} catch (IOException closeEx) {
e.addSuppressed(closeEx);
}
throw e;
}
}
return channel;| } | ||
| BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId); | ||
| BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId); | ||
| BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry); |
There was a problem hiding this comment.
In the finally block, this.openTelemetry can be null if the constructor fails before openTelemetry is initialized (or during its initialization). Calling releaseSdk with a null argument without a guard can cause a NullPointerException, which would mask the original exception that triggered the finally block. Adding a null check prevents this.
if (this.openTelemetry != null) {
BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry);
}References
- When using lazily initialized resources, ensure that teardown or close methods perform explicit null checks before invoking methods on them to prevent NullPointerException.
…g files PR 1 of 6 in the diagnostic logging series (b/584840147, part 1 of 3). Replaces java.util.logging.FileHandler inside PerConnectionFileHandler with an NIO SeekableByteChannel writer enforcing 0700/0600 POSIX permissions, symlink rejection, collision-safe exclusive creation, literal % path handling, and graceful ErrorManager degradation.
47aaf40 to
578cc0b
Compare
|
/gemini review |
578cc0b to
8c47507
Compare
There was a problem hiding this comment.
Code Review
This pull request refactors PerConnectionFileHandler to use custom NIO SeekableByteChannel writers instead of standard FileHandler, enforcing secure owner-only POSIX permissions and rejecting symbolic links to improve security. Feedback on these changes includes removing the expensive FileChannel.force(false) call during flushes, improving the robustness of the POSIX owner verification in containerized environments using UserPrincipalLookupService, and adding a defensive null check in closeQuietlyWithSuppressed to prevent a potential NullPointerException from masking primary exceptions.
8c47507 to
5b55b06
Compare
keshavdandeva
left a comment
There was a problem hiding this comment.
The permission hardening works: new directories and files come out 0700 / 0600. But replacing FileHandler with a raw FileChannel introduced one blocker and three majors that main does not have. Details inline.
Question. On Windows, tryLock() on the log file is a mandatory lock. Can another process still tail BQ-JDBC-GLOBAL.log while the JVM runs? FileHandler locked a .lck sidecar instead.
| try { | ||
| ByteBuffer buffer = ByteBuffer.wrap(formatted.getBytes(StandardCharsets.UTF_8)); | ||
| while (buffer.hasRemaining()) { | ||
| channel.write(buffer); |
There was a problem hiding this comment.
Blocker. FileChannel is interruptible. One log call on a thread whose interrupt flag is set closes the channel, and every later record for that file is dropped. Repro: 1 of 4 records written (FileHandler: 3 of 3). The driver's own cancel path appears to trigger it: ResultSet.close() calls cancel(true), and the worker re-asserts the flag and then logs. Please clear and restore the flag around channel I/O, reopen on ClosedChannelException, and add a test.
| Files.setPosixFilePermissions(file, OWNER_FILE_PERMS); | ||
| } | ||
| SeekableByteChannel channel = | ||
| Files.newByteChannel(file, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS); |
There was a problem hiding this comment.
Major. Please open with StandardOpenOption.APPEND and drop both position(size()) calls. Without it, an external truncate (e.g. logrotate copytruncate) leaves a NUL-filled hole (repro: 11,290 NUL bytes), and two writers on one file overwrite each other. (Also applies to the CREATE_NEW open at L288.)
|
|
||
| static void verifyPosixOwner(Path file) throws IOException { | ||
| if (isPosixFileSystem(file)) { | ||
| String currentUser = System.getProperty("user.name"); |
There was a problem hiding this comment.
Major. user.name is not the process's file-system identity. Under a UID with no passwd entry (runAsUser on Kubernetes) it is ?, so this check always fails. Repro, with the handler re-created per connect as setPath does: 65 global log files, then logging stops. Suggest comparing against the owner of a file this process just created.
| depth++; | ||
| current = current.resolve(segment); | ||
| if (Files.isSymbolicLink(current)) { | ||
| if (depth == 1 && Files.isDirectory(current)) { |
There was a problem hiding this comment.
Major. Any symlink below the first path component silently disables file logging, e.g. /var/run or /var/log/app -> /data/.... Depth is not what makes a link safe; ownership is. Suggest following links owned by root or by the current user.
| return; | ||
| } | ||
| try { | ||
| ByteBuffer buffer = ByteBuffer.wrap(formatted.getBytes(StandardCharsets.UTF_8)); |
There was a problem hiding this comment.
Minor. A single write() of the whole record makes the JDK cache a direct buffer of that size per thread. Repro: 8 threads, one 16 MiB record each, 128 MiB held. Writing in 8 KiB slices avoids it.
|
|
||
| String origUser = System.getProperty("user.name"); | ||
| try { | ||
| System.setProperty("user.name", ""); |
There was a problem hiding this comment.
Minor. This flips the JVM-wide user.name and locks in the behavior from my comment on verifyPosixOwner. Also, openSecureAppendChannel(Path) (L177) passes tightenOnOpen = true and only tests call it; production passes false. Please test the production branch.
Summary
PR 1 of 6 in the diagnostic logging stack (
b/584840147, part 1 of 3; bounded 1 GiB.1.logrotation follows in PR 2). Replacesjava.util.logging.FileHandlerinPerConnectionFileHandlerwith an NIOSeekableByteChannelwriter (ChannelLogWriter) enforcing owner-only permissions and graceful error handling.Design Decisions
SeekableByteChannel(ChannelLogWriter) overjava.util.logging.FileHandler:FileHandlercreates files with default process umask (0644), leaves.lcksidecar files behind, expands%t/%h/%g/%utokens in user-supplied paths, and falls back toSystem.getProperty("user.home")on empty patterns. UsingFiles.newByteChannelsets0600(rw-------) atomically at creation time viaCREATE_NEW, treatsLogPathas a literal filesystem path, and eliminates.lckfiles.0700(rwx------), while pre-existing shared directories (such as/tmp) keep their existing permissions untouched. Symlink checks skip top-level OS root links (preserving macOS/tmp -> /private/tmpand/var -> /private/var) while rejecting nested directory or file symlinks.ACTIVE_GLOBAL_PATHSbefore opening a channel onBQ-JDBC-GLOBAL.log(avoiding POSIXfcntllock release from duplicate in-JVM file descriptors) and uses non-blockingFileChannel.tryLock(), isolating ontoBQ-JDBC-GLOBAL-<PID>.logon contention.LogPathvalues report once through JULErrorManagerand disable file output rather than throwingIOException/SQLExceptionout ofDriverManager.getConnection(...).