Sha256: 31defcb4ee9dc94d4038885c90e16541550def9339b7a1daa424e22b3de9f381

Contents?: true

Size: 1.9 KB

Versions: 7

Compression:

Stored size: 1.9 KB

Contents

# Copyright (c) 2020 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
# frozen_string_literal: true

cs__scoped_require 'contrast/components/interface'

module Contrast
  module Utils
    # Util for information about an IO
    class IOUtil
      include Contrast::Components::Interface

      access_component :logging

      # StringIO is a valid path because it logs directly to a string buffer
      def self.write_permission? path
        return false if path.nil?
        return true if path.is_a?(StringIO)
        return File.writable?(path) if File.exist?(path)

        dir_name = File.dirname(File.absolute_path(path))
        File.writable?(dir_name)
      end

      # We're only going to call rewind on things that we believe are safe to
      # call it on. This method white lists those cases and returns false in
      # all others.
      def self.should_rewind? potential_io
        return true if potential_io.is_a?(StringIO)
        return false unless io?(potential_io)

        should_rewind_io?(potential_io)
      rescue StandardError => e
        logger.debug(e, "Encountered an issue inspecting instance of #{ potential_io } - continuing without rewind")
        false
      end

      # IO cannot be used with streams such as pipes, ttys, and sockets.
      def self.should_rewind_io? io
        return false if io.tty?

        status = io.stat
        return false unless status
        return false if status.pipe?
        return false if status.socket?

        true
      end

      # A class is IO if it is a decedent or delegate of IO
      def self.io? object
        return true if object.is_a?(IO)

        # DelegateClass, which is a Delegator, defines __getobj__ as a way to
        # get the object that the class wraps around (delegates to)
        return false unless object.is_a?(Delegator)

        object.__getobj__.is_a?(IO)
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
contrast-agent-3.10.2 lib/contrast/utils/io_util.rb
contrast-agent-3.10.1 lib/contrast/utils/io_util.rb
contrast-agent-3.10.0 lib/contrast/utils/io_util.rb
contrast-agent-3.9.1 lib/contrast/utils/io_util.rb
contrast-agent-3.9.0 lib/contrast/utils/io_util.rb
contrast-agent-3.8.5 lib/contrast/utils/io_util.rb
contrast-agent-3.8.4 lib/contrast/utils/io_util.rb