Skip to content

fix(bigquery-jdbc): use NIO channel with 0700/0600 permissions for log files - #15112

Open
Neenu1995 wants to merge 4 commits into
mainfrom
fix/bq-jdbc-log-file-hardening
Open

Neenu1995 wants to merge 4 commits into
mainfrom
fix/bq-jdbc-log-file-hardening

Conversation

@Neenu1995

@Neenu1995 Neenu1995 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

PR 1 of 6 in the diagnostic logging stack (b/584840147, part 1 of 3; bounded 1 GiB .1.log rotation follows in PR 2). Replaces java.util.logging.FileHandler in PerConnectionFileHandler with an NIO SeekableByteChannel writer (ChannelLogWriter) enforcing owner-only permissions and graceful error handling.

Design Decisions

  • NIO SeekableByteChannel (ChannelLogWriter) over java.util.logging.FileHandler: FileHandler creates files with default process umask (0644), leaves .lck sidecar files behind, expands %t/%h/%g/%u tokens in user-supplied paths, and falls back to System.getProperty("user.home") on empty patterns. Using Files.newByteChannel sets 0600 (rw-------) atomically at creation time via CREATE_NEW, treats LogPath as a literal filesystem path, and eliminates .lck files.
  • Directory creation & symlink handling: Newly created log directories receive 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/tmp and /var -> /private/var) while rejecting nested directory or file symlinks.
  • In-JVM + cross-process global log coordination: Claims normalized paths in ACTIVE_GLOBAL_PATHS before opening a channel on BQ-JDBC-GLOBAL.log (avoiding POSIX fcntl lock release from duplicate in-JVM file descriptors) and uses non-blocking FileChannel.tryLock(), isolating onto BQ-JDBC-GLOBAL-<PID>.log on contention.
  • Graceful degradation (preserving the JDBC contract): Invalid or inaccessible LogPath values report once through JUL ErrorManager and disable file output rather than throwing IOException / SQLException out of DriverManager.getConnection(...).

@Neenu1995
Neenu1995 requested review from a team as code owners November 20, 2026 21:25
@Neenu1995
Neenu1995 added this pull request to stack #15115 November 20, 2026 21:26

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +200 to +204
SeekableByteChannel channel = Files.newByteChannel(file, createNewOpts, attrs);
if (isPosix) {
Files.setPosixFilePermissions(file, OWNER_FILE_PERMS);
}
return channel;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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;

Comment on lines +221 to +223
SeekableByteChannel channel = Files.newByteChannel(file, writeExistingOpts);
channel.position(channel.size());
return channel;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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;

Comment on lines +236 to +240
SeekableByteChannel channel = Files.newByteChannel(file, opts, attrs);
if (isPosix) {
Files.setPosixFilePermissions(file, OWNER_FILE_PERMS);
}
return channel;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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
  1. 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.
@Neenu1995 Neenu1995 changed the title fix(bigquery-jdbc): harden log file permissions and prevent post-close handler leaks [WIP] fix(bigquery-jdbc): harden log file permissions and prevent post-close handler leaks Nov 23, 2026
@Neenu1995
Neenu1995 force-pushed the fix/bq-jdbc-log-file-hardening branch from 47aaf40 to 578cc0b Compare November 23, 2026 19:57
@Neenu1995 Neenu1995 changed the title [WIP] fix(bigquery-jdbc): harden log file permissions and prevent post-close handler leaks [WIP] fix(bigquery-jdbc): use NIO channel with 0700/0600 permissions for log files Nov 23, 2026
@Neenu1995

Copy link
Copy Markdown
Contributor Author

/gemini review

@Neenu1995
Neenu1995 force-pushed the fix/bq-jdbc-log-file-hardening branch from 578cc0b to 8c47507 Compare November 23, 2026 20:23

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Neenu1995
Neenu1995 removed this pull request from stack #15115 November 23, 2026 20:27
@Neenu1995
Neenu1995 force-pushed the fix/bq-jdbc-log-file-hardening branch from 8c47507 to 5b55b06 Compare November 23, 2026 20:58
@Neenu1995 Neenu1995 changed the title [WIP] fix(bigquery-jdbc): use NIO channel with 0700/0600 permissions for log files fix(bigquery-jdbc): use NIO channel with 0700/0600 permissions for log files Nov 24, 2026

@keshavdandeva keshavdandeva left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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", "");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants