repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/mercenary-0.3.6/lib/mercenary/program.rb | _vendor/ruby/2.6.0/gems/mercenary-0.3.6/lib/mercenary/program.rb | module Mercenary
class Program < Command
attr_reader :optparse
attr_reader :config
# Public: Creates a new Program
#
# name - the name of the program
#
# Returns nothing
def initialize(name)
@config = {}
super(name)
end
# Public: Run the program
#
# argv - an array of string args (usually ARGV)
#
# Returns nothing
def go(argv)
logger.debug("Using args passed in: #{argv.inspect}")
cmd = nil
@optparse = OptionParser.new do |opts|
cmd = super(argv, opts, @config)
end
begin
@optparse.parse!(argv)
rescue OptionParser::InvalidOption => e
logger.error "Whoops, we can't understand your command."
logger.error "#{e.message}"
logger.error "Run your command again with the --help switch to see available options."
abort
end
logger.debug("Parsed config: #{@config.inspect}")
begin
cmd.execute(argv, @config)
rescue => e
if cmd.trace
raise e
else
logger.error e.message
abort
end
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/mercenary-0.3.6/lib/mercenary/option.rb | _vendor/ruby/2.6.0/gems/mercenary-0.3.6/lib/mercenary/option.rb | module Mercenary
class Option
attr_reader :config_key, :description, :short, :long, :return_type
# Public: Create a new Option
#
# config_key - the key in the config hash to which the value of this option
# will map
# info - an array containing first the switches, then an optional
# return type (e.g. Array), then a description of the option
#
# Returns nothing
def initialize(config_key, info)
@config_key = config_key
while arg = info.shift
begin
@return_type = Object.const_get("#{arg}")
next
rescue NameError
end
if arg.start_with?("-")
if arg.start_with?("--")
@long = arg
else
@short = arg
end
next
end
@description = arg
end
end
# Public: Fetch the array containing the info OptionParser is interested in
#
# Returns the array which OptionParser#on wants
def for_option_parser
[short, long, return_type, description].flatten.reject{ |o| o.to_s.empty? }
end
# Public: Build a string representation of this option including the
# switches and description
#
# Returns a string representation of this option
def to_s
"#{formatted_switches} #{description}"
end
# Public: Build a beautifully-formatted string representation of the switches
#
# Returns a formatted string representation of the switches
def formatted_switches
[
switches.first.rjust(10),
switches.last.ljust(13)
].join(", ").gsub(/ , /, ' ').gsub(/, /, ' ')
end
# Public: Hash based on the hash value of instance variables
#
# Returns a Fixnum which is unique to this Option based on the instance variables
def hash
instance_variables.map do |var|
instance_variable_get(var).hash
end.reduce(:^)
end
# Public: Check equivalence of two Options based on equivalence of their
# instance variables
#
# Returns true if all the instance variables are equal, false otherwise
def eql?(other)
return false unless self.class.eql?(other.class)
instance_variables.map do |var|
instance_variable_get(var).eql?(other.instance_variable_get(var))
end.all?
end
# Public: Fetch an array of switches, including the short and long versions
#
# Returns an array of two strings. An empty string represents no switch in
# that position.
def switches
[short, long].map(&:to_s)
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/helper.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/helper.rb | # encoding: BINARY
require 'rubygems'
require 'rspec'
require 'em-spec/rspec'
require 'em-http'
require 'em-websocket'
require 'em-websocket-client'
require 'integration/shared_examples'
require 'integration/gte_03_examples'
RSpec.configure do |c|
c.mock_with :rspec
end
class FakeWebSocketClient < EM::Connection
attr_reader :handshake_response, :packets
def onopen(&blk); @onopen = blk; end
def onclose(&blk); @onclose = blk; end
def onerror(&blk); @onerror = blk; end
def onmessage(&blk); @onmessage = blk; end
def initialize
@state = :new
@packets = []
end
def receive_data(data)
# puts "RECEIVE DATA #{data}"
if @state == :new
@handshake_response = data
@onopen.call if defined? @onopen
@state = :open
else
@onmessage.call(data) if defined? @onmessage
@packets << data
end
end
def send(application_data)
send_frame(:text, application_data)
end
def send_frame(type, application_data)
send_data construct_frame(type, application_data)
end
def unbind
@onclose.call if defined? @onclose
end
private
def construct_frame(type, data)
"\x00#{data}\xff"
end
end
class Draft03FakeWebSocketClient < FakeWebSocketClient
private
def construct_frame(type, data)
frame = ""
frame << EM::WebSocket::Framing03::FRAME_TYPES[type]
frame << encoded_length(data.size)
frame << data
end
def encoded_length(length)
if length <= 125
[length].pack('C') # since rsv4 is 0
elsif length < 65536 # write 2 byte length
"\126#{[length].pack('n')}"
else # write 8 byte length
"\127#{[length >> 32, length & 0xFFFFFFFF].pack("NN")}"
end
end
end
class Draft05FakeWebSocketClient < Draft03FakeWebSocketClient
private
def construct_frame(type, data)
frame = ""
frame << "\x00\x00\x00\x00" # Mask with nothing for simplicity
frame << (EM::WebSocket::Framing05::FRAME_TYPES[type] | 0b10000000)
frame << encoded_length(data.size)
frame << data
end
end
class Draft07FakeWebSocketClient < Draft05FakeWebSocketClient
private
def construct_frame(type, data)
frame = ""
frame << (EM::WebSocket::Framing07::FRAME_TYPES[type] | 0b10000000)
# Should probably mask the data, but I get away without bothering since
# the server doesn't enforce that incoming frames are masked
frame << encoded_length(data.size)
frame << data
end
end
# Wrapper around em-websocket-client
class Draft75WebSocketClient
def onopen(&blk); @onopen = blk; end
def onclose(&blk); @onclose = blk; end
def onerror(&blk); @onerror = blk; end
def onmessage(&blk); @onmessage = blk; end
def initialize
@ws = EventMachine::WebSocketClient.connect('ws://127.0.0.1:12345/',
:version => 75,
:origin => 'http://example.com')
@ws.errback { |err| @onerror.call if defined? @onerror }
@ws.callback { @onopen.call if defined? @onopen }
@ws.stream { |msg| @onmessage.call(msg) if defined? @onmessage }
@ws.disconnect { @onclose.call if defined? @onclose }
end
def send(message)
@ws.send_msg(message)
end
def close_connection
@ws.close_connection
end
end
def start_server(opts = {})
EM::WebSocket.run({:host => "0.0.0.0", :port => 12345}.merge(opts)) { |ws|
yield ws if block_given?
}
end
def format_request(r)
data = "#{r[:method]} #{r[:path]} HTTP/1.1\r\n"
header_lines = r[:headers].map { |k,v| "#{k}: #{v}" }
data << [header_lines, '', r[:body]].join("\r\n")
data
end
def format_response(r)
data = r[:protocol] || "HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
header_lines = r[:headers].map { |k,v| "#{k}: #{v}" }
data << [header_lines, '', r[:body]].join("\r\n")
data
end
RSpec::Matchers.define :succeed_with_upgrade do |response|
match do |actual|
success = nil
actual.callback { |upgrade_response, handler_klass|
success = (upgrade_response.lines.sort == format_response(response).lines.sort)
}
success
end
end
RSpec::Matchers.define :fail_with_error do |error_klass, error_message|
match do |actual|
success = nil
actual.errback { |e|
success = (e.class == error_klass)
success &= (e.message == error_message) if error_message
}
success
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/common_spec.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/common_spec.rb | require 'helper'
# These tests are not specific to any particular draft of the specification
#
describe "WebSocket server" do
include EM::SpecHelper
default_timeout 1
it "should fail on non WebSocket requests" do
em {
EM.add_timer(0.1) do
http = EM::HttpRequest.new('http://127.0.0.1:12345/').get :timeout => 0
http.errback { done }
http.callback { fail }
end
start_server
}
end
it "should expose the WebSocket request headers, path and query params" do
em {
EM.add_timer(0.1) do
ws = EventMachine::WebSocketClient.connect('ws://127.0.0.1:12345/',
:origin => 'http://example.com')
ws.errback { fail }
ws.callback { ws.close_connection }
ws.stream { |msg| }
end
start_server do |ws|
ws.onopen { |handshake|
headers = handshake.headers
headers["Connection"].should == "Upgrade"
headers["Upgrade"].should == "websocket"
headers["Host"].to_s.should == "127.0.0.1:12345"
handshake.path.should == "/"
handshake.query.should == {}
handshake.origin.should == 'http://example.com'
}
ws.onclose {
ws.state.should == :closed
done
}
end
}
end
it "should expose the WebSocket path and query params when nonempty" do
em {
EM.add_timer(0.1) do
ws = EventMachine::WebSocketClient.connect('ws://127.0.0.1:12345/hello?foo=bar&baz=qux')
ws.errback { fail }
ws.callback {
ws.close_connection
}
ws.stream { |msg| }
end
start_server do |ws|
ws.onopen { |handshake|
handshake.path.should == '/hello'
handshake.query_string.split('&').sort.
should == ["baz=qux", "foo=bar"]
handshake.query.should == {"foo"=>"bar", "baz"=>"qux"}
}
ws.onclose {
ws.state.should == :closed
done
}
end
}
end
it "should raise an exception if frame sent before handshake complete" do
em {
# 1. Start WebSocket server
start_server { |ws|
# 3. Try to send a message to the socket
lambda {
ws.send('early message')
}.should raise_error('Cannot send data before onopen callback')
done
}
# 2. Connect a dumb TCP connection (will not send handshake)
EM.connect('0.0.0.0', 12345, EM::Connection)
}
end
it "should allow the server to be started inside an existing EM" do
em {
EM.add_timer(0.1) do
http = EM::HttpRequest.new('http://127.0.0.1:12345/').get :timeout => 0
http.errback { |e| done }
http.callback { fail }
end
start_server do |ws|
ws.onopen { |handshake|
headers = handshake.headers
headers["Host"].to_s.should == "127.0.0.1:12345"
}
ws.onclose {
ws.state.should == :closed
done
}
end
}
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft13_spec.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft13_spec.rb | # encoding: BINARY
require 'helper'
describe "draft13" do
include EM::SpecHelper
default_timeout 1
before :each do
@request = {
:port => 80,
:method => "GET",
:path => "/demo",
:headers => {
'Host' => 'example.com',
'Upgrade' => 'websocket',
'Connection' => 'Upgrade',
'Sec-WebSocket-Key' => 'dGhlIHNhbXBsZSBub25jZQ==',
'Sec-WebSocket-Protocol' => 'sample',
'Sec-WebSocket-Origin' => 'http://example.com',
'Sec-WebSocket-Version' => '13'
}
}
@response = {
:protocol => "HTTP/1.1 101 Switching Protocols\r\n",
:headers => {
"Upgrade" => "websocket",
"Connection" => "Upgrade",
"Sec-WebSocket-Accept" => "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",
}
}
end
def start_client
client = EM.connect('0.0.0.0', 12345, Draft07FakeWebSocketClient)
client.send_data(format_request(@request))
yield client if block_given?
return client
end
it_behaves_like "a websocket server" do
let(:version) { 13 }
end
it_behaves_like "a WebSocket server drafts 3 and above" do
let(:version) { 13 }
end
it "should send back the correct handshake response" do
em {
start_server
connection = start_client
connection.onopen {
connection.handshake_response.lines.sort.
should == format_response(@response).lines.sort
done
}
}
end
# TODO: This test would be much nicer with a real websocket client...
it "should support sending pings and binding to onpong" do
em {
start_server { |ws|
ws.onopen {
ws.should be_pingable
EM.next_tick {
ws.ping('hello').should == true
}
}
ws.onpong { |data|
data.should == 'hello'
done
}
}
connection = start_client
# Confusing, fake onmessage means any data after the handshake
connection.onmessage { |data|
# This is what a ping looks like
data.should == "\x89\x05hello"
# This is what a pong looks like
connection.send_data("\x8a\x05hello")
}
}
end
it "should report that close codes are supported" do
em {
start_server { |ws|
ws.onopen {
ws.supports_close_codes?.should == true
done
}
}
start_client
}
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft76_spec.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft76_spec.rb | # encoding: BINARY
require 'helper'
describe "WebSocket server draft76" do
include EM::SpecHelper
default_timeout 1
before :each do
@request = {
:port => 80,
:method => "GET",
:path => "/demo",
:headers => {
'Host' => 'example.com',
'Connection' => 'Upgrade',
'Sec-WebSocket-Key2' => '12998 5 Y3 1 .P00',
'Sec-WebSocket-Protocol' => 'sample',
'Upgrade' => 'WebSocket',
'Sec-WebSocket-Key1' => '4 @1 46546xW%0l 1 5',
'Origin' => 'http://example.com'
},
:body => '^n:ds[4U'
}
@response = {
:headers => {
"Upgrade" => "WebSocket",
"Connection" => "Upgrade",
"Sec-WebSocket-Location" => "ws://example.com/demo",
"Sec-WebSocket-Origin" => "http://example.com",
"Sec-WebSocket-Protocol" => "sample"
},
:body => "8jKS\'y:G*Co,Wxa-"
}
end
def start_client
client = EM.connect('0.0.0.0', 12345, FakeWebSocketClient)
client.send_data(format_request(@request))
yield client if block_given?
return client
end
it_behaves_like "a websocket server" do
let(:version) { 76 }
end
it "should send back the correct handshake response" do
em {
start_server
start_client { |connection|
connection.onopen {
connection.handshake_response.lines.sort.
should == format_response(@response).lines.sort
done
}
}
}
end
it "should send closing frame back and close the connection after recieving closing frame" do
em {
start_server
connection = start_client
# Send closing frame after handshake complete
connection.onopen {
connection.send_data(EM::WebSocket::Handler76::TERMINATE_STRING)
}
# Check that this causes a termination string to be returned and the
# connection close
connection.onclose {
connection.packets[0].should ==
EM::WebSocket::Handler76::TERMINATE_STRING
done
}
}
end
it "should ignore any data received after the closing frame" do
em {
start_server { |ws|
# Fail if foobar message is received
ws.onmessage { |msg|
fail
}
}
connection = start_client
# Send closing frame after handshake complete, followed by another msg
connection.onopen {
connection.send_data(EM::WebSocket::Handler76::TERMINATE_STRING)
connection.send('foobar')
}
connection.onclose {
done
}
}
end
it "should accept null bytes within the frame after a line return" do
em {
start_server { |ws|
ws.onmessage { |msg|
msg.should == "\n\000"
}
}
connection = start_client
# Send closing frame after handshake complete
connection.onopen {
connection.send_data("\000\n\000\377")
connection.send_data(EM::WebSocket::Handler76::TERMINATE_STRING)
}
connection.onclose {
done
}
}
end
it "should handle unreasonable frame lengths by calling onerror callback" do
em {
start_server { |server|
server.onerror { |error|
error.should be_an_instance_of EM::WebSocket::WSMessageTooBigError
error.message.should == "Frame length too long (1180591620717411303296 bytes)"
done
}
}
client = start_client
# This particular frame indicates a message length of
# 1180591620717411303296 bytes. Such a message would previously cause
# a "bignum too big to convert into `long'" error.
# However it is clearly unreasonable and should be rejected.
client.onopen {
client.send_data("\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00")
}
}
end
it "should handle impossible frames by calling onerror callback" do
em {
start_server { |server|
server.onerror { |error|
error.should be_an_instance_of EM::WebSocket::WSProtocolError
error.message.should == "Invalid frame received"
done
}
}
client = start_client
client.onopen {
client.send_data("foobar") # Does not start with \x00 or \xff
}
}
end
it "should handle invalid http requests by raising HandshakeError passed to onerror callback" do
em {
start_server { |server|
server.onerror { |error|
error.should be_an_instance_of EM::WebSocket::HandshakeError
error.message.should == "Invalid HTTP header: Could not parse data entirely (1 != 29)"
done
}
}
client = EM.connect('0.0.0.0', 12345, FakeWebSocketClient)
client.send_data("This is not a HTTP header\r\n\r\n")
}
end
it "should handle handshake request split into two TCP packets" do
em {
start_server
# Create a fake client which sends draft 76 handshake
connection = EM.connect('0.0.0.0', 12345, FakeWebSocketClient)
data = format_request(@request)
# Sends first half of the request
connection.send_data(data[0...(data.length / 2)])
connection.onopen {
connection.handshake_response.lines.sort.
should == format_response(@response).lines.sort
done
}
EM.add_timer(0.1) do
# Sends second half of the request
connection.send_data(data[(data.length / 2)..-1])
end
}
end
it "should report that close codes are not supported" do
em {
start_server { |ws|
ws.onopen {
ws.supports_close_codes?.should == false
done
}
}
start_client
}
end
it "should call onclose when the server closes the connection [antiregression]" do
em {
start_server { |ws|
ws.onopen {
EM.add_timer(0.1) {
ws.close()
}
}
ws.onclose {
done
}
}
start_client
}
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/gte_03_examples.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/gte_03_examples.rb | shared_examples_for "a WebSocket server drafts 3 and above" do
it "should force close connections after a timeout if close handshake is not sent by the client" do
em {
server_onerror_fired = false
server_onclose_fired = false
client_got_close_handshake = false
start_server(:close_timeout => 0.1) { |ws|
ws.onopen {
# 1: Send close handshake to client
EM.next_tick { ws.close(4999, "Close message") }
}
ws.onerror { |e|
# 3: Client should receive onerror
e.class.should == EM::WebSocket::WSProtocolError
e.message.should == "Close handshake un-acked after 0.1s, closing tcp connection"
server_onerror_fired = true
}
ws.onclose {
server_onclose_fired = true
}
}
start_client { |client|
client.onmessage { |msg|
# 2: Client does not respond to close handshake (the fake client
# doesn't understand them at all hence this is in onmessage)
msg.should =~ /Close message/ if version >= 6
client_got_close_handshake = true
}
client.onclose {
server_onerror_fired.should == true
server_onclose_fired.should == true
client_got_close_handshake.should == true
done
}
}
}
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/shared_examples.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/shared_examples.rb | # encoding: UTF-8
# These tests are run against all draft versions
#
shared_examples_for "a websocket server" do
it "should expose the protocol version" do
em {
start_server { |ws|
ws.onopen { |handshake|
handshake.protocol_version.should == version
done
}
}
start_client
}
end
it "should expose the origin header" do
em {
start_server { |ws|
ws.onopen { |handshake|
handshake.origin.should == 'http://example.com'
done
}
}
start_client
}
end
it "should send messages successfully" do
em {
start_server { |ws|
ws.onmessage { |message|
message.should == "hello server"
done
}
}
start_client { |client|
client.onopen {
client.send("hello server")
}
}
}
end
it "should allow connection to be closed with valid close code" do
em {
start_server { |ws|
ws.onopen {
ws.close(4004, "Bye bye")
done
}
}
start_client
# TODO: Use a real client which understands how to respond to closing
# handshakes, sending the handshake currently untested
}
end
it "should raise error if if invalid close code is used" do
em {
start_server { |ws|
ws.onopen {
lambda {
ws.close(2000)
}.should raise_error("Application code may only use codes from 1000, 3000-4999")
done
}
}
start_client
}
end
it "should call onclose with was_clean set to false if connection closed without closing handshake by server" do
em {
start_server { |ws|
ws.onopen {
# Close tcp connection (no close handshake)
ws.close_connection
}
ws.onclose { |event|
event.should == {:code => 1006, :was_clean => false}
done
}
}
start_client
}
end
it "should call onclose with was_clean set to false if connection closed without closing handshake by client" do
em {
start_server { |ws|
ws.onclose { |event|
event.should == {:code => 1006, :was_clean => false}
done
}
}
start_client { |client|
client.onopen {
# Close tcp connection (no close handshake)
client.close_connection
}
}
}
end
it "should call onerror if an application error raised in onopen" do
em {
start_server { |ws|
ws.onopen {
raise "application error"
}
ws.onerror { |e|
e.message.should == "application error"
done
}
}
start_client
}
end
it "should call onerror if an application error raised in onmessage" do
em {
start_server { |server|
server.onmessage {
raise "application error"
}
server.onerror { |e|
e.message.should == "application error"
done
}
}
start_client { |client|
client.onopen {
client.send('a message')
}
}
}
end
it "should call onerror in an application error raised in onclose" do
em {
start_server { |server|
server.onclose {
raise "application error"
}
server.onerror { |e|
e.message.should == "application error"
done
}
}
start_client { |client|
client.onopen {
EM.add_timer(0.1) {
client.close_connection
}
}
}
}
end
it "should close the connection when a too long frame is sent" do
em {
start_server { |server|
server.max_frame_size = 20
server.onerror { |e|
# 3: Error should be reported to server
e.class.should == EventMachine::WebSocket::WSMessageTooBigError
e.message.should =~ /Frame length too long/
}
}
start_client { |client|
client.onopen {
EM.next_tick {
client.send("This message is longer than 20 characters")
}
}
client.onmessage { |msg|
# 4: This is actually the close message. Really need to use a real
# WebSocket client in these tests...
done
}
client.onclose {
# 4: Drafts 75 & 76 don't send a close message, they just close the
# connection
done
}
}
}
end
# Only run these tests on ruby 1.9
if "a".respond_to?(:force_encoding)
it "should raise error if you try to send non utf8 text data to ws" do
em {
start_server { |server|
server.onopen {
# Create a string which claims to be UTF-8 but which is not
s = "ê" # utf-8 string
s.encode!("ISO-8859-1")
s.force_encoding("UTF-8")
s.valid_encoding?.should == false # now invalid utf8
# Send non utf8 encoded data
server.send(s)
}
server.onerror { |error|
error.class.should == EventMachine::WebSocket::WebSocketError
error.message.should == "Data sent to WebSocket must be valid UTF-8 but was UTF-8 (valid: false)"
done
}
}
start_client { }
}
end
it "should not change the encoding of strings sent to send [antiregression]" do
em {
start_server { |server|
server.onopen {
s = "example string"
s.force_encoding("UTF-8")
server.send(s)
s.encoding.should == Encoding.find("UTF-8")
done
}
}
start_client { }
}
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft03_spec.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft03_spec.rb | require 'helper'
describe "draft03" do
include EM::SpecHelper
default_timeout 1
before :each do
@request = {
:port => 80,
:method => "GET",
:path => "/demo",
:headers => {
'Host' => 'example.com',
'Connection' => 'Upgrade',
'Sec-WebSocket-Key2' => '12998 5 Y3 1 .P00',
'Sec-WebSocket-Protocol' => 'sample',
'Upgrade' => 'WebSocket',
'Sec-WebSocket-Key1' => '4 @1 46546xW%0l 1 5',
'Origin' => 'http://example.com',
'Sec-WebSocket-Draft' => '3'
},
:body => '^n:ds[4U'
}
@response = {
:headers => {
"Upgrade" => "WebSocket",
"Connection" => "Upgrade",
"Sec-WebSocket-Location" => "ws://example.com/demo",
"Sec-WebSocket-Origin" => "http://example.com",
"Sec-WebSocket-Protocol" => "sample"
},
:body => "8jKS\'y:G*Co,Wxa-"
}
end
def start_client
client = EM.connect('0.0.0.0', 12345, Draft03FakeWebSocketClient)
client.send_data(format_request(@request))
yield client if block_given?
return client
end
it_behaves_like "a websocket server" do
let(:version) { 3 }
end
it_behaves_like "a WebSocket server drafts 3 and above" do
let(:version) { 3 }
end
# These examples are straight from the spec
# http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-03#section-4.6
describe "examples from the spec" do
it "should accept a single-frame text message" do
em {
start_server { |ws|
ws.onmessage { |msg|
msg.should == 'Hello'
done
}
}
start_client { |client|
client.onopen {
client.send_data("\x04\x05Hello")
}
}
}
end
it "should accept a fragmented text message" do
em {
start_server { |ws|
ws.onmessage { |msg|
msg.should == 'Hello'
done
}
}
connection = start_client
# Send frame
connection.onopen {
connection.send_data("\x84\x03Hel")
connection.send_data("\x00\x02lo")
}
}
end
it "should accept a ping request and respond with the same body" do
em {
start_server
connection = start_client
# Send frame
connection.onopen {
connection.send_data("\x02\x05Hello")
}
connection.onmessage { |frame|
next if frame.nil?
frame.should == "\x03\x05Hello"
done
}
}
end
it "should accept a 256 bytes binary message in a single frame" do
em {
data = "a" * 256
start_server { |ws|
ws.onbinary { |msg|
msg.encoding.should == Encoding.find("BINARY") if defined?(Encoding)
msg.should == data
done
}
}
connection = start_client
# Send frame
connection.onopen {
connection.send_data("\x05\x7E\x01\x00" + data)
}
}
end
it "should accept a 64KiB binary message in a single frame" do
em {
data = "a" * 65536
start_server { |ws|
ws.onbinary { |msg|
msg.encoding.should == Encoding.find("BINARY") if defined?(Encoding)
msg.should == data
done
}
}
connection = start_client
# Send frame
connection.onopen {
connection.send_data("\x05\x7F\x00\x00\x00\x00\x00\x01\x00\x00" + data)
}
}
end
end
describe "close handling" do
it "should respond to a new close frame with a close frame" do
em {
start_server
connection = start_client
# Send close frame
connection.onopen {
connection.send_data("\x01\x00")
}
# Check that close ack received
connection.onmessage { |frame|
frame.should == "\x01\x00"
done
}
}
end
it "should close the connection on receiving a close acknowlegement and call onclose with close code 1005 and was_clean=true (initiated by server)" do
em {
ack_received = false
start_server { |ws|
ws.onopen {
# 2. Send a close frame
EM.next_tick {
ws.close
}
}
# 5. Onclose event on server
ws.onclose { |event|
event.should == {
:code => 1005,
:reason => "",
:was_clean => true,
}
done
}
}
# 1. Create a fake client which sends draft 76 handshake
connection = start_client
# 3. Check that close frame recieved and acknowlege it
connection.onmessage { |frame|
frame.should == "\x01\x00"
ack_received = true
connection.send_data("\x01\x00")
}
# 4. Check that connection is closed _after_ the ack
connection.onclose {
ack_received.should == true
}
}
end
# it "should repur"
#
it "should return close code 1005 and was_clean=true after closing handshake (initiated by client)" do
em {
start_server { |ws|
ws.onclose { |event|
event.should == {
:code => 1005,
:reason => "",
:was_clean => true,
}
done
}
}
start_client { |client|
client.onopen {
client.send_data("\x01\x00")
}
}
}
end
it "should not allow data frame to be sent after close frame sent" do
em {
start_server { |ws|
ws.onopen {
# 2. Send a close frame
EM.next_tick {
ws.close
}
# 3. Check that exception raised if I attempt to send more data
EM.add_timer(0.1) {
lambda {
ws.send('hello world')
}.should raise_error(EM::WebSocket::WebSocketError, 'Cannot send data frame since connection is closing')
done
}
}
}
# 1. Create a fake client which sends draft 76 handshake
start_client
}
end
it "should still respond to control frames after close frame sent" do
em {
start_server { |ws|
ws.onopen {
# 2. Send a close frame
EM.next_tick {
ws.close
}
}
}
# 1. Create a fake client which sends draft 76 handshake
connection = start_client
connection.onmessage { |frame|
if frame == "\x01\x00"
# 3. After the close frame is received send a ping frame, but
# don't respond with a close ack
connection.send_data("\x02\x05Hello")
else
# 4. Check that the pong is received
frame.should == "\x03\x05Hello"
done
end
}
}
end
it "should report that close codes are not supported" do
em {
start_server { |ws|
ws.onopen {
ws.supports_close_codes?.should == false
done
}
}
start_client
}
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft05_spec.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft05_spec.rb | require 'helper'
describe "draft05" do
include EM::SpecHelper
default_timeout 1
before :each do
@request = {
:port => 80,
:method => "GET",
:path => "/demo",
:headers => {
'Host' => 'example.com',
'Upgrade' => 'websocket',
'Connection' => 'Upgrade',
'Sec-WebSocket-Key' => 'dGhlIHNhbXBsZSBub25jZQ==',
'Sec-WebSocket-Protocol' => 'sample',
'Sec-WebSocket-Origin' => 'http://example.com',
'Sec-WebSocket-Version' => '5'
}
}
end
def start_client
client = EM.connect('0.0.0.0', 12345, Draft05FakeWebSocketClient)
client.send_data(format_request(@request))
yield client if block_given?
return client
end
it_behaves_like "a websocket server" do
let(:version) { 5 }
end
it_behaves_like "a WebSocket server drafts 3 and above" do
let(:version) { 5 }
end
it "should report that close codes are not supported" do
em {
start_server { |ws|
ws.onopen {
ws.supports_close_codes?.should == false
done
}
}
start_client
}
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft06_spec.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft06_spec.rb | require 'helper'
describe "draft06" do
include EM::SpecHelper
default_timeout 1
before :each do
@request = {
:port => 80,
:method => "GET",
:path => "/demo",
:headers => {
'Host' => 'example.com',
'Upgrade' => 'websocket',
'Connection' => 'Upgrade',
'Sec-WebSocket-Key' => 'dGhlIHNhbXBsZSBub25jZQ==',
'Sec-WebSocket-Protocol' => 'sample',
'Sec-WebSocket-Origin' => 'http://example.com',
'Sec-WebSocket-Version' => '6'
}
}
@response = {
:protocol => "HTTP/1.1 101 Switching Protocols\r\n",
:headers => {
"Upgrade" => "websocket",
"Connection" => "Upgrade",
"Sec-WebSocket-Accept" => "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=",
}
}
end
def start_client
client = EM.connect('0.0.0.0', 12345, Draft05FakeWebSocketClient)
client.send_data(format_request(@request))
yield client if block_given?
return client
end
it_behaves_like "a websocket server" do
let(:version) { 6 }
end
it_behaves_like "a WebSocket server drafts 3 and above" do
let(:version) { 6 }
end
it "should open connection" do
em {
start_server { |server|
server.onopen {
server.instance_variable_get(:@handler).class.should == EventMachine::WebSocket::Handler06
}
}
start_client { |client|
client.onopen {
client.handshake_response.lines.sort.
should == format_response(@response).lines.sort
done
}
}
}
end
it "should accept a single-frame text message (masked)" do
em {
start_server { |server|
server.onmessage { |msg|
msg.should == 'Hello'
if msg.respond_to?(:encoding)
msg.encoding.should == Encoding.find("UTF-8")
end
done
}
server.onerror {
fail
}
}
start_client { |client|
client.onopen {
client.send_data("\x00\x00\x01\x00\x84\x05Ielln")
}
}
}
end
it "should return close code and reason if closed via handshake" do
em {
start_server { |ws|
ws.onclose { |event|
# 2. Receive close event in server
event.should == {
:code => 4004,
:reason => "close reason",
:was_clean => true,
}
done
}
}
start_client { |client|
client.onopen {
# 1: Send close handshake
close_data = [4004].pack('n')
close_data << "close reason"
client.send_frame(:close, close_data)
}
}
}
end
it "should return close code 1005 if no code was specified" do
em {
start_server { |ws|
ws.onclose { |event|
event.should == {
:code => 1005,
:reason => "",
:was_clean => true,
}
done
}
}
start_client { |client|
client.onopen {
client.send_frame(:close, '')
}
}
}
end
it "should report that close codes are supported" do
em {
start_server { |ws|
ws.onopen {
ws.supports_close_codes?.should == true
done
}
}
start_client
}
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft75_spec.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/integration/draft75_spec.rb | require 'helper'
# These integration tests are older and use a different testing style to the
# integration tests for newer drafts. They use EM::HttpRequest which happens
# to currently estabish a websocket connection using the draft75 protocol.
#
describe "WebSocket server draft75" do
include EM::SpecHelper
default_timeout 1
def start_client
client = Draft75WebSocketClient.new
yield client if block_given?
return client
end
it_behaves_like "a websocket server" do
let(:version) { 75 }
end
it "should automatically complete WebSocket handshake" do
em {
MSG = "Hello World!"
EventMachine.add_timer(0.1) do
ws = EventMachine::WebSocketClient.connect('ws://127.0.0.1:12345/')
ws.errback { fail }
ws.callback { }
ws.stream { |msg|
msg.data.should == MSG
EventMachine.stop
}
end
start_server { |ws|
ws.onopen {
ws.send MSG
}
}
}
end
it "should split multiple messages into separate callbacks" do
em {
messages = %w[1 2]
received = []
EventMachine.add_timer(0.1) do
ws = EventMachine::WebSocketClient.connect('ws://127.0.0.1:12345/')
ws.errback { fail }
ws.stream {|msg|}
ws.callback {
ws.send_msg messages[0]
ws.send_msg messages[1]
}
end
start_server { |ws|
ws.onopen {}
ws.onclose {}
ws.onmessage {|msg|
msg.should == messages[received.size]
received.push msg
EventMachine.stop if received.size == messages.size
}
}
}
end
it "should call onclose callback when client closes connection" do
em {
EventMachine.add_timer(0.1) do
ws = EventMachine::WebSocketClient.connect('ws://127.0.0.1:12345/')
ws.errback { fail }
ws.callback {
ws.close_connection
}
ws.stream{|msg|}
end
start_server { |ws|
ws.onopen {}
ws.onclose {
ws.state.should == :closed
EventMachine.stop
}
}
}
end
it "should call onerror callback with raised exception and close connection on bad handshake" do
em {
EventMachine.add_timer(0.1) do
http = EM::HttpRequest.new('http://127.0.0.1:12345/').get
http.errback { }
http.callback { fail }
end
start_server { |ws|
ws.onopen { fail }
ws.onclose { EventMachine.stop }
ws.onerror {|e|
e.should be_an_instance_of EventMachine::WebSocket::HandshakeError
e.message.should match('Not an upgrade request')
EventMachine.stop
}
}
}
end
it "should report that close codes are not supported" do
em {
start_server { |ws|
ws.onopen {
ws.supports_close_codes?.should == false
done
}
}
start_client
}
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/unit/framing_spec.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/unit/framing_spec.rb | # encoding: BINARY
require 'helper'
describe EM::WebSocket::Framing03 do
class FramingContainer
include EM::WebSocket::Framing03
def initialize
@connection = Object.new
def @connection.max_frame_size
1000000
end
end
def <<(data)
@data << data
process_data
end
def debug(*args); end
end
before :each do
@f = FramingContainer.new
@f.initialize_framing
end
describe "basic examples" do
it "connection close" do
@f.should_receive(:message).with(:close, '', '')
@f << 0b00000001
@f << 0b00000000
end
it "ping" do
@f.should_receive(:message).with(:ping, '', '')
@f << 0b00000010
@f << 0b00000000
end
it "pong" do
@f.should_receive(:message).with(:pong, '', '')
@f << 0b00000011
@f << 0b00000000
end
it "text" do
@f.should_receive(:message).with(:text, '', 'foo')
@f << 0b00000100
@f << 0b00000011
@f << 'foo'
end
it "Text in two frames" do
@f.should_receive(:message).with(:text, '', 'hello world')
@f << 0b10000100
@f << 0b00000110
@f << "hello "
@f << 0b00000000
@f << 0b00000101
@f << "world"
end
it "2 byte extended payload length text frame" do
data = 'a' * 256
@f.should_receive(:message).with(:text, '', data)
@f << 0b00000100 # Single frame, text
@f << 0b01111110 # Length 126 (so read 2 bytes)
@f << 0b00000001 # Two bytes in network byte order (256)
@f << 0b00000000
@f << data
end
end
# These examples are straight from the spec
# http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-03#section-4.6
describe "examples from the spec" do
it "a single-frame text message" do
@f.should_receive(:message).with(:text, '', 'Hello')
@f << "\x04\x05Hello"
end
it "a fragmented text message" do
@f.should_receive(:message).with(:text, '', 'Hello')
@f << "\x84\x03Hel"
@f << "\x00\x02lo"
end
it "Ping request and response" do
@f.should_receive(:message).with(:ping, '', 'Hello')
@f << "\x02\x05Hello"
end
it "256 bytes binary message in a single frame" do
data = "a"*256
@f.should_receive(:message).with(:binary, '', data)
@f << "\x05\x7E\x01\x00" + data
end
it "64KiB binary message in a single frame" do
data = "a"*65536
@f.should_receive(:message).with(:binary, '', data)
@f << "\x05\x7F\x00\x00\x00\x00\x00\x01\x00\x00" + data
end
end
describe "other tests" do
it "should accept a fragmented unmasked text message in 3 frames" do
@f.should_receive(:message).with(:text, '', 'Hello world')
@f << "\x84\x03Hel"
@f << "\x80\x02lo"
@f << "\x00\x06 world"
end
end
describe "error cases" do
it "should raise an exception on continuation frame without preceeding more frame" do
lambda {
@f << 0b00000000 # Single frame, continuation
@f << 0b00000001 # Length 1
@f << 'f'
}.should raise_error(EM::WebSocket::WebSocketError, 'Continuation frame not expected')
end
end
end
# These examples are straight from the spec
# http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-03#section-4.6
describe EM::WebSocket::Framing04 do
class FramingContainer04
include EM::WebSocket::Framing04
def initialize
@connection = Object.new
def @connection.max_frame_size
1000000
end
end
def <<(data)
@data << data
process_data
end
def debug(*args); end
end
before :each do
@f = FramingContainer04.new
@f.initialize_framing
end
describe "examples from the spec" do
it "a single-frame text message" do
@f.should_receive(:message).with(:text, '', 'Hello')
@f << "\x84\x05\x48\x65\x6c\x6c\x6f" # "\x84\x05Hello"
end
it "a fragmented text message" do
@f.should_receive(:message).with(:text, '', 'Hello')
@f << "\x04\x03Hel"
@f << "\x80\x02lo"
end
it "Ping request" do
@f.should_receive(:message).with(:ping, '', 'Hello')
@f << "\x82\x05Hello"
end
it "a pong response" do
@f.should_receive(:message).with(:pong, '', 'Hello')
@f << "\x83\x05Hello"
end
it "256 bytes binary message in a single frame" do
data = "a"*256
@f.should_receive(:message).with(:binary, '', data)
@f << "\x85\x7E\x01\x00" + data
end
it "64KiB binary message in a single frame" do
data = "a"*65536
@f.should_receive(:message).with(:binary, '', data)
@f << "\x85\x7F\x00\x00\x00\x00\x00\x01\x00\x00" + data
end
end
describe "other tests" do
it "should accept a fragmented unmasked text message in 3 frames" do
@f.should_receive(:message).with(:text, '', 'Hello world')
@f << "\x04\x03Hel"
@f << "\x00\x02lo"
@f << "\x80\x06 world"
end
end
end
describe EM::WebSocket::Framing07 do
class FramingContainer07
include EM::WebSocket::Framing07
def initialize
@connection = Object.new
def @connection.max_frame_size
1000000
end
end
def <<(data)
@data << data
process_data
end
def debug(*args); end
end
before :each do
@f = FramingContainer07.new
@f.initialize_framing
end
# These examples are straight from the spec
# http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07#section-4.6
describe "examples from the spec" do
it "a single-frame unmakedtext message" do
@f.should_receive(:message).with(:text, '', 'Hello')
@f << "\x81\x05\x48\x65\x6c\x6c\x6f" # "\x84\x05Hello"
end
it "a single-frame masked text message" do
@f.should_receive(:message).with(:text, '', 'Hello')
@f << "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58" # "\x84\x05Hello"
end
it "a fragmented unmasked text message" do
@f.should_receive(:message).with(:text, '', 'Hello')
@f << "\x01\x03Hel"
@f << "\x80\x02lo"
end
it "Ping request" do
@f.should_receive(:message).with(:ping, '', 'Hello')
@f << "\x89\x05Hello"
end
it "a pong response" do
@f.should_receive(:message).with(:pong, '', 'Hello')
@f << "\x8a\x05Hello"
end
it "256 bytes binary message in a single unmasked frame" do
data = "a"*256
@f.should_receive(:message).with(:binary, '', data)
@f << "\x82\x7E\x01\x00" + data
end
it "64KiB binary message in a single unmasked frame" do
data = "a"*65536
@f.should_receive(:message).with(:binary, '', data)
@f << "\x82\x7F\x00\x00\x00\x00\x00\x01\x00\x00" + data
end
end
describe "other tests" do
it "should raise a WSProtocolError if an invalid frame type is requested" do
lambda {
# Opcode 3 is not supported by this draft
@f << "\x83\x05Hello"
}.should raise_error(EventMachine::WebSocket::WSProtocolError, "Unknown opcode 3")
end
it "should accept a fragmented unmasked text message in 3 frames" do
@f.should_receive(:message).with(:text, '', 'Hello world')
@f << "\x01\x03Hel"
@f << "\x00\x02lo"
@f << "\x80\x06 world"
end
it "should raise if non-fin frame is followed by a non-continuation data frame (continuation frame would be expected)" do
lambda {
@f << 0b00000001 # Not fin, text
@f << 0b00000001 # Length 1
@f << 'f'
@f << 0b10000001 # fin, text (continutation expected)
@f << 0b00000001 # Length 1
@f << 'b'
}.should raise_error(EM::WebSocket::WebSocketError, 'Continuation frame expected')
end
it "should raise on non-fin control frames (control frames must not be fragmented)" do
lambda {
@f << 0b00001010 # Not fin, pong (opcode 10)
@f << 0b00000000 # Length 1
}.should raise_error(EM::WebSocket::WebSocketError, 'Control frames must not be fragmented')
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/unit/masking_spec.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/unit/masking_spec.rb | # encoding: BINARY
require 'helper'
describe EM::WebSocket::MaskedString do
it "should allow reading 4 byte mask and unmasking byte / bytes" do
t = EM::WebSocket::MaskedString.new("\x00\x00\x00\x01\x00\x01\x00\x01")
t.read_mask
t.getbyte(3).should == 0x00
t.getbytes(4, 4).should == "\x00\x01\x00\x00"
t.getbytes(5, 3).should == "\x01\x00\x00"
end
it "should return nil from getbyte if index requested is out of range" do
t = EM::WebSocket::MaskedString.new("\x00\x00\x00\x00\x53")
t.read_mask
t.getbyte(4).should == 0x53
t.getbyte(5).should == nil
end
it "should allow switching masking on and off" do
t = EM::WebSocket::MaskedString.new("\x02\x00\x00\x00\x03")
t.getbyte(4).should == 0x03
t.read_mask
t.getbyte(4).should == 0x01
t.unset_mask
t.getbyte(4).should == 0x03
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/unit/handshake_spec.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/spec/unit/handshake_spec.rb | require 'helper'
describe EM::WebSocket::Handshake do
def handshake(request, secure = false)
handshake = EM::WebSocket::Handshake.new(secure)
handshake.receive_data(format_request(request))
handshake
end
before :each do
@request = {
:port => 80,
:method => "GET",
:path => "/demo",
:headers => {
'Host' => 'example.com',
'Connection' => 'Upgrade',
'Sec-WebSocket-Key2' => '12998 5 Y3 1 .P00',
'Sec-WebSocket-Protocol' => 'sample',
'Upgrade' => 'WebSocket',
'Sec-WebSocket-Key1' => '4 @1 46546xW%0l 1 5',
'Origin' => 'http://example.com'
},
:body => '^n:ds[4U'
}
@secure_request = @request.merge(:port => 443)
@response = {
:headers => {
"Upgrade" => "WebSocket",
"Connection" => "Upgrade",
"Sec-WebSocket-Location" => "ws://example.com/demo",
"Sec-WebSocket-Origin" => "http://example.com",
"Sec-WebSocket-Protocol" => "sample"
},
:body => "8jKS\'y:G*Co,Wxa-"
}
@secure_response = @response.merge(:headers => @response[:headers].merge('Sec-WebSocket-Location' => "wss://example.com/demo"))
end
it "should handle good request" do
handshake(@request).should succeed_with_upgrade(@response)
end
it "should handle good request to secure default port if secure mode is enabled" do
handshake(@secure_request, true).
should succeed_with_upgrade(@secure_response)
end
it "should not handle good request to secure default port if secure mode is disabled" do
handshake(@secure_request, false).
should_not succeed_with_upgrade(@secure_response)
end
it "should handle good request on nondefault port" do
@request[:port] = 8081
@request[:headers]['Host'] = 'example.com:8081'
@response[:headers]['Sec-WebSocket-Location'] =
'ws://example.com:8081/demo'
handshake(@request).should succeed_with_upgrade(@response)
end
it "should handle good request to secure nondefault port" do
@secure_request[:port] = 8081
@secure_request[:headers]['Host'] = 'example.com:8081'
@secure_response[:headers]['Sec-WebSocket-Location'] = 'wss://example.com:8081/demo'
handshake(@secure_request, true).
should succeed_with_upgrade(@secure_response)
end
it "should handle good request with no protocol" do
@request[:headers].delete('Sec-WebSocket-Protocol')
@response[:headers].delete("Sec-WebSocket-Protocol")
handshake(@request).should succeed_with_upgrade(@response)
end
it "should handle extra headers by simply ignoring them" do
@request[:headers]['EmptyValue'] = ""
@request[:headers]['AKey'] = "AValue"
handshake(@request).should succeed_with_upgrade(@response)
end
it "should raise error on HTTP request" do
@request[:headers] = {
'Host' => 'www.google.com',
'User-Agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 GTB6 GTBA',
'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language' => 'en-us,en;q=0.5',
'Accept-Encoding' => 'gzip,deflate',
'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Keep-Alive' => '300',
'Connection' => 'keep-alive',
}
handshake(@request).should fail_with_error(EM::WebSocket::HandshakeError)
end
it "should raise error on wrong method" do
@request[:method] = 'POST'
handshake(@request).should fail_with_error(EM::WebSocket::HandshakeError)
end
it "should raise error if upgrade header incorrect" do
@request[:headers]['Upgrade'] = 'NonWebSocket'
handshake(@request).should fail_with_error(EM::WebSocket::HandshakeError)
end
it "should raise error if Sec-WebSocket-Protocol is empty" do
@request[:headers]['Sec-WebSocket-Protocol'] = ''
handshake(@request).should fail_with_error(EM::WebSocket::HandshakeError)
end
%w[Sec-WebSocket-Key1 Sec-WebSocket-Key2].each do |header|
it "should raise error if #{header} has zero spaces" do
@request[:headers][header] = 'nospaces'
handshake(@request).
should fail_with_error(EM::WebSocket::HandshakeError, 'Websocket Key1 or Key2 does not contain spaces - this is a symptom of a cross-protocol attack')
end
end
it "should raise error if Sec-WebSocket-Key1 is missing" do
@request[:headers].delete("Sec-WebSocket-Key1")
# The error message isn't correct since key1 is used to heuristically
# determine the protocol version in use, however this test at least checks
# that the handshake does correctly fail
handshake(@request).
should fail_with_error(EM::WebSocket::HandshakeError, 'Extra bytes after header')
end
it "should raise error if Sec-WebSocket-Key2 is missing" do
@request[:headers].delete("Sec-WebSocket-Key2")
handshake(@request).
should fail_with_error(EM::WebSocket::HandshakeError, 'WebSocket key1 or key2 is missing')
end
it "should raise error if spaces do not divide numbers in Sec-WebSocket-Key* " do
@request[:headers]['Sec-WebSocket-Key2'] = '12998 5 Y3 1.P00'
handshake(@request).
should fail_with_error(EM::WebSocket::HandshakeError, 'Invalid Key "12998 5 Y3 1.P00"')
end
it "should raise error if the HTTP header is empty" do
handshake = EM::WebSocket::Handshake.new(false)
handshake.receive_data("\r\n\r\nfoobar")
handshake.
should fail_with_error(EM::WebSocket::HandshakeError, 'Invalid HTTP header: Could not parse data entirely (4 != 10)')
end
# This might seems crazy, but very occasionally we saw multiple "Upgrade:
# WebSocket" headers in the wild. RFC 4.2.1 isn't particularly clear on this
# point, so for now I have decided not to accept --@mloughran
it "should raise error on multiple upgrade headers" do
handshake = EM::WebSocket::Handshake.new(false)
# Add a duplicate upgrade header
headers = format_request(@request)
upgrade_header = "Upgrade: WebSocket\r\n"
headers.gsub!(upgrade_header, "#{upgrade_header}#{upgrade_header}")
handshake.receive_data(headers)
handshake.errback { |e|
e.class.should == EM::WebSocket::HandshakeError
e.message.should == 'Invalid upgrade header: ["WebSocket", "WebSocket"]'
}
end
it "should cope with requests where the header is split" do
request = format_request(@request)
incomplete_request = request[0...(request.length / 2)]
rest = request[(request.length / 2)..-1]
handshake = EM::WebSocket::Handshake.new(false)
handshake.receive_data(incomplete_request)
handshake.instance_variable_get(:@deferred_status).should == nil
# Send the remaining header
handshake.receive_data(rest)
handshake(@request).should succeed_with_upgrade(@response)
end
it "should cope with requests where the third key is split" do
request = format_request(@request)
# Removes last two bytes of the third key
incomplete_request = request[0..-3]
rest = request[-2..-1]
handshake = EM::WebSocket::Handshake.new(false)
handshake.receive_data(incomplete_request)
handshake.instance_variable_get(:@deferred_status).should == nil
# Send the remaining third key
handshake.receive_data(rest)
handshake(@request).should succeed_with_upgrade(@response)
end
it "should fail if the request URI is invalid" do
@request[:path] = "/%"
handshake(@request).should \
fail_with_error(EM::WebSocket::HandshakeError, 'Invalid request URI: /%')
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/examples/ping.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/examples/ping.rb | require File.expand_path('../../lib/em-websocket', __FILE__)
EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080, :debug => false) do |ws|
timer = nil
ws.onopen {
puts "Ping supported: #{ws.pingable?}"
timer = EM.add_periodic_timer(1) {
p ["Sent ping", ws.ping('hello')]
}
}
ws.onpong { |value|
puts "Received pong: #{value}"
}
ws.onping { |value|
puts "Received ping: #{value}"
}
ws.onclose {
EM.cancel_timer(timer)
puts "WebSocket closed"
}
ws.onerror { |e|
puts "Error: #{e.message}"
}
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/examples/echo.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/examples/echo.rb | require File.expand_path('../../lib/em-websocket', __FILE__)
EM.run {
EM::WebSocket.run(:host => "0.0.0.0", :port => 8080, :debug => false) do |ws|
ws.onopen { |handshake|
puts "WebSocket opened #{{
:path => handshake.path,
:query => handshake.query,
:origin => handshake.origin,
}}"
ws.send "Hello Client!"
}
ws.onmessage { |msg|
ws.send "Pong: #{msg}"
}
ws.onclose {
puts "WebSocket closed"
}
ws.onerror { |e|
puts "Error: #{e.message}"
}
end
}
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/examples/multicast.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/examples/multicast.rb | require 'em-websocket'
# requires the twitter-stream gem
require 'twitter/json_stream'
require 'json'
#
# broadcast all ruby related tweets to all connected users!
#
username = ARGV.shift
password = ARGV.shift
raise "need username and password" if !username or !password
EventMachine.run {
@channel = EM::Channel.new
@twitter = Twitter::JSONStream.connect(
:path => '/1/statuses/filter.json?track=ruby',
:auth => "#{username}:#{password}",
:ssl => true
)
@twitter.each_item do |status|
status = JSON.parse(status)
@channel.push "#{status['user']['screen_name']}: #{status['text']}"
end
EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080, :debug => true) do |ws|
ws.onopen {
sid = @channel.subscribe { |msg| ws.send msg }
@channel.push "#{sid} connected!"
ws.onmessage { |msg|
@channel.push "<#{sid}>: #{msg}"
}
ws.onclose {
@channel.unsubscribe(sid)
}
}
end
puts "Server started"
}
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket.rb | $:.unshift(File.dirname(__FILE__) + '/../lib')
require "eventmachine"
%w[
debugger websocket connection
handshake
handshake75 handshake76 handshake04
framing76 framing03 framing04 framing05 framing07
close75 close03 close05 close06
masking04
message_processor_03 message_processor_06
handler handler75 handler76 handler03 handler05 handler06 handler07 handler08 handler13
].each do |file|
require "em-websocket/#{file}"
end
unless ''.respond_to?(:getbyte)
class String
def getbyte(i)
self[i]
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler05.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler05.rb | module EventMachine
module WebSocket
class Handler05 < Handler
include Framing05
include MessageProcessor03
include Close05
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler03.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler03.rb | module EventMachine
module WebSocket
class Handler03 < Handler
include Framing03
include MessageProcessor03
include Close03
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/framing04.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/framing04.rb | # encoding: BINARY
module EventMachine
module WebSocket
# The only difference between draft 03 framing and draft 04 framing is
# that the MORE bit has been changed to a FIN bit
module Framing04
include Framing03
private
def fin; true; end
end
end
end | ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler76.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler76.rb | # encoding: BINARY
module EventMachine
module WebSocket
class Handler76 < Handler
include Handshake76
include Framing76
include Close75
# "\377\000" is octet version and "\xff\x00" is hex version
TERMINATE_STRING = "\xff\x00"
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/version.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/version.rb | module EventMachine
module Websocket
VERSION = "0.5.1"
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/framing03.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/framing03.rb | # encoding: BINARY
module EventMachine
module WebSocket
module Framing03
def initialize_framing
@data = ''
@application_data_buffer = '' # Used for MORE frames
@frame_type = nil
end
def process_data
error = false
while !error && @data.size > 1
pointer = 0
more = ((@data.getbyte(pointer) & 0b10000000) == 0b10000000) ^ fin
# Ignoring rsv1-3 for now
opcode = @data.getbyte(0) & 0b00001111
pointer += 1
# Ignoring rsv4
length = @data.getbyte(pointer) & 0b01111111
pointer += 1
payload_length = case length
when 127 # Length defined by 8 bytes
# Check buffer size
if @data.getbyte(pointer+8-1) == nil
debug [:buffer_incomplete, @data]
error = true
next
end
# Only using the last 4 bytes for now, till I work out how to
# unpack 8 bytes. I'm sure 4GB frames will do for now :)
l = @data[(pointer+4)..(pointer+7)].unpack('N').first
pointer += 8
l
when 126 # Length defined by 2 bytes
# Check buffer size
if @data.getbyte(pointer+2-1) == nil
debug [:buffer_incomplete, @data]
error = true
next
end
l = @data[pointer..(pointer+1)].unpack('n').first
pointer += 2
l
else
length
end
if payload_length > @connection.max_frame_size
raise WSMessageTooBigError, "Frame length too long (#{payload_length} bytes)"
end
# Check buffer size
if @data.getbyte(pointer+payload_length-1) == nil
debug [:buffer_incomplete, @data]
error = true
next
end
# Throw away data up to pointer
@data.slice!(0...pointer)
# Read application data
application_data = @data.slice!(0...payload_length)
frame_type = opcode_to_type(opcode)
if frame_type == :continuation && !@frame_type
raise WSProtocolError, 'Continuation frame not expected'
end
if more
debug [:moreframe, frame_type, application_data]
@application_data_buffer << application_data
# The message type is passed in the first frame
@frame_type ||= frame_type
else
# Message is complete
if frame_type == :continuation
@application_data_buffer << application_data
message(@frame_type, '', @application_data_buffer)
@application_data_buffer = ''
@frame_type = nil
else
message(frame_type, '', application_data)
end
end
end # end while
end
def send_frame(frame_type, application_data)
debug [:sending_frame, frame_type, application_data]
if @state == :closing && data_frame?(frame_type)
raise WebSocketError, "Cannot send data frame since connection is closing"
end
frame = ''
opcode = type_to_opcode(frame_type)
byte1 = opcode # since more, rsv1-3 are 0
frame << byte1
length = application_data.size
if length <= 125
byte2 = length # since rsv4 is 0
frame << byte2
elsif length < 65536 # write 2 byte length
frame << 126
frame << [length].pack('n')
else # write 8 byte length
frame << 127
frame << [length >> 32, length & 0xFFFFFFFF].pack("NN")
end
frame << application_data
@connection.send_data(frame)
end
def send_text_frame(data)
send_frame(:text, data)
end
private
# This allows flipping the more bit to fin for draft 04
def fin; false; end
FRAME_TYPES = {
:continuation => 0,
:close => 1,
:ping => 2,
:pong => 3,
:text => 4,
:binary => 5
}
FRAME_TYPES_INVERSE = FRAME_TYPES.invert
# Frames are either data frames or control frames
DATA_FRAMES = [:text, :binary, :continuation]
def type_to_opcode(frame_type)
FRAME_TYPES[frame_type] || raise("Unknown frame type")
end
def opcode_to_type(opcode)
FRAME_TYPES_INVERSE[opcode] || raise(WSProtocolError, "Unknown opcode #{opcode}")
end
def data_frame?(type)
DATA_FRAMES.include?(type)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/framing05.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/framing05.rb | # encoding: BINARY
module EventMachine
module WebSocket
module Framing05
def initialize_framing
@data = MaskedString.new
@application_data_buffer = '' # Used for MORE frames
@frame_type = nil
end
def process_data
error = false
while !error && @data.size > 5 # mask plus first byte present
pointer = 0
@data.read_mask
pointer += 4
fin = (@data.getbyte(pointer) & 0b10000000) == 0b10000000
# Ignoring rsv1-3 for now
opcode = @data.getbyte(pointer) & 0b00001111
pointer += 1
# Ignoring rsv4
length = @data.getbyte(pointer) & 0b01111111
pointer += 1
payload_length = case length
when 127 # Length defined by 8 bytes
# Check buffer size
if @data.getbyte(pointer+8-1) == nil
debug [:buffer_incomplete, @data]
error = true
next
end
# Only using the last 4 bytes for now, till I work out how to
# unpack 8 bytes. I'm sure 4GB frames will do for now :)
l = @data.getbytes(pointer+4, 4).unpack('N').first
pointer += 8
l
when 126 # Length defined by 2 bytes
# Check buffer size
if @data.getbyte(pointer+2-1) == nil
debug [:buffer_incomplete, @data]
error = true
next
end
l = @data.getbytes(pointer, 2).unpack('n').first
pointer += 2
l
else
length
end
if payload_length > @connection.max_frame_size
raise WSMessageTooBigError, "Frame length too long (#{payload_length} bytes)"
end
# Check buffer size
if @data.getbyte(pointer+payload_length-1) == nil
debug [:buffer_incomplete, @data]
error = true
next
end
# Read application data
application_data = @data.getbytes(pointer, payload_length)
pointer += payload_length
# Throw away data up to pointer
@data.unset_mask
@data.slice!(0...pointer)
frame_type = opcode_to_type(opcode)
if frame_type == :continuation && !@frame_type
raise WSProtocolError, 'Continuation frame not expected'
end
if !fin
debug [:moreframe, frame_type, application_data]
@application_data_buffer << application_data
@frame_type = frame_type
else
# Message is complete
if frame_type == :continuation
@application_data_buffer << application_data
message(@frame_type, '', @application_data_buffer)
@application_data_buffer = ''
@frame_type = nil
else
message(frame_type, '', application_data)
end
end
end # end while
end
def send_frame(frame_type, application_data)
debug [:sending_frame, frame_type, application_data]
if @state == :closing && data_frame?(frame_type)
raise WebSocketError, "Cannot send data frame since connection is closing"
end
frame = ''
opcode = type_to_opcode(frame_type)
byte1 = opcode | 0b10000000 # fin bit set, rsv1-3 are 0
frame << byte1
length = application_data.size
if length <= 125
byte2 = length # since rsv4 is 0
frame << byte2
elsif length < 65536 # write 2 byte length
frame << 126
frame << [length].pack('n')
else # write 8 byte length
frame << 127
frame << [length >> 32, length & 0xFFFFFFFF].pack("NN")
end
frame << application_data
@connection.send_data(frame)
end
def send_text_frame(data)
send_frame(:text, data)
end
private
FRAME_TYPES = {
:continuation => 0,
:close => 1,
:ping => 2,
:pong => 3,
:text => 4,
:binary => 5
}
FRAME_TYPES_INVERSE = FRAME_TYPES.invert
# Frames are either data frames or control frames
DATA_FRAMES = [:text, :binary, :continuation]
def type_to_opcode(frame_type)
FRAME_TYPES[frame_type] || raise("Unknown frame type")
end
def opcode_to_type(opcode)
FRAME_TYPES_INVERSE[opcode] || raise(WSProtocolError, "Unknown opcode #{opcode}")
end
def data_frame?(type)
DATA_FRAMES.include?(type)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler75.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler75.rb | module EventMachine
module WebSocket
class Handler75 < Handler
include Handshake75
include Framing76
include Close75
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handshake76.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handshake76.rb | require 'digest/md5'
module EventMachine::WebSocket
module Handshake76
class << self
def handshake(headers, path, secure)
challenge_response = solve_challenge(
headers['sec-websocket-key1'],
headers['sec-websocket-key2'],
headers['third-key']
)
scheme = (secure ? "wss" : "ws")
location = "#{scheme}://#{headers['host']}#{path}"
upgrade = "HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
upgrade << "Upgrade: WebSocket\r\n"
upgrade << "Connection: Upgrade\r\n"
upgrade << "Sec-WebSocket-Location: #{location}\r\n"
upgrade << "Sec-WebSocket-Origin: #{headers['origin']}\r\n"
if protocol = headers['sec-websocket-protocol']
validate_protocol!(protocol)
upgrade << "Sec-WebSocket-Protocol: #{protocol}\r\n"
end
upgrade << "\r\n"
upgrade << challenge_response
return upgrade
end
private
def solve_challenge(first, second, third)
# Refer to 5.2 4-9 of the draft 76
sum = [numbers_over_spaces(first)].pack("N*") +
[numbers_over_spaces(second)].pack("N*") +
third
Digest::MD5.digest(sum)
end
def numbers_over_spaces(string)
unless string
raise HandshakeError, "WebSocket key1 or key2 is missing"
end
numbers = string.scan(/[0-9]/).join.to_i
spaces = string.scan(/ /).size
# As per 5.2.5, abort the connection if spaces are zero.
raise HandshakeError, "Websocket Key1 or Key2 does not contain spaces - this is a symptom of a cross-protocol attack" if spaces == 0
# As per 5.2.6, abort if numbers is not an integral multiple of spaces
if numbers % spaces != 0
raise HandshakeError, "Invalid Key #{string.inspect}"
end
quotient = numbers / spaces
if quotient > 2**32-1
raise HandshakeError, "Challenge computation out of range for key #{string.inspect}"
end
return quotient
end
def validate_protocol!(protocol)
raise HandshakeError, "Invalid WebSocket-Protocol: empty" if protocol.empty?
# TODO: Validate characters
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/debugger.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/debugger.rb | module EventMachine
module WebSocket
module Debugger
private
def debug(*data)
if @debug
require 'pp'
pp data
puts
end
end
end
end
end | ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/close06.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/close06.rb | module EventMachine
module WebSocket
module Close06
def close_websocket(code, body)
if code
close_data = [code].pack('n')
close_data << body if body
send_frame(:close, close_data)
else
send_frame(:close, '')
end
@state = :closing
start_close_timeout
end
def supports_close_codes?; true; end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler08.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler08.rb | module EventMachine
module WebSocket
class Handler08 < Handler
include Framing07
include MessageProcessor06
include Close06
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handshake75.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handshake75.rb | module EventMachine
module WebSocket
module Handshake75
def self.handshake(headers, path, secure)
scheme = (secure ? "wss" : "ws")
location = "#{scheme}://#{headers['host']}#{path}"
upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
upgrade << "Upgrade: WebSocket\r\n"
upgrade << "Connection: Upgrade\r\n"
upgrade << "WebSocket-Origin: #{headers['origin']}\r\n"
upgrade << "WebSocket-Location: #{location}\r\n\r\n"
return upgrade
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handshake.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handshake.rb | require "http/parser"
require "uri"
module EventMachine
module WebSocket
# Resposible for creating the server handshake response
class Handshake
include EM::Deferrable
attr_reader :parser, :protocol_version
# Unfortunately drafts 75 & 76 require knowledge of whether the
# connection is being terminated as ws/wss in order to generate the
# correct handshake response
def initialize(secure)
@parser = Http::Parser.new
@secure = secure
@parser.on_headers_complete = proc { |headers|
@headers = Hash[headers.map { |k,v| [k.downcase, v] }]
}
end
def receive_data(data)
@parser << data
if defined? @headers
process(@headers, @parser.upgrade_data)
end
rescue HTTP::Parser::Error => e
fail(HandshakeError.new("Invalid HTTP header: #{e.message}"))
end
# Returns the WebSocket upgrade headers as a hash.
#
# Keys are strings, unmodified from the request.
#
def headers
@parser.headers
end
# The same as headers, except that the hash keys are downcased
#
def headers_downcased
@headers
end
# Returns the request path (excluding any query params)
#
def path
@path
end
# Returns the query params as a string foo=bar&baz=...
def query_string
@query_string
end
def query
Hash[query_string.split('&').map { |c| c.split('=', 2) }]
end
# Returns the WebSocket origin header if provided
#
def origin
@headers["origin"] || @headers["sec-websocket-origin"] || nil
end
def secure?
@secure
end
private
def process(headers, remains)
unless @parser.http_method == "GET"
raise HandshakeError, "Must be GET request"
end
# Validate request path
#
# According to http://tools.ietf.org/search/rfc2616#section-5.1.2, an
# invalid Request-URI should result in a 400 status code, but
# HandshakeError's currently result in a WebSocket abort. It's not
# clear which should take precedence, but an abort will do just fine.
begin
uri = URI.parse(@parser.request_url)
@path = uri.path
@query_string = uri.query || ""
rescue URI::InvalidURIError
raise HandshakeError, "Invalid request URI: #{@parser.request_url}"
end
# Validate Upgrade
unless @parser.upgrade?
raise HandshakeError, "Not an upgrade request"
end
upgrade = @headers['upgrade']
unless upgrade.kind_of?(String) && upgrade.downcase == 'websocket'
raise HandshakeError, "Invalid upgrade header: #{upgrade.inspect}"
end
# Determine version heuristically
version = if @headers['sec-websocket-version']
# Used from drafts 04 onwards
@headers['sec-websocket-version'].to_i
elsif @headers['sec-websocket-draft']
# Used in drafts 01 - 03
@headers['sec-websocket-draft'].to_i
elsif @headers['sec-websocket-key1']
76
else
75
end
# Additional handling of bytes after the header if required
case version
when 75
if !remains.empty?
raise HandshakeError, "Extra bytes after header"
end
when 76, 1..3
if remains.length < 8
# The whole third-key has not been received yet.
return nil
elsif remains.length > 8
raise HandshakeError, "Extra bytes after third key"
end
@headers['third-key'] = remains
end
handshake_klass = case version
when 75
Handshake75
when 76, 1..3
Handshake76
when 5, 6, 7, 8, 13
Handshake04
else
# According to spec should abort the connection
raise HandshakeError, "Protocol version #{version} not supported"
end
upgrade_response = handshake_klass.handshake(@headers, @parser.request_url, @secure)
handler_klass = Handler.klass_factory(version)
@protocol_version = version
succeed(upgrade_response, handler_klass)
rescue HandshakeError => e
fail(e)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handshake04.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handshake04.rb | require 'digest/sha1'
require 'base64'
module EventMachine
module WebSocket
module Handshake04
def self.handshake(headers, _, __)
# Required
unless key = headers['sec-websocket-key']
raise HandshakeError, "sec-websocket-key header is required"
end
string_to_sign = "#{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
signature = Base64.encode64(Digest::SHA1.digest(string_to_sign)).chomp
upgrade = ["HTTP/1.1 101 Switching Protocols"]
upgrade << "Upgrade: websocket"
upgrade << "Connection: Upgrade"
upgrade << "Sec-WebSocket-Accept: #{signature}"
# TODO: Support sec-websocket-protocol
# TODO: sec-websocket-extensions
return upgrade.join("\r\n") + "\r\n\r\n"
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler.rb | module EventMachine
module WebSocket
class Handler
def self.klass_factory(version)
case version
when 75
Handler75
when 76
Handler76
when 1..3
# We'll use handler03 - I believe they're all compatible
Handler03
when 5
Handler05
when 6
Handler06
when 7
Handler07
when 8
# drafts 9, 10, 11 and 12 should never change the version
# number as they are all the same as version 08.
Handler08
when 13
# drafts 13 to 17 all identify as version 13 as they are
# only minor changes or text changes.
Handler13
else
# According to spec should abort the connection
raise HandshakeError, "Protocol version #{version} not supported"
end
end
include Debugger
attr_reader :request, :state
def initialize(connection, debug = false)
@connection = connection
@debug = debug
@state = :connected
@close_timer = nil
initialize_framing
end
def receive_data(data)
@data << data
process_data
rescue WSProtocolError => e
fail_websocket(e)
end
def close_websocket(code, body)
# Implemented in subclass
end
# Used to avoid un-acked and unclosed remaining open indefinitely
def start_close_timeout
@close_timer = EM::Timer.new(@connection.close_timeout) {
@connection.close_connection
e = WSProtocolError.new("Close handshake un-acked after #{@connection.close_timeout}s, closing tcp connection")
@connection.trigger_on_error(e)
}
end
# This corresponds to "Fail the WebSocket Connection" in the spec.
def fail_websocket(e)
debug [:error, e]
close_websocket(e.code, e.message)
@connection.close_connection_after_writing
@connection.trigger_on_error(e)
end
def unbind
@state = :closed
@close_timer.cancel if @close_timer
@close_info = defined?(@close_info) ? @close_info : {
:code => 1006,
:was_clean => false,
}
@connection.trigger_on_close(@close_info)
end
def ping
# Overridden in subclass
false
end
def pingable?
# Also Overridden
false
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/connection.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/connection.rb | module EventMachine
module WebSocket
class Connection < EventMachine::Connection
include Debugger
attr_writer :max_frame_size
# define WebSocket callbacks
def onopen(&blk); @onopen = blk; end
def onclose(&blk); @onclose = blk; end
def onerror(&blk); @onerror = blk; end
def onmessage(&blk); @onmessage = blk; end
def onbinary(&blk); @onbinary = blk; end
def onping(&blk); @onping = blk; end
def onpong(&blk); @onpong = blk; end
def trigger_on_message(msg)
@onmessage.call(msg) if defined? @onmessage
end
def trigger_on_binary(msg)
@onbinary.call(msg) if defined? @onbinary
end
def trigger_on_open(handshake)
@onopen.call(handshake) if defined? @onopen
end
def trigger_on_close(event = {})
@onclose.call(event) if defined? @onclose
end
def trigger_on_ping(data)
@onping.call(data) if defined? @onping
end
def trigger_on_pong(data)
@onpong.call(data) if defined? @onpong
end
def trigger_on_error(reason)
return false unless defined? @onerror
@onerror.call(reason)
true
end
def initialize(options)
@options = options
@debug = options[:debug] || false
@secure = options[:secure] || false
@secure_proxy = options[:secure_proxy] || false
@tls_options = options[:tls_options] || {}
@close_timeout = options[:close_timeout]
@handler = nil
debug [:initialize]
end
# Use this method to close the websocket connection cleanly
# This sends a close frame and waits for acknowlegement before closing
# the connection
def close(code = nil, body = nil)
if code && !acceptable_close_code?(code)
raise "Application code may only use codes from 1000, 3000-4999"
end
close_websocket_private(code, body)
end
# Deprecated, to be removed in version 0.6
alias :close_websocket :close
def post_init
start_tls(@tls_options) if @secure
end
def receive_data(data)
debug [:receive_data, data]
if @handler
@handler.receive_data(data)
else
dispatch(data)
end
rescue => e
debug [:error, e]
# There is no code defined for application errors, so use 3000
# (which is reserved for frameworks)
close_websocket_private(3000, "Application error")
# These are application errors - raise unless onerror defined
trigger_on_error(e) || raise(e)
end
def unbind
debug [:unbind, :connection]
@handler.unbind if @handler
rescue => e
debug [:error, e]
# These are application errors - raise unless onerror defined
trigger_on_error(e) || raise(e)
end
def dispatch(data)
if data.match(/\A<policy-file-request\s*\/>/)
send_flash_cross_domain_file
else
@handshake ||= begin
handshake = Handshake.new(@secure || @secure_proxy)
handshake.callback { |upgrade_response, handler_klass|
debug [:accepting_ws_version, handshake.protocol_version]
debug [:upgrade_response, upgrade_response]
self.send_data(upgrade_response)
@handler = handler_klass.new(self, @debug)
@handshake = nil
trigger_on_open(handshake)
}
handshake.errback { |e|
debug [:error, e]
trigger_on_error(e)
# Handshake errors require the connection to be aborted
abort
}
handshake
end
@handshake.receive_data(data)
end
end
def send_flash_cross_domain_file
file = '<?xml version="1.0"?><cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>'
debug [:cross_domain, file]
send_data file
# handle the cross-domain request transparently
# no need to notify the user about this connection
@onclose = nil
close_connection_after_writing
end
# Cache encodings since it's moderately expensive to look them up each time
ENCODING_SUPPORTED = "string".respond_to?(:force_encoding)
UTF8 = Encoding.find("UTF-8") if ENCODING_SUPPORTED
BINARY = Encoding.find("BINARY") if ENCODING_SUPPORTED
# Send a WebSocket text frame.
#
# A WebSocketError may be raised if the connection is in an opening or a
# closing state, or if the passed in data is not valid UTF-8
#
def send_text(data)
# If we're using Ruby 1.9, be pedantic about encodings
if ENCODING_SUPPORTED
# Also accept ascii only data in other encodings for convenience
unless (data.encoding == UTF8 && data.valid_encoding?) || data.ascii_only?
raise WebSocketError, "Data sent to WebSocket must be valid UTF-8 but was #{data.encoding} (valid: #{data.valid_encoding?})"
end
# This labels the encoding as binary so that it can be combined with
# the BINARY framing
data.force_encoding(BINARY)
else
# TODO: Check that data is valid UTF-8
end
if @handler
@handler.send_text_frame(data)
else
raise WebSocketError, "Cannot send data before onopen callback"
end
# Revert data back to the original encoding (which we assume is UTF-8)
# Doing this to avoid duping the string - there may be a better way
data.force_encoding(UTF8) if ENCODING_SUPPORTED
return nil
end
alias :send :send_text
# Send a WebSocket binary frame.
#
def send_binary(data)
if @handler
@handler.send_frame(:binary, data)
else
raise WebSocketError, "Cannot send binary before onopen callback"
end
end
# Send a ping to the client. The client must respond with a pong.
#
# In the case that the client is running a WebSocket draft < 01, false
# is returned since ping & pong are not supported
#
def ping(body = '')
if @handler
@handler.pingable? ? @handler.send_frame(:ping, body) && true : false
else
raise WebSocketError, "Cannot ping before onopen callback"
end
end
# Send an unsolicited pong message, as allowed by the protocol. The
# client is not expected to respond to this message.
#
# em-websocket automatically takes care of sending pong replies to
# incoming ping messages, as the protocol demands.
#
def pong(body = '')
if @handler
@handler.pingable? ? @handler.send_frame(:pong, body) && true : false
else
raise WebSocketError, "Cannot ping before onopen callback"
end
end
# Test whether the connection is pingable (i.e. the WebSocket draft in
# use is >= 01)
def pingable?
if @handler
@handler.pingable?
else
raise WebSocketError, "Cannot test whether pingable before onopen callback"
end
end
def supports_close_codes?
if @handler
@handler.supports_close_codes?
else
raise WebSocketError, "Cannot test before onopen callback"
end
end
def state
@handler ? @handler.state : :handshake
end
# Returns the maximum frame size which this connection is configured to
# accept. This can be set globally or on a per connection basis, and
# defaults to a value of 10MB if not set.
#
# The behaviour when a too large frame is received varies by protocol,
# but in the newest protocols the connection will be closed with the
# correct close code (1009) immediately after receiving the frame header
#
def max_frame_size
defined?(@max_frame_size) ? @max_frame_size : WebSocket.max_frame_size
end
def close_timeout
@close_timeout || WebSocket.close_timeout
end
private
# As definited in draft 06 7.2.2, some failures require that the server
# abort the websocket connection rather than close cleanly
def abort
close_connection
end
def close_websocket_private(code, body)
if @handler
debug [:closing, code]
@handler.close_websocket(code, body)
else
# The handshake hasn't completed - should be safe to terminate
abort
end
end
# Allow applications to close with 1000, 1003, 1008, 1011, 3xxx or 4xxx.
#
# em-websocket uses a few other codes internally which should not be
# used by applications
#
# Browsers generally allow connections to be closed with code 1000,
# 3xxx, and 4xxx. em-websocket allows closing with a few other codes
# which seem reasonable (for discussion see
# https://github.com/igrigorik/em-websocket/issues/98)
#
# Usage from the rfc:
#
# 1000 indicates a normal closure
#
# 1003 indicates that an endpoint is terminating the connection
# because it has received a type of data it cannot accept
#
# 1008 indicates that an endpoint is terminating the connection because
# it has received a message that violates its policy
#
# 1011 indicates that a server is terminating the connection because it
# encountered an unexpected condition that prevented it from fulfilling
# the request
#
# Status codes in the range 3000-3999 are reserved for use by libraries,
# frameworks, and applications
#
# Status codes in the range 4000-4999 are reserved for private use and
# thus can't be registered
#
def acceptable_close_code?(code)
case code
when 1000, 1003, 1008, 1011, (3000..4999)
true
else
false
end
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/message_processor_06.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/message_processor_06.rb | module EventMachine
module WebSocket
module MessageProcessor06
def message(message_type, extension_data, application_data)
debug [:message_received, message_type, application_data]
case message_type
when :close
status_code = case application_data.length
when 0
# close messages MAY contain a body
nil
when 1
# Illegal close frame
raise WSProtocolError, "Close frames with a body must contain a 2 byte status code"
else
application_data.slice!(0, 2).unpack('n').first
end
debug [:close_frame_received, status_code, application_data]
@close_info = {
:code => status_code || 1005,
:reason => application_data,
:was_clean => true,
}
if @state == :closing
# We can close connection immediately since no more data may be
# sent or received on this connection
@connection.close_connection
elsif @state == :connected
# Acknowlege close & echo status back to client
# The connection is considered closed
close_data = [status_code || 1000].pack('n')
send_frame(:close, close_data)
@connection.close_connection_after_writing
end
when :ping
# Pong back the same data
send_frame(:pong, application_data)
@connection.trigger_on_ping(application_data)
when :pong
@connection.trigger_on_pong(application_data)
when :text
if application_data.respond_to?(:force_encoding)
application_data.force_encoding("UTF-8")
unless application_data.valid_encoding?
raise InvalidDataError, "Invalid UTF8 data"
end
end
@connection.trigger_on_message(application_data)
when :binary
@connection.trigger_on_binary(application_data)
end
end
# Ping & Pong supported
def pingable?
true
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/close03.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/close03.rb | module EventMachine
module WebSocket
module Close03
def close_websocket(code, body)
# TODO: Ideally send body data and check that it matches in ack
send_frame(:close, '')
@state = :closing
start_close_timeout
end
def supports_close_codes?; false; end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/message_processor_03.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/message_processor_03.rb | # encoding: BINARY
module EventMachine
module WebSocket
module MessageProcessor03
def message(message_type, extension_data, application_data)
case message_type
when :close
@close_info = {
:code => 1005,
:reason => "",
:was_clean => true,
}
if @state == :closing
# TODO: Check that message body matches sent data
# We can close connection immediately since there is no more data
# is allowed to be sent or received on this connection
@connection.close_connection
else
# Acknowlege close
# The connection is considered closed
send_frame(:close, application_data)
@connection.close_connection_after_writing
end
when :ping
# Pong back the same data
send_frame(:pong, application_data)
@connection.trigger_on_ping(application_data)
when :pong
@connection.trigger_on_pong(application_data)
when :text
if application_data.respond_to?(:force_encoding)
application_data.force_encoding("UTF-8")
end
@connection.trigger_on_message(application_data)
when :binary
@connection.trigger_on_binary(application_data)
end
end
# Ping & Pong supported
def pingable?
true
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler07.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler07.rb | module EventMachine
module WebSocket
class Handler07 < Handler
include Framing07
include MessageProcessor06
include Close06
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler13.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler13.rb | module EventMachine
module WebSocket
class Handler13 < Handler
include Framing07
include MessageProcessor06
include Close06
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/framing07.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/framing07.rb | # encoding: BINARY
module EventMachine
module WebSocket
module Framing07
def initialize_framing
@data = MaskedString.new
@application_data_buffer = '' # Used for MORE frames
@frame_type = nil
end
def process_data
error = false
while !error && @data.size >= 2
pointer = 0
fin = (@data.getbyte(pointer) & 0b10000000) == 0b10000000
# Ignoring rsv1-3 for now
opcode = @data.getbyte(pointer) & 0b00001111
pointer += 1
mask = (@data.getbyte(pointer) & 0b10000000) == 0b10000000
length = @data.getbyte(pointer) & 0b01111111
pointer += 1
# raise WebSocketError, 'Data from client must be masked' unless mask
payload_length = case length
when 127 # Length defined by 8 bytes
# Check buffer size
if @data.getbyte(pointer+8-1) == nil
debug [:buffer_incomplete, @data]
error = true
next
end
# Only using the last 4 bytes for now, till I work out how to
# unpack 8 bytes. I'm sure 4GB frames will do for now :)
l = @data.getbytes(pointer+4, 4).unpack('N').first
pointer += 8
l
when 126 # Length defined by 2 bytes
# Check buffer size
if @data.getbyte(pointer+2-1) == nil
debug [:buffer_incomplete, @data]
error = true
next
end
l = @data.getbytes(pointer, 2).unpack('n').first
pointer += 2
l
else
length
end
# Compute the expected frame length
frame_length = pointer + payload_length
frame_length += 4 if mask
if frame_length > @connection.max_frame_size
raise WSMessageTooBigError, "Frame length too long (#{frame_length} bytes)"
end
# Check buffer size
if @data.getbyte(frame_length - 1) == nil
debug [:buffer_incomplete, @data]
error = true
next
end
# Remove frame header
@data.slice!(0...pointer)
pointer = 0
# Read application data (unmasked if required)
@data.read_mask if mask
pointer += 4 if mask
application_data = @data.getbytes(pointer, payload_length)
pointer += payload_length
@data.unset_mask if mask
# Throw away data up to pointer
@data.slice!(0...pointer)
frame_type = opcode_to_type(opcode)
if frame_type == :continuation
if !@frame_type
raise WSProtocolError, 'Continuation frame not expected'
end
else # Not a continuation frame
if @frame_type && data_frame?(frame_type)
raise WSProtocolError, "Continuation frame expected"
end
end
# Validate that control frames are not fragmented
if !fin && !data_frame?(frame_type)
raise WSProtocolError, 'Control frames must not be fragmented'
end
if !fin
debug [:moreframe, frame_type, application_data]
@application_data_buffer << application_data
# The message type is passed in the first frame
@frame_type ||= frame_type
else
# Message is complete
if frame_type == :continuation
@application_data_buffer << application_data
message(@frame_type, '', @application_data_buffer)
@application_data_buffer = ''
@frame_type = nil
else
message(frame_type, '', application_data)
end
end
end # end while
end
def send_frame(frame_type, application_data)
debug [:sending_frame, frame_type, application_data]
if @state == :closing && data_frame?(frame_type)
raise WebSocketError, "Cannot send data frame since connection is closing"
end
frame = ''
opcode = type_to_opcode(frame_type)
byte1 = opcode | 0b10000000 # fin bit set, rsv1-3 are 0
frame << byte1
length = application_data.size
if length <= 125
byte2 = length # since rsv4 is 0
frame << byte2
elsif length < 65536 # write 2 byte length
frame << 126
frame << [length].pack('n')
else # write 8 byte length
frame << 127
frame << [length >> 32, length & 0xFFFFFFFF].pack("NN")
end
frame << application_data
@connection.send_data(frame)
end
def send_text_frame(data)
send_frame(:text, data)
end
private
FRAME_TYPES = {
:continuation => 0,
:text => 1,
:binary => 2,
:close => 8,
:ping => 9,
:pong => 10,
}
FRAME_TYPES_INVERSE = FRAME_TYPES.invert
# Frames are either data frames or control frames
DATA_FRAMES = [:text, :binary, :continuation]
def type_to_opcode(frame_type)
FRAME_TYPES[frame_type] || raise("Unknown frame type")
end
def opcode_to_type(opcode)
FRAME_TYPES_INVERSE[opcode] || raise(WSProtocolError, "Unknown opcode #{opcode}")
end
def data_frame?(type)
DATA_FRAMES.include?(type)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler06.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/handler06.rb | module EventMachine
module WebSocket
class Handler06 < Handler
include Framing05
include MessageProcessor06
include Close06
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/close05.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/close05.rb | module EventMachine
module WebSocket
module Close05
def close_websocket(code, body)
# TODO: Ideally send body data and check that it matches in ack
send_frame(:close, "\x53")
@state = :closing
start_close_timeout
end
def supports_close_codes?; false; end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/websocket.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/websocket.rb | module EventMachine
module WebSocket
class << self
attr_accessor :max_frame_size
attr_accessor :close_timeout
end
@max_frame_size = 10 * 1024 * 1024 # 10MB
# Connections are given 60s to close after being sent a close handshake
@close_timeout = 60
# All errors raised by em-websocket should descend from this class
class WebSocketError < RuntimeError; end
# Used for errors that occur during WebSocket handshake
class HandshakeError < WebSocketError; end
# Used for errors which should cause the connection to close.
# See RFC6455 §7.4.1 for a full description of meanings
class WSProtocolError < WebSocketError
def code; 1002; end
end
class InvalidDataError < WSProtocolError
def code; 1007; end
end
# 1009: Message too big to process
class WSMessageTooBigError < WSProtocolError
def code; 1009; end
end
# Start WebSocket server, including starting eventmachine run loop
def self.start(options, &blk)
EM.epoll
EM.run {
trap("TERM") { stop }
trap("INT") { stop }
run(options, &blk)
}
end
# Start WebSocket server inside eventmachine run loop
def self.run(options)
host, port = options.values_at(:host, :port)
EM.start_server(host, port, Connection, options) do |c|
yield c
end
end
def self.stop
puts "Terminating WebSocket Server"
EM.stop
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/close75.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/close75.rb | module EventMachine
module WebSocket
module Close75
def close_websocket(code, body)
@connection.close_connection_after_writing
end
def supports_close_codes?; false; end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/framing76.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/framing76.rb | # encoding: BINARY
module EventMachine
module WebSocket
module Framing76
def initialize_framing
@data = ''
end
def process_data
debug [:message, @data]
# This algorithm comes straight from the spec
# http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76#section-5.3
error = false
while !error
return if @data.size == 0
pointer = 0
frame_type = @data.getbyte(pointer)
pointer += 1
if (frame_type & 0x80) == 0x80
# If the high-order bit of the /frame type/ byte is set
length = 0
loop do
return false if !@data.getbyte(pointer)
b = @data.getbyte(pointer)
pointer += 1
b_v = b & 0x7F
length = length * 128 + b_v
break unless (b & 0x80) == 0x80
end
if length > @connection.max_frame_size
raise WSMessageTooBigError, "Frame length too long (#{length} bytes)"
end
if @data.getbyte(pointer+length-1) == nil
debug [:buffer_incomplete, @data]
# Incomplete data - leave @data to accumulate
error = true
else
# Straight from spec - I'm sure this isn't crazy...
# 6. Read /length/ bytes.
# 7. Discard the read bytes.
@data = @data[(pointer+length)..-1]
# If the /frame type/ is 0xFF and the /length/ was 0, then close
if length == 0
@connection.send_data("\xff\x00")
@state = :closing
@connection.close_connection_after_writing
else
error = true
end
end
else
# If the high-order bit of the /frame type/ byte is _not_ set
if @data.getbyte(0) != 0x00
# Close the connection since this buffer can never match
raise WSProtocolError, "Invalid frame received"
end
# Addition to the spec to protect against malicious requests
if @data.size > @connection.max_frame_size
raise WSMessageTooBigError, "Frame length too long (#{@data.size} bytes)"
end
msg = @data.slice!(/\A\x00[^\xff]*\xff/)
if msg
msg.gsub!(/\A\x00|\xff\z/, '')
if @state == :closing
debug [:ignored_message, msg]
else
msg.force_encoding('UTF-8') if msg.respond_to?(:force_encoding)
@connection.trigger_on_message(msg)
end
else
error = true
end
end
end
false
end
# frames need to start with 0x00-0x7f byte and end with
# an 0xFF byte. Per spec, we can also set the first
# byte to a value betweent 0x80 and 0xFF, followed by
# a leading length indicator
def send_text_frame(data)
debug [:sending_text_frame, data]
ary = ["\x00", data, "\xff"]
ary.collect{ |s| s.force_encoding('UTF-8') if s.respond_to?(:force_encoding) }
@connection.send_data(ary.join)
end
end
end
end | ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/masking04.rb | _vendor/ruby/2.6.0/gems/em-websocket-0.5.1/lib/em-websocket/masking04.rb | module EventMachine
module WebSocket
class MaskedString < String
# Read a 4 bit XOR mask - further requested bytes will be unmasked
def read_mask
if respond_to?(:encoding) && encoding.name != "ASCII-8BIT"
raise "MaskedString only operates on BINARY strings"
end
raise "Too short" if bytesize < 4 # TODO - change
@masking_key = String.new(self[0..3])
end
# Removes the mask, behaves like a normal string again
def unset_mask
@masking_key = nil
end
def getbyte(index)
if defined?(@masking_key) && @masking_key
masked_char = super
masked_char ? masked_char ^ @masking_key.getbyte(index % 4) : nil
else
super
end
end
def getbytes(start_index, count)
data = ''
data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding)
count.times do |i|
data << getbyte(start_index + i)
end
data
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-watch-2.1.2/lib/jekyll-watch.rb | _vendor/ruby/2.6.0/gems/jekyll-watch-2.1.2/lib/jekyll-watch.rb | # frozen_string_literal: true
require "jekyll-watch/version"
require_relative "jekyll/watcher"
require_relative "jekyll/commands/watch"
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-watch-2.1.2/lib/jekyll-watch/version.rb | _vendor/ruby/2.6.0/gems/jekyll-watch-2.1.2/lib/jekyll-watch/version.rb | # frozen_string_literal: true
module Jekyll
module Watch
VERSION = "2.1.2"
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-watch-2.1.2/lib/jekyll/watcher.rb | _vendor/ruby/2.6.0/gems/jekyll-watch-2.1.2/lib/jekyll/watcher.rb | # frozen_string_literal: true
require "listen"
module Jekyll
module Watcher
extend self
# Public: Continuously watch for file changes and rebuild the site
# whenever a change is detected.
#
# If the optional site argument is populated, that site instance will be
# reused and the options Hash ignored. Otherwise, a new site instance will
# be instantiated from the options Hash and used.
#
# options - A Hash containing the site configuration
# site - The current site instance (populated starting with Jekyll 3.2)
# (optional, default: nil)
#
# Returns nothing.
def watch(options, site = nil)
ENV["LISTEN_GEM_DEBUGGING"] ||= "1" if options["verbose"]
site ||= Jekyll::Site.new(options)
listener = build_listener(site, options)
listener.start
Jekyll.logger.info "Auto-regeneration:", "enabled for '#{options["source"]}'"
unless options["serving"]
trap("INT") do
listener.stop
Jekyll.logger.info "", "Halting auto-regeneration."
exit 0
end
sleep_forever
end
rescue ThreadError
# You pressed Ctrl-C, oh my!
end
private
def build_listener(site, options)
Listen.to(
options["source"],
:ignore => listen_ignore_paths(options),
:force_polling => options["force_polling"],
&listen_handler(site)
)
end
def listen_handler(site)
proc do |modified, added, removed|
t = Time.now
c = modified + added + removed
n = c.length
Jekyll.logger.info "Regenerating:",
"#{n} file(s) changed at #{t.strftime("%Y-%m-%d %H:%M:%S")}"
c.each { |path| Jekyll.logger.info "", path["#{site.source}/".length..-1] }
process(site, t)
end
end
def custom_excludes(options)
Array(options["exclude"]).map { |e| Jekyll.sanitized_path(options["source"], e) }
end
def config_files(options)
%w(yml yaml toml).map do |ext|
Jekyll.sanitized_path(options["source"], "_config.#{ext}")
end
end
def to_exclude(options)
[
config_files(options),
options["destination"],
custom_excludes(options),
].flatten
end
# Paths to ignore for the watch option
#
# options - A Hash of options passed to the command
#
# Returns a list of relative paths from source that should be ignored
def listen_ignore_paths(options)
source = Pathname.new(options["source"]).expand_path
paths = to_exclude(options)
paths.map do |p|
absolute_path = Pathname.new(p).expand_path
next unless absolute_path.exist?
begin
relative_path = absolute_path.relative_path_from(source).to_s
unless relative_path.start_with?("../")
path_to_ignore = Regexp.new(Regexp.escape(relative_path))
Jekyll.logger.debug "Watcher:", "Ignoring #{path_to_ignore}"
path_to_ignore
end
rescue ArgumentError
# Could not find a relative path
end
end.compact + [%r!\.jekyll\-metadata!]
end
def sleep_forever
loop { sleep 1000 }
end
def process(site, time)
begin
site.process
Jekyll.logger.info "", "...done in #{Time.now - time} seconds."
rescue => e
Jekyll.logger.warn "Error:", e.message
Jekyll.logger.warn "Error:", "Run jekyll build --trace for more information."
end
Jekyll.logger.info ""
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/jekyll-watch-2.1.2/lib/jekyll/commands/watch.rb | _vendor/ruby/2.6.0/gems/jekyll-watch-2.1.2/lib/jekyll/commands/watch.rb | # frozen_string_literal: true
module Jekyll
module Commands
module Watch
extend self
def init_with_program(prog); end
# Build your jekyll site
# Continuously watch if `watch` is set to true in the config.
def process(options)
Jekyll.logger.log_level = :error if options["quiet"]
Jekyll::Watcher.watch(options) if options["watch"]
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/libyaml_checker_spec.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/libyaml_checker_spec.rb | require "spec_helper"
describe SafeYAML::LibyamlChecker do
describe "check_libyaml_version" do
REAL_YAML_ENGINE = SafeYAML::YAML_ENGINE
REAL_LIBYAML_VERSION = SafeYAML::LibyamlChecker::LIBYAML_VERSION
let(:libyaml_patched) { false }
before :each do
allow(SafeYAML::LibyamlChecker).to receive(:libyaml_patched?).and_return(libyaml_patched)
end
after :each do
silence_warnings do
SafeYAML::YAML_ENGINE = REAL_YAML_ENGINE
SafeYAML::LibyamlChecker::LIBYAML_VERSION = REAL_LIBYAML_VERSION
end
end
def test_libyaml_version_ok(expected_result, yaml_engine, libyaml_version=nil)
silence_warnings do
SafeYAML.const_set("YAML_ENGINE", yaml_engine)
SafeYAML::LibyamlChecker.const_set("LIBYAML_VERSION", libyaml_version)
expect(SafeYAML::LibyamlChecker.libyaml_version_ok?).to eq(expected_result)
end
end
unless defined?(JRUBY_VERSION)
it "issues no warnings when 'Syck' is the YAML engine" do
test_libyaml_version_ok(true, "syck")
end
it "issues a warning if Psych::LIBYAML_VERSION is not defined" do
test_libyaml_version_ok(false, "psych")
end
it "issues a warning if Psych::LIBYAML_VERSION is < 0.1.6" do
test_libyaml_version_ok(false, "psych", "0.1.5")
end
it "issues no warning if Psych::LIBYAML_VERSION is == 0.1.6" do
test_libyaml_version_ok(true, "psych", "0.1.6")
end
it "issues no warning if Psych::LIBYAML_VERSION is > 0.1.6" do
test_libyaml_version_ok(true, "psych", "1.0.0")
end
it "does a proper version comparison (not just a string comparison)" do
test_libyaml_version_ok(true, "psych", "0.1.10")
end
context "when the system has a known patched libyaml version" do
let(:libyaml_patched) { true }
it "issues no warning, even when Psych::LIBYAML_VERSION < 0.1.6" do
test_libyaml_version_ok(true, "psych", "0.1.4")
end
end
end
if defined?(JRUBY_VERSION)
it "issues no warning, as JRuby doesn't use libyaml" do
test_libyaml_version_ok(true, "psych", "0.1.4")
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/syck_resolver_spec.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/syck_resolver_spec.rb | require "spec_helper"
if SafeYAML::YAML_ENGINE == "syck"
require "safe_yaml/syck_resolver"
describe SafeYAML::SyckResolver do
include ResolverSpecs
let(:resolver) { SafeYAML::SyckResolver.new }
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/resolver_specs.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/resolver_specs.rb | module ResolverSpecs
def self.included(base)
base.module_eval do
let(:resolver) { nil }
let(:result) { @result }
before :each do
# See the comment in the first before :each block in safe_yaml_spec.rb.
require "safe_yaml"
end
def parse(yaml)
tree = YAML.parse(yaml.unindent)
@result = resolver.resolve_node(tree)
end
# Isn't this how I should've been doing it all along?
def parse_and_test(yaml)
safe_result = parse(yaml)
exception_thrown = nil
unsafe_result = begin
YAML.unsafe_load(yaml)
rescue Exception => e
exception_thrown = e
end
if exception_thrown
# If the underlying YAML parser (e.g. Psych) threw an exception, I'm
# honestly not sure what the right thing to do is. For now I'll just
# print a warning. Should SafeYAML fail when Psych fails?
Kernel.warn "\n"
Kernel.warn "Discrepancy between SafeYAML and #{SafeYAML::YAML_ENGINE} on input:\n"
Kernel.warn "#{yaml.unindent}\n"
Kernel.warn "SafeYAML result:"
Kernel.warn "#{safe_result.inspect}\n"
Kernel.warn "#{SafeYAML::YAML_ENGINE} result:"
Kernel.warn "#{exception_thrown.inspect}\n"
else
expect(safe_result).to eq(unsafe_result)
end
end
context "by default" do
it "translates maps to hashes" do
parse <<-YAML
potayto: potahto
tomayto: tomahto
YAML
expect(result).to eq({
"potayto" => "potahto",
"tomayto" => "tomahto"
})
end
it "translates sequences to arrays" do
parse <<-YAML
- foo
- bar
- baz
YAML
expect(result).to eq(["foo", "bar", "baz"])
end
it "translates most values to strings" do
parse "string: value"
expect(result).to eq({ "string" => "value" })
end
it "does not deserialize symbols" do
parse ":symbol: value"
expect(result).to eq({ ":symbol" => "value" })
end
it "translates valid integral numbers to integers" do
parse "integer: 1"
expect(result).to eq({ "integer" => 1 })
end
it "translates valid decimal numbers to floats" do
parse "float: 3.14"
expect(result).to eq({ "float" => 3.14 })
end
it "translates valid dates" do
parse "date: 2013-01-24"
expect(result).to eq({ "date" => Date.parse("2013-01-24") })
end
it "translates valid true/false values to booleans" do
parse <<-YAML
- yes
- true
- no
- false
YAML
expect(result).to eq([true, true, false, false])
end
it "translates valid nulls to nil" do
parse <<-YAML
-
- ~
- null
YAML
expect(result).to eq([nil] * 3)
end
it "matches the behavior of the underlying YAML engine w/ respect to capitalization of boolean values" do
parse_and_test <<-YAML
- true
- True
- TRUE
- tRue
- TRue
- False
- FALSE
- fAlse
- FALse
YAML
# using Syck: [true, true, true, "tRue", "TRue", false, false, "fAlse", "FALse"]
# using Psych: all booleans
end
it "matches the behavior of the underlying YAML engine w/ respect to capitalization of nil values" do
parse_and_test <<-YAML
- Null
- NULL
- nUll
- NUll
YAML
# using Syck: [nil, nil, "nUll", "NUll"]
# using Psych: all nils
end
it "translates quoted empty strings to strings (not nil)" do
parse "foo: ''"
expect(result).to eq({ "foo" => "" })
end
it "correctly reverse-translates strings encoded via #to_yaml" do
parse "5.10".to_yaml
expect(result).to eq("5.10")
end
it "does not specially parse any double-quoted strings" do
parse <<-YAML
- "1"
- "3.14"
- "true"
- "false"
- "2013-02-03"
- "2013-02-03 16:27:00 -0600"
YAML
expect(result).to eq(["1", "3.14", "true", "false", "2013-02-03", "2013-02-03 16:27:00 -0600"])
end
it "does not specially parse any single-quoted strings" do
parse <<-YAML
- '1'
- '3.14'
- 'true'
- 'false'
- '2013-02-03'
- '2013-02-03 16:27:00 -0600'
YAML
expect(result).to eq(["1", "3.14", "true", "false", "2013-02-03", "2013-02-03 16:27:00 -0600"])
end
it "deals just fine with nested maps" do
parse <<-YAML
foo:
bar:
marco: polo
YAML
expect(result).to eq({ "foo" => { "bar" => { "marco" => "polo" } } })
end
it "deals just fine with nested sequences" do
parse <<-YAML
- foo
-
- bar1
- bar2
-
- baz1
- baz2
YAML
expect(result).to eq(["foo", ["bar1", "bar2", ["baz1", "baz2"]]])
end
it "applies the same transformations to keys as to values" do
parse <<-YAML
foo: string
:bar: symbol
1: integer
3.14: float
2013-01-24: date
YAML
expect(result).to eq({
"foo" => "string",
":bar" => "symbol",
1 => "integer",
3.14 => "float",
Date.parse("2013-01-24") => "date",
})
end
it "applies the same transformations to elements in sequences as to all values" do
parse <<-YAML
- foo
- :bar
- 1
- 3.14
- 2013-01-24
YAML
expect(result).to eq(["foo", ":bar", 1, 3.14, Date.parse("2013-01-24")])
end
end
context "for Ruby version #{RUBY_VERSION}" do
it "translates valid time values" do
parse "time: 2013-01-29 05:58:00 -0800"
expect(result).to eq({ "time" => Time.utc(2013, 1, 29, 13, 58, 0) })
end
it "applies the same transformation to elements in sequences" do
parse "- 2013-01-29 05:58:00 -0800"
expect(result).to eq([Time.utc(2013, 1, 29, 13, 58, 0)])
end
it "applies the same transformation to keys" do
parse "2013-01-29 05:58:00 -0800: time"
expect(result).to eq({ Time.utc(2013, 1, 29, 13, 58, 0) => "time" })
end
end
context "with symbol deserialization enabled" do
before :each do
SafeYAML::OPTIONS[:deserialize_symbols] = true
end
after :each do
SafeYAML.restore_defaults!
end
it "translates values starting with ':' to symbols" do
parse "symbol: :value"
expect(result).to eq({ "symbol" => :value })
end
it "applies the same transformation to keys" do
parse ":bar: symbol"
expect(result).to eq({ :bar => "symbol" })
end
it "applies the same transformation to elements in sequences" do
parse "- :bar"
expect(result).to eq([:bar])
end
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/psych_resolver_spec.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/psych_resolver_spec.rb | require "spec_helper"
if SafeYAML::YAML_ENGINE == "psych"
require "safe_yaml/psych_resolver"
describe SafeYAML::PsychResolver do
include ResolverSpecs
let(:resolver) { SafeYAML::PsychResolver.new }
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/yaml_spec.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/yaml_spec.rb | # See https://github.com/dtao/safe_yaml/issues/47
require "spec_helper"
describe YAML do
context "when you've only required safe_yaml/load", :libraries => true do
it "YAML.load doesn't get monkey patched" do
expect(YAML.method(:load)).to eq(ORIGINAL_YAML_LOAD)
end
it "YAML.load_file doesn't get monkey patched" do
expect(YAML.method(:load_file)).to eq(ORIGINAL_YAML_LOAD_FILE)
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/spec_helper.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/spec_helper.rb | HERE = File.dirname(__FILE__) unless defined?(HERE)
ROOT = File.join(HERE, "..") unless defined?(ROOT)
$LOAD_PATH << File.join(ROOT, "lib")
$LOAD_PATH << File.join(HERE, "support")
require "yaml"
if ENV["YAMLER"] && defined?(YAML::ENGINE)
YAML::ENGINE.yamler = ENV["YAMLER"]
end
ruby_version = defined?(JRUBY_VERSION) ? "JRuby #{JRUBY_VERSION} in #{RUBY_VERSION} mode" : "Ruby #{RUBY_VERSION}"
yaml_engine = defined?(YAML::ENGINE) ? YAML::ENGINE.yamler : "syck"
libyaml_version = yaml_engine == "psych" && Psych.const_defined?("LIBYAML_VERSION", false) ? Psych::LIBYAML_VERSION : "N/A"
env_info = [
ruby_version,
"YAML: #{yaml_engine} (#{YAML::VERSION}) (libyaml: #{libyaml_version})",
"Monkeypatch: #{ENV['MONKEYPATCH_YAML']}"
]
puts env_info.join(", ")
# Caching references to these methods before loading safe_yaml in order to test
# that they aren't touched unless you actually require safe_yaml (see yaml_spec.rb).
ORIGINAL_YAML_LOAD = YAML.method(:load)
ORIGINAL_YAML_LOAD_FILE = YAML.method(:load_file)
require "safe_yaml/load"
require "ostruct"
require "hashie"
require "heredoc_unindent"
# Stolen from Rails:
# https://github.com/rails/rails/blob/3-2-stable/activesupport/lib/active_support/core_ext/kernel/reporting.rb#L10-25
def silence_warnings
$VERBOSE = nil; yield
ensure
$VERBOSE = true
end
require File.join(HERE, "resolver_specs")
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/support/exploitable_back_door.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/support/exploitable_back_door.rb | class ExploitableBackDoor
def exploited?
@exploited_through_setter || @exploited_through_init_with || @exploited_through_ivars
end
def exploited_through_setter?
@exploited_through_setter
end
def exploited_through_init_with?
@exploited_through_init_with
end
def exploited_through_ivars?
self.instance_variables.any?
end
def init_with(command)
# Note: this is how bad this COULD be.
# system("#{command}")
@exploited_through_init_with = true
end
def []=(command, arguments)
# Note: this is how bad this COULD be.
# system("#{command} #{arguments}")
@exploited_through_setter = true
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/transform/to_integer_spec.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/transform/to_integer_spec.rb | require "spec_helper"
describe SafeYAML::Transform::ToInteger do
it "returns true when the value matches a valid Integer" do
expect(subject.transform?("10")).to eq([true, 10])
end
it "returns false when the value does not match a valid Integer" do
expect(subject.transform?("foobar")).to be_falsey
end
it "returns false when the value spans multiple lines" do
expect(subject.transform?("10\nNOT AN INTEGER")).to be_falsey
end
it "allows commas in the number" do
expect(subject.transform?("1,000")).to eq([true, 1000])
end
it "correctly parses numbers in octal format" do
expect(subject.transform?("010")).to eq([true, 8])
end
it "correctly parses numbers in hexadecimal format" do
expect(subject.transform?("0x1FF")).to eq([true, 511])
end
it "defaults to a string for a number that resembles octal format but is not" do
expect(subject.transform?("09")).to be_falsey
end
it "correctly parses 0 in decimal" do
expect(subject.transform?("0")).to eq([true, 0])
end
it "defaults to a string for a number that resembles hexadecimal format but is not" do
expect(subject.transform?("0x1G")).to be_falsey
end
it "correctly parses all formats in the YAML spec" do
# canonical
expect(subject.transform?("685230")).to eq([true, 685230])
# decimal
expect(subject.transform?("+685_230")).to eq([true, 685230])
# octal
expect(subject.transform?("02472256")).to eq([true, 685230])
# hexadecimal:
expect(subject.transform?("0x_0A_74_AE")).to eq([true, 685230])
# binary
expect(subject.transform?("0b1010_0111_0100_1010_1110")).to eq([true, 685230])
# sexagesimal
expect(subject.transform?("190:20:30")).to eq([true, 685230])
end
# see https://github.com/dtao/safe_yaml/pull/51
it "strips out underscores before parsing decimal values" do
expect(subject.transform?("_850_")).to eq([true, 850])
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/transform/base64_spec.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/transform/base64_spec.rb | require "spec_helper"
describe SafeYAML::Transform do
it "should return the same encoding when decoding Base64" do
value = "c3VyZS4="
decoded = SafeYAML::Transform.to_proper_type(value, false, "!binary")
expect(decoded).to eq("sure.")
expect(decoded.encoding).to eq(value.encoding) if decoded.respond_to?(:encoding)
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/transform/to_date_spec.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/transform/to_date_spec.rb | require "spec_helper"
describe SafeYAML::Transform::ToDate do
it "returns true when the value matches a valid Date" do
expect(subject.transform?("2013-01-01")).to eq([true, Date.parse("2013-01-01")])
end
it "returns false when the value does not match a valid Date" do
expect(subject.transform?("foobar")).to be_falsey
end
it "returns false when the value does not end with a Date" do
expect(subject.transform?("2013-01-01\nNOT A DATE")).to be_falsey
end
it "returns false when the value does not begin with a Date" do
expect(subject.transform?("NOT A DATE\n2013-01-01")).to be_falsey
end
it "correctly parses the remaining formats of the YAML spec" do
equivalent_values = [
"2001-12-15T02:59:43.1Z", # canonical
"2001-12-14t21:59:43.10-05:00", # iso8601
"2001-12-14 21:59:43.10 -5", # space separated
"2001-12-15 2:59:43.10" # no time zone (Z)
]
equivalent_values.each do |value|
success, result = subject.transform?(value)
expect(success).to be_truthy
expect(result).to eq(Time.utc(2001, 12, 15, 2, 59, 43, 100000))
end
end
it "converts times to the local timezone" do
success, result = subject.transform?("2012-12-01 10:33:45 +11:00")
expect(success).to be_truthy
expect(result).to eq(Time.utc(2012, 11, 30, 23, 33, 45))
expect(result.gmt_offset).to eq(Time.local(2012, 11, 30).gmt_offset)
end
it "returns strings for invalid dates" do
expect(subject.transform?("0000-00-00")).to eq([true, "0000-00-00"])
expect(subject.transform?("2013-13-01")).to eq([true, "2013-13-01"])
expect(subject.transform?("2014-01-32")).to eq([true, "2014-01-32"])
end
it "returns strings for invalid date/times" do
expect(subject.transform?("0000-00-00 00:00:00 -0000")).to eq([true, "0000-00-00 00:00:00 -0000"])
expect(subject.transform?("2013-13-01 21:59:43 -05:00")).to eq([true, "2013-13-01 21:59:43 -05:00"])
expect(subject.transform?("2013-01-32 21:59:43 -05:00")).to eq([true, "2013-01-32 21:59:43 -05:00"])
expect(subject.transform?("2013-01-30 25:59:43 -05:00")).to eq([true, "2013-01-30 25:59:43 -05:00"])
expect(subject.transform?("2013-01-30 21:69:43 -05:00")).to eq([true, "2013-01-30 21:69:43 -05:00"])
# Interesting. It seems that in some older Ruby versions, the below actually parses successfully
# w/ DateTime.parse; but it fails w/ YAML.load. Whom to follow???
# subject.transform?("2013-01-30 21:59:63 -05:00").should == [true, "2013-01-30 21:59:63 -05:00"]
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/transform/to_float_spec.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/transform/to_float_spec.rb | require "spec_helper"
describe SafeYAML::Transform::ToFloat do
it "returns true when the value matches a valid Float" do
expect(subject.transform?("20.00")).to eq([true, 20.0])
end
it "returns false when the value does not match a valid Float" do
expect(subject.transform?("foobar")).to be_falsey
end
it "returns false when the value spans multiple lines" do
expect(subject.transform?("20.00\nNOT A FLOAT")).to be_falsey
end
it "correctly parses all formats in the YAML spec" do
# canonical
expect(subject.transform?("6.8523015e+5")).to eq([true, 685230.15])
# exponentioal
expect(subject.transform?("685.230_15e+03")).to eq([true, 685230.15])
# fixed
expect(subject.transform?("685_230.15")).to eq([true, 685230.15])
# sexagesimal
expect(subject.transform?("190:20:30.15")).to eq([true, 685230.15])
# infinity
expect(subject.transform?("-.inf")).to eq([true, (-1.0 / 0.0)])
# not a number
# NOTE: can't use == here since NaN != NaN
success, result = subject.transform?(".NaN")
expect(success).to be_truthy; expect(result).to be_nan
end
# issue 29
it "returns false for the string '.'" do
expect(subject.transform?(".")).to be_falsey
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/transform/to_symbol_spec.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/spec/transform/to_symbol_spec.rb | require "spec_helper"
describe SafeYAML::Transform::ToSymbol do
def with_symbol_deserialization_value(value)
symbol_deserialization_flag = SafeYAML::OPTIONS[:deserialize_symbols]
SafeYAML::OPTIONS[:deserialize_symbols] = value
yield
ensure
SafeYAML::OPTIONS[:deserialize_symbols] = symbol_deserialization_flag
end
def with_symbol_deserialization(&block)
with_symbol_deserialization_value(true, &block)
end
def without_symbol_deserialization(&block)
with_symbol_deserialization_value(false, &block)
end
it "returns true when the value matches a valid Symbol" do
with_symbol_deserialization { expect(subject.transform?(":foo")[0]).to be_truthy }
end
it "returns true when the value matches a valid String+Symbol" do
with_symbol_deserialization { expect(subject.transform?(':"foo"')[0]).to be_truthy }
end
it "returns true when the value matches a valid String+Symbol with 's" do
with_symbol_deserialization { expect(subject.transform?(":'foo'")[0]).to be_truthy }
end
it "returns true when the value has special characters and is wrapped in a String" do
with_symbol_deserialization { expect(subject.transform?(':"foo.bar"')[0]).to be_truthy }
end
it "returns false when symbol deserialization is disabled" do
without_symbol_deserialization { expect(subject.transform?(":foo")).to be_falsey }
end
it "returns false when the value does not match a valid Symbol" do
with_symbol_deserialization { expect(subject.transform?("foo")).to be_falsey }
end
it "returns false when the symbol does not begin the line" do
with_symbol_deserialization do
expect(subject.transform?("NOT A SYMBOL\n:foo")).to be_falsey
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml.rb | require "safe_yaml/load"
module YAML
def self.load_with_options(yaml, *original_arguments)
filename, options = filename_and_options_from_arguments(original_arguments)
safe_mode = safe_mode_from_options("load", options)
arguments = [yaml]
if safe_mode == :safe
arguments << filename if SafeYAML::YAML_ENGINE == "psych"
arguments << options_for_safe_load(options)
safe_load(*arguments)
else
arguments << filename if SafeYAML::MULTI_ARGUMENT_YAML_LOAD
unsafe_load(*arguments)
end
end
def self.load_file_with_options(file, options={})
safe_mode = safe_mode_from_options("load_file", options)
if safe_mode == :safe
safe_load_file(file, options_for_safe_load(options))
else
unsafe_load_file(file)
end
end
def self.safe_load(*args)
SafeYAML.load(*args)
end
def self.safe_load_file(*args)
SafeYAML.load_file(*args)
end
if SafeYAML::MULTI_ARGUMENT_YAML_LOAD
def self.unsafe_load_file(filename)
# https://github.com/tenderlove/psych/blob/v1.3.2/lib/psych.rb#L296-298
File.open(filename, 'r:bom|utf-8') { |f| self.unsafe_load(f, filename) }
end
else
def self.unsafe_load_file(filename)
# https://github.com/tenderlove/psych/blob/v1.2.2/lib/psych.rb#L231-233
self.unsafe_load File.open(filename)
end
end
class << self
alias_method :unsafe_load, :load
alias_method :load, :load_with_options
alias_method :load_file, :load_file_with_options
private
def filename_and_options_from_arguments(arguments)
if arguments.count == 1
if arguments.first.is_a?(String)
return arguments.first, {}
else
return nil, arguments.first || {}
end
else
return arguments.first, arguments.last || {}
end
end
def safe_mode_from_options(method, options={})
if options[:safe].nil?
safe_mode = SafeYAML::OPTIONS[:default_mode] || :safe
if SafeYAML::OPTIONS[:default_mode].nil? && !SafeYAML::OPTIONS[:suppress_warnings]
Kernel.warn <<-EOWARNING.gsub(/^\s+/, '')
Called '#{method}' without the :safe option -- defaulting to #{safe_mode} mode.
You can avoid this warning in the future by setting the SafeYAML::OPTIONS[:default_mode] option (to :safe or :unsafe).
EOWARNING
SafeYAML::OPTIONS[:suppress_warnings] = true
end
return safe_mode
end
options[:safe] ? :safe : :unsafe
end
def options_for_safe_load(base_options)
options = base_options.dup
options.delete(:safe)
options
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/safe_to_ruby_visitor.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/safe_to_ruby_visitor.rb | module SafeYAML
class SafeToRubyVisitor < Psych::Visitors::ToRuby
INITIALIZE_ARITY = superclass.instance_method(:initialize).arity
def initialize(resolver)
case INITIALIZE_ARITY
when 2
# https://github.com/tenderlove/psych/blob/v2.0.0/lib/psych/visitors/to_ruby.rb#L14-L28
loader = Psych::ClassLoader.new
scanner = Psych::ScalarScanner.new(loader)
super(scanner, loader)
else
super()
end
@resolver = resolver
end
def accept(node)
if node.tag
SafeYAML.tag_safety_check!(node.tag, @resolver.options)
return super
end
@resolver.resolve_node(node)
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/version.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/version.rb | module SafeYAML
VERSION = "1.0.4"
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/psych_handler.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/psych_handler.rb | require "psych"
require "base64"
module SafeYAML
class PsychHandler < Psych::Handler
def initialize(options, &block)
@options = SafeYAML::OPTIONS.merge(options || {})
@block = block
@initializers = @options[:custom_initializers] || {}
@anchors = {}
@stack = []
@current_key = nil
@result = nil
@begun = false
end
def result
@begun ? @result : false
end
def add_to_current_structure(value, anchor=nil, quoted=nil, tag=nil)
value = Transform.to_proper_type(value, quoted, tag, @options)
@anchors[anchor] = value if anchor
if !@begun
@begun = true
@result = value
@current_structure = @result
return
end
if @current_structure.respond_to?(:<<)
@current_structure << value
elsif @current_structure.respond_to?(:[]=)
if @current_key.nil?
@current_key = value
else
if @current_key == "<<"
@current_structure.merge!(value)
else
@current_structure[@current_key] = value
end
@current_key = nil
end
else
raise "Don't know how to add to a #{@current_structure.class}!"
end
end
def end_current_structure
@stack.pop
@current_structure = @stack.last
end
def streaming?
true
end
# event handlers
def alias(anchor)
add_to_current_structure(@anchors[anchor])
end
def scalar(value, anchor, tag, plain, quoted, style)
add_to_current_structure(value, anchor, quoted, tag)
end
def end_document(implicit)
@block.call(@result)
end
def start_mapping(anchor, tag, implicit, style)
map = @initializers.include?(tag) ? @initializers[tag].call : {}
self.add_to_current_structure(map, anchor)
@current_structure = map
@stack.push(map)
end
def end_mapping
self.end_current_structure()
end
def start_sequence(anchor, tag, implicit, style)
seq = @initializers.include?(tag) ? @initializers[tag].call : []
self.add_to_current_structure(seq, anchor)
@current_structure = seq
@stack.push(seq)
end
def end_sequence
self.end_current_structure()
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/syck_hack.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/syck_hack.rb | # Hack to JRuby 1.8's YAML Parser Yecht
#
# This file is always loaded AFTER either syck or psych are already
# loaded. It then looks at what constants are available and creates
# a consistent view on all rubys.
#
# Taken from rubygems and modified.
# See https://github.com/rubygems/rubygems/blob/master/lib/rubygems/syck_hack.rb
module YAML
# In newer 1.9.2, there is a Syck toplevel constant instead of it
# being underneith YAML. If so, reference it back under YAML as
# well.
if defined? ::Syck
# for tests that change YAML::ENGINE
# 1.8 does not support the second argument to const_defined?
remove_const :Syck rescue nil
Syck = ::Syck
# JRuby's "Syck" is called "Yecht"
elsif defined? YAML::Yecht
Syck = YAML::Yecht
end
end
# Sometime in the 1.9 dev cycle, the Syck constant was moved from under YAML
# to be a toplevel constant. So gemspecs created under these versions of Syck
# will have references to Syck::DefaultKey.
#
# So we need to be sure that we reference Syck at the toplevel too so that
# we can always load these kind of gemspecs.
#
if !defined?(Syck)
Syck = YAML::Syck
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/load.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/load.rb | require "set"
require "yaml"
# This needs to be defined up front in case any internal classes need to base
# their behavior off of this.
module SafeYAML
YAML_ENGINE = defined?(YAML::ENGINE) ? YAML::ENGINE.yamler : (defined?(Psych) && YAML == Psych ? "psych" : "syck")
end
require "safe_yaml/libyaml_checker"
require "safe_yaml/deep"
require "safe_yaml/parse/hexadecimal"
require "safe_yaml/parse/sexagesimal"
require "safe_yaml/parse/date"
require "safe_yaml/transform/transformation_map"
require "safe_yaml/transform/to_boolean"
require "safe_yaml/transform/to_date"
require "safe_yaml/transform/to_float"
require "safe_yaml/transform/to_integer"
require "safe_yaml/transform/to_nil"
require "safe_yaml/transform/to_symbol"
require "safe_yaml/transform"
require "safe_yaml/resolver"
require "safe_yaml/syck_hack" if SafeYAML::YAML_ENGINE == "syck" && defined?(JRUBY_VERSION)
module SafeYAML
MULTI_ARGUMENT_YAML_LOAD = YAML.method(:load).arity != 1
DEFAULT_OPTIONS = Deep.freeze({
:default_mode => nil,
:suppress_warnings => false,
:deserialize_symbols => false,
:whitelisted_tags => [],
:custom_initializers => {},
:raise_on_unknown_tag => false
})
OPTIONS = Deep.copy(DEFAULT_OPTIONS)
PREDEFINED_TAGS = {}
if YAML_ENGINE == "syck"
YAML.tagged_classes.each do |tag, klass|
PREDEFINED_TAGS[klass] = tag
end
else
# Special tags appear to be hard-coded in Psych:
# https://github.com/tenderlove/psych/blob/v1.3.4/lib/psych/visitors/to_ruby.rb
# Fortunately, there aren't many that SafeYAML doesn't already support.
PREDEFINED_TAGS.merge!({
Exception => "!ruby/exception",
Range => "!ruby/range",
Regexp => "!ruby/regexp",
})
end
Deep.freeze(PREDEFINED_TAGS)
module_function
def restore_defaults!
OPTIONS.clear.merge!(Deep.copy(DEFAULT_OPTIONS))
end
def tag_safety_check!(tag, options)
return if tag.nil? || tag == "!"
if options[:raise_on_unknown_tag] && !options[:whitelisted_tags].include?(tag) && !tag_is_explicitly_trusted?(tag)
raise "Unknown YAML tag '#{tag}'"
end
end
def whitelist!(*classes)
classes.each do |klass|
whitelist_class!(klass)
end
end
def whitelist_class!(klass)
raise "#{klass} not a Class" unless klass.is_a?(::Class)
klass_name = klass.name
raise "#{klass} cannot be anonymous" if klass_name.nil? || klass_name.empty?
# Whitelist any built-in YAML tags supplied by Syck or Psych.
predefined_tag = PREDEFINED_TAGS[klass]
if predefined_tag
OPTIONS[:whitelisted_tags] << predefined_tag
return
end
# Exception is exceptional (har har).
tag_class = klass < Exception ? "exception" : "object"
tag_prefix = case YAML_ENGINE
when "psych" then "!ruby/#{tag_class}"
when "syck" then "tag:ruby.yaml.org,2002:#{tag_class}"
else raise "unknown YAML_ENGINE #{YAML_ENGINE}"
end
OPTIONS[:whitelisted_tags] << "#{tag_prefix}:#{klass_name}"
end
if YAML_ENGINE == "psych"
def tag_is_explicitly_trusted?(tag)
false
end
else
TRUSTED_TAGS = Set.new([
"tag:yaml.org,2002:binary",
"tag:yaml.org,2002:bool#no",
"tag:yaml.org,2002:bool#yes",
"tag:yaml.org,2002:float",
"tag:yaml.org,2002:float#fix",
"tag:yaml.org,2002:int",
"tag:yaml.org,2002:map",
"tag:yaml.org,2002:null",
"tag:yaml.org,2002:seq",
"tag:yaml.org,2002:str",
"tag:yaml.org,2002:timestamp",
"tag:yaml.org,2002:timestamp#ymd"
]).freeze
def tag_is_explicitly_trusted?(tag)
TRUSTED_TAGS.include?(tag)
end
end
if SafeYAML::YAML_ENGINE == "psych"
require "safe_yaml/psych_handler"
require "safe_yaml/psych_resolver"
require "safe_yaml/safe_to_ruby_visitor"
def self.load(yaml, filename=nil, options={})
# If the user hasn't whitelisted any tags, we can go with this implementation which is
# significantly faster.
if (options && options[:whitelisted_tags] || SafeYAML::OPTIONS[:whitelisted_tags]).empty?
safe_handler = SafeYAML::PsychHandler.new(options) do |result|
return result
end
arguments_for_parse = [yaml]
arguments_for_parse << filename if SafeYAML::MULTI_ARGUMENT_YAML_LOAD
Psych::Parser.new(safe_handler).parse(*arguments_for_parse)
return safe_handler.result
else
safe_resolver = SafeYAML::PsychResolver.new(options)
tree = SafeYAML::MULTI_ARGUMENT_YAML_LOAD ?
Psych.parse(yaml, filename) :
Psych.parse(yaml)
return safe_resolver.resolve_node(tree)
end
end
def self.load_file(filename, options={})
if SafeYAML::MULTI_ARGUMENT_YAML_LOAD
File.open(filename, 'r:bom|utf-8') { |f| self.load(f, filename, options) }
else
# Ruby pukes on 1.9.2 if we try to open an empty file w/ 'r:bom|utf-8';
# so we'll not specify those flags here. This mirrors the behavior for
# unsafe_load_file so it's probably preferable anyway.
self.load File.open(filename), nil, options
end
end
else
require "safe_yaml/syck_resolver"
require "safe_yaml/syck_node_monkeypatch"
def self.load(yaml, options={})
resolver = SafeYAML::SyckResolver.new(SafeYAML::OPTIONS.merge(options || {}))
tree = YAML.parse(yaml)
return resolver.resolve_node(tree)
end
def self.load_file(filename, options={})
File.open(filename) { |f| self.load(f, options) }
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/syck_node_monkeypatch.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/syck_node_monkeypatch.rb | # This is, admittedly, pretty insane. Fundamentally the challenge here is this: if we want to allow
# whitelisting of tags (while still leveraging Syck's internal functionality), then we have to
# change how Syck::Node#transform works. But since we (SafeYAML) do not control instantiation of
# Syck::Node objects, we cannot, for example, subclass Syck::Node and override #tranform the "easy"
# way. So the only choice is to monkeypatch, like this. And the only way to make this work
# recursively with potentially call-specific options (that my feeble brain can think of) is to set
# pseudo-global options on the first call and unset them once the recursive stack has fully unwound.
monkeypatch = <<-EORUBY
class Node
@@safe_transform_depth = 0
@@safe_transform_whitelist = nil
def safe_transform(options={})
begin
@@safe_transform_depth += 1
@@safe_transform_whitelist ||= options[:whitelisted_tags]
if self.type_id
SafeYAML.tag_safety_check!(self.type_id, options)
return unsafe_transform if @@safe_transform_whitelist.include?(self.type_id)
end
SafeYAML::SyckResolver.new.resolve_node(self)
ensure
@@safe_transform_depth -= 1
if @@safe_transform_depth == 0
@@safe_transform_whitelist = nil
end
end
end
alias_method :unsafe_transform, :transform
alias_method :transform, :safe_transform
end
EORUBY
if defined?(YAML::Syck::Node)
YAML::Syck.module_eval monkeypatch
else
Syck.module_eval monkeypatch
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/deep.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/deep.rb | module SafeYAML
class Deep
def self.freeze(object)
object.each do |*entry|
value = entry.last
case value
when String, Regexp
value.freeze
when Enumerable
Deep.freeze(value)
end
end
return object.freeze
end
def self.copy(object)
duplicate = object.dup rescue object
case object
when Array
(0...duplicate.count).each do |i|
duplicate[i] = Deep.copy(duplicate[i])
end
when Hash
duplicate.keys.each do |key|
duplicate[key] = Deep.copy(duplicate[key])
end
end
duplicate
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform.rb | require 'base64'
module SafeYAML
class Transform
TRANSFORMERS = [
Transform::ToSymbol.new,
Transform::ToInteger.new,
Transform::ToFloat.new,
Transform::ToNil.new,
Transform::ToBoolean.new,
Transform::ToDate.new
]
def self.to_guessed_type(value, quoted=false, options=nil)
return value if quoted
if value.is_a?(String)
TRANSFORMERS.each do |transformer|
success, transformed_value = transformer.method(:transform?).arity == 1 ?
transformer.transform?(value) :
transformer.transform?(value, options)
return transformed_value if success
end
end
value
end
def self.to_proper_type(value, quoted=false, tag=nil, options=nil)
case tag
when "tag:yaml.org,2002:binary", "x-private:binary", "!binary"
decoded = Base64.decode64(value)
decoded = decoded.force_encoding(value.encoding) if decoded.respond_to?(:force_encoding)
decoded
else
self.to_guessed_type(value, quoted, options)
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/resolver.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/resolver.rb | module SafeYAML
class Resolver
def initialize(options)
@options = SafeYAML::OPTIONS.merge(options || {})
@whitelist = @options[:whitelisted_tags] || []
@initializers = @options[:custom_initializers] || {}
@raise_on_unknown_tag = @options[:raise_on_unknown_tag]
end
def resolve_node(node)
return node if !node
return self.native_resolve(node) if tag_is_whitelisted?(self.get_node_tag(node))
case self.get_node_type(node)
when :root
resolve_root(node)
when :map
resolve_map(node)
when :seq
resolve_seq(node)
when :scalar
resolve_scalar(node)
when :alias
resolve_alias(node)
else
raise "Don't know how to resolve this node: #{node.inspect}"
end
end
def resolve_map(node)
tag = get_and_check_node_tag(node)
hash = @initializers.include?(tag) ? @initializers[tag].call : {}
map = normalize_map(self.get_node_value(node))
# Take the "<<" key nodes first, as these are meant to approximate a form of inheritance.
inheritors = map.select { |key_node, value_node| resolve_node(key_node) == "<<" }
inheritors.each do |key_node, value_node|
merge_into_hash(hash, resolve_node(value_node))
end
# All that's left should be normal (non-"<<") nodes.
(map - inheritors).each do |key_node, value_node|
hash[resolve_node(key_node)] = resolve_node(value_node)
end
return hash
end
def resolve_seq(node)
seq = self.get_node_value(node)
tag = get_and_check_node_tag(node)
arr = @initializers.include?(tag) ? @initializers[tag].call : []
seq.inject(arr) { |array, n| array << resolve_node(n) }
end
def resolve_scalar(node)
Transform.to_proper_type(self.get_node_value(node), self.value_is_quoted?(node), get_and_check_node_tag(node), @options)
end
def get_and_check_node_tag(node)
tag = self.get_node_tag(node)
SafeYAML.tag_safety_check!(tag, @options)
tag
end
def tag_is_whitelisted?(tag)
@whitelist.include?(tag)
end
def options
@options
end
private
def normalize_map(map)
# Syck creates Hashes from maps.
if map.is_a?(Hash)
map.inject([]) { |arr, key_and_value| arr << key_and_value }
# Psych is really weird; it flattens out a Hash completely into: [key, value, key, value, ...]
else
map.each_slice(2).to_a
end
end
def merge_into_hash(hash, array)
array.each do |key, value|
hash[key] = value
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/syck_resolver.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/syck_resolver.rb | module SafeYAML
class SyckResolver < Resolver
QUOTE_STYLES = [
:quote1,
:quote2
].freeze
NODE_TYPES = {
Hash => :map,
Array => :seq,
String => :scalar
}.freeze
def initialize(options={})
super
end
def native_resolve(node)
node.transform(self.options)
end
def get_node_type(node)
NODE_TYPES[node.value.class]
end
def get_node_tag(node)
node.type_id
end
def get_node_value(node)
node.value
end
def value_is_quoted?(node)
QUOTE_STYLES.include?(node.instance_variable_get(:@style))
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/libyaml_checker.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/libyaml_checker.rb | require "set"
module SafeYAML
class LibyamlChecker
LIBYAML_VERSION = Psych::LIBYAML_VERSION rescue nil
# Do proper version comparison (e.g. so 0.1.10 is >= 0.1.6)
SAFE_LIBYAML_VERSION = Gem::Version.new("0.1.6")
KNOWN_PATCHED_LIBYAML_VERSIONS = Set.new([
# http://people.canonical.com/~ubuntu-security/cve/2014/CVE-2014-2525.html
"0.1.4-2ubuntu0.12.04.3",
"0.1.4-2ubuntu0.12.10.3",
"0.1.4-2ubuntu0.13.10.3",
"0.1.4-3ubuntu3",
# https://security-tracker.debian.org/tracker/CVE-2014-2525
"0.1.3-1+deb6u4",
"0.1.4-2+deb7u4",
"0.1.4-3.2"
]).freeze
def self.libyaml_version_ok?
return true if YAML_ENGINE != "psych" || defined?(JRUBY_VERSION)
return true if Gem::Version.new(LIBYAML_VERSION || "0") >= SAFE_LIBYAML_VERSION
return libyaml_patched?
end
def self.libyaml_patched?
return false if (`which dpkg` rescue '').empty?
libyaml_version = `dpkg -s libyaml-0-2`.match(/^Version: (.*)$/)
return false if libyaml_version.nil?
KNOWN_PATCHED_LIBYAML_VERSIONS.include?(libyaml_version[1])
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/psych_resolver.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/psych_resolver.rb | module SafeYAML
class PsychResolver < Resolver
NODE_TYPES = {
Psych::Nodes::Document => :root,
Psych::Nodes::Mapping => :map,
Psych::Nodes::Sequence => :seq,
Psych::Nodes::Scalar => :scalar,
Psych::Nodes::Alias => :alias
}.freeze
def initialize(options={})
super
@aliased_nodes = {}
end
def resolve_root(root)
resolve_seq(root).first
end
def resolve_alias(node)
resolve_node(@aliased_nodes[node.anchor])
end
def native_resolve(node)
@visitor ||= SafeYAML::SafeToRubyVisitor.new(self)
@visitor.accept(node)
end
def get_node_type(node)
NODE_TYPES[node.class]
end
def get_node_tag(node)
node.tag
end
def get_node_value(node)
@aliased_nodes[node.anchor] = node if node.respond_to?(:anchor) && node.anchor
case get_node_type(node)
when :root, :map, :seq
node.children
when :scalar
node.value
end
end
def value_is_quoted?(node)
node.quoted
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/parse/hexadecimal.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/parse/hexadecimal.rb | module SafeYAML
class Parse
class Hexadecimal
MATCHER = /\A[-+]?0x[0-9a-fA-F_]+\Z/.freeze
def self.value(value)
# This is safe to do since we already validated the value.
return Integer(value.gsub(/_/, ""))
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/parse/sexagesimal.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/parse/sexagesimal.rb | module SafeYAML
class Parse
class Sexagesimal
INTEGER_MATCHER = /\A[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\Z/.freeze
FLOAT_MATCHER = /\A[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\.[0-9_]*\Z/.freeze
def self.value(value)
before_decimal, after_decimal = value.split(".")
whole_part = 0
multiplier = 1
before_decimal = before_decimal.split(":")
until before_decimal.empty?
whole_part += (Float(before_decimal.pop) * multiplier)
multiplier *= 60
end
result = whole_part
result += Float("." + after_decimal) unless after_decimal.nil?
result *= -1 if value[0] == "-"
result
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/parse/date.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/parse/date.rb | module SafeYAML
class Parse
class Date
# This one's easy enough :)
DATE_MATCHER = /\A(\d{4})-(\d{2})-(\d{2})\Z/.freeze
# This unbelievable little gem is taken basically straight from the YAML spec, but made
# slightly more readable (to my poor eyes at least) to me:
# http://yaml.org/type/timestamp.html
TIME_MATCHER = /\A\d{4}-\d{1,2}-\d{1,2}(?:[Tt]|\s+)\d{1,2}:\d{2}:\d{2}(?:\.\d*)?\s*(?:Z|[-+]\d{1,2}(?::?\d{2})?)?\Z/.freeze
SECONDS_PER_DAY = 60 * 60 * 24
MICROSECONDS_PER_SECOND = 1000000
# So this is weird. In Ruby 1.8.7, the DateTime#sec_fraction method returned fractional
# seconds in units of DAYS for some reason. In 1.9.2, they changed the units -- much more
# reasonably -- to seconds.
SEC_FRACTION_MULTIPLIER = RUBY_VERSION == "1.8.7" ? (SECONDS_PER_DAY * MICROSECONDS_PER_SECOND) : MICROSECONDS_PER_SECOND
# The DateTime class has a #to_time method in Ruby 1.9+;
# Before that we'll just need to convert DateTime to Time ourselves.
TO_TIME_AVAILABLE = DateTime.instance_methods.include?(:to_time)
def self.value(value)
d = DateTime.parse(value)
return d.to_time if TO_TIME_AVAILABLE
usec = d.sec_fraction * SEC_FRACTION_MULTIPLIER
time = Time.utc(d.year, d.month, d.day, d.hour, d.min, d.sec, usec) - (d.offset * SECONDS_PER_DAY)
time.getlocal
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_integer.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_integer.rb | module SafeYAML
class Transform
class ToInteger
MATCHERS = Deep.freeze([
/\A[-+]?(0|([1-9][0-9_,]*))\Z/, # decimal
/\A0[0-7]+\Z/, # octal
/\A0x[0-9a-f]+\Z/i, # hexadecimal
/\A0b[01_]+\Z/ # binary
])
def transform?(value)
MATCHERS.each_with_index do |matcher, idx|
value = value.gsub(/[_,]/, "") if idx == 0
return true, Integer(value) if matcher.match(value)
end
try_edge_cases?(value)
end
def try_edge_cases?(value)
return true, Parse::Hexadecimal.value(value) if Parse::Hexadecimal::MATCHER.match(value)
return true, Parse::Sexagesimal.value(value) if Parse::Sexagesimal::INTEGER_MATCHER.match(value)
return false
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_float.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_float.rb | module SafeYAML
class Transform
class ToFloat
Infinity = 1.0 / 0.0
NaN = 0.0 / 0.0
PREDEFINED_VALUES = {
".inf" => Infinity,
".Inf" => Infinity,
".INF" => Infinity,
"-.inf" => -Infinity,
"-.Inf" => -Infinity,
"-.INF" => -Infinity,
".nan" => NaN,
".NaN" => NaN,
".NAN" => NaN,
}.freeze
MATCHER = /\A[-+]?(?:\d[\d_]*)?\.[\d_]+(?:[eE][-+][\d]+)?\Z/.freeze
def transform?(value)
return true, Float(value) if MATCHER.match(value)
try_edge_cases?(value)
end
def try_edge_cases?(value)
return true, PREDEFINED_VALUES[value] if PREDEFINED_VALUES.include?(value)
return true, Parse::Sexagesimal.value(value) if Parse::Sexagesimal::FLOAT_MATCHER.match(value)
return false
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_nil.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_nil.rb | module SafeYAML
class Transform
class ToNil
include TransformationMap
set_predefined_values({
"" => nil,
"~" => nil,
"null" => nil
})
def transform?(value)
return false if value.length > 4
return PREDEFINED_VALUES.include?(value), PREDEFINED_VALUES[value]
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_symbol.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_symbol.rb | module SafeYAML
class Transform
class ToSymbol
def transform?(value, options=SafeYAML::OPTIONS)
if options[:deserialize_symbols] && value =~ /\A:./
if value =~ /\A:(["'])(.*)\1\Z/
return true, $2.sub(/^:/, "").to_sym
else
return true, value.sub(/^:/, "").to_sym
end
end
return false
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_boolean.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_boolean.rb | module SafeYAML
class Transform
class ToBoolean
include TransformationMap
set_predefined_values({
"yes" => true,
"on" => true,
"true" => true,
"no" => false,
"off" => false,
"false" => false
})
def transform?(value)
return false if value.length > 5
return PREDEFINED_VALUES.include?(value), PREDEFINED_VALUES[value]
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_date.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/to_date.rb | module SafeYAML
class Transform
class ToDate
def transform?(value)
return true, Date.parse(value) if Parse::Date::DATE_MATCHER.match(value)
return true, Parse::Date.value(value) if Parse::Date::TIME_MATCHER.match(value)
false
rescue ArgumentError
return true, value
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/transformation_map.rb | _vendor/ruby/2.6.0/gems/safe_yaml-1.0.4/lib/safe_yaml/transform/transformation_map.rb | module SafeYAML
class Transform
module TransformationMap
def self.included(base)
base.extend(ClassMethods)
end
class CaseAgnosticMap < Hash
def initialize(*args)
super
end
def include?(key)
super(key.downcase)
end
def [](key)
super(key.downcase)
end
# OK, I actually don't think it's all that important that this map be
# frozen.
def freeze
self
end
end
module ClassMethods
def set_predefined_values(predefined_values)
if SafeYAML::YAML_ENGINE == "syck"
expanded_map = predefined_values.inject({}) do |hash, (key, value)|
hash[key] = value
hash[key.capitalize] = value
hash[key.upcase] = value
hash
end
else
expanded_map = CaseAgnosticMap.new
expanded_map.merge!(predefined_values)
end
self.const_set(:PREDEFINED_VALUES, expanded_map.freeze)
end
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/test_helper.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/test_helper.rb | if ENV["COVERALL"]
require "coveralls"
Coveralls.wear!
end
require "minitest/autorun"
require "minitest/reporters"
require "mocha/setup"
Minitest::Reporters.use! Minitest::Reporters::DefaultReporter.new(color: true)
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "public_suffix"
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/psl_test.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/psl_test.rb | require "test_helper"
require "public_suffix"
# This test runs against the current PSL file and ensures
# the definitions satisfies the test suite.
class PslTest < Minitest::Test
ROOT = File.expand_path("..", __dir__)
# rubocop:disable Security/Eval
def self.tests
File.readlines(File.join(ROOT, "test/tests.txt")).map do |line|
line = line.strip
next if line.empty?
next if line.start_with?("//")
input, output = line.split(", ")
# handle the case of eval("null"), it must be eval("nil")
input = "nil" if input == "null"
output = "nil" if output == "null"
input = eval(input)
output = eval(output)
[input, output]
end
end
# rubocop:enable Security/Eval
def test_valid
# Parse the PSL and run the tests
data = File.read(PublicSuffix::List::DEFAULT_LIST_PATH)
PublicSuffix::List.default = PublicSuffix::List.parse(data)
failures = []
self.class.tests.each do |input, output|
# Punycode domains are not supported ATM
next if input =~ /xn\-\-/
domain = PublicSuffix.domain(input) rescue nil
failures << [input, output, domain] if output != domain
end
message = "The following #{failures.size} tests fail:\n"
failures.each { |i, o, d| message += "Expected %s to be %s, got %s\n" % [i.inspect, o.inspect, d.inspect] }
assert_equal 0, failures.size, message
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/acceptance_test.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/acceptance_test.rb | require "test_helper"
class AcceptanceTest < Minitest::Test
VALID_CASES = [
["example.com", "example.com", [nil, "example", "com"]],
["foo.example.com", "example.com", ["foo", "example", "com"]],
["verybritish.co.uk", "verybritish.co.uk", [nil, "verybritish", "co.uk"]],
["foo.verybritish.co.uk", "verybritish.co.uk", ["foo", "verybritish", "co.uk"]],
["parliament.uk", "parliament.uk", [nil, "parliament", "uk"]],
["foo.parliament.uk", "parliament.uk", ["foo", "parliament", "uk"]],
].freeze
def test_valid
VALID_CASES.each do |input, domain, results|
parsed = PublicSuffix.parse(input)
trd, sld, tld = results
assert_equal tld, parsed.tld, "Invalid tld for `#{name}`"
assert_equal sld, parsed.sld, "Invalid sld for `#{name}`"
if trd.nil?
assert_nil parsed.trd, "Invalid trd for `#{name}`"
else
assert_equal trd, parsed.trd, "Invalid trd for `#{name}`"
end
assert_equal domain, PublicSuffix.domain(input)
assert PublicSuffix.valid?(input)
end
end
INVALID_CASES = [
["nic.bd", PublicSuffix::DomainNotAllowed],
[nil, PublicSuffix::DomainInvalid],
["", PublicSuffix::DomainInvalid],
[" ", PublicSuffix::DomainInvalid],
].freeze
def test_invalid
INVALID_CASES.each do |(name, error)|
assert_raises(error) { PublicSuffix.parse(name) }
assert !PublicSuffix.valid?(name)
end
end
REJECTED_CASES = [
["www. .com", true],
["foo.co..uk", true],
["goo,gle.com", true],
["-google.com", true],
["google-.com", true],
# This case was covered in GH-15.
# I decided to cover this case because it's not easily reproducible with URI.parse
# and can lead to several false positives.
["http://google.com", false],
].freeze
def test_rejected
REJECTED_CASES.each do |name, expected|
assert_equal expected, PublicSuffix.valid?(name),
"Expected %s to be %s" % [name.inspect, expected.inspect]
assert !valid_domain?(name),
"#{name} expected to be invalid"
end
end
CASE_CASES = [
["Www.google.com", %w( www google com )],
["www.Google.com", %w( www google com )],
["www.google.Com", %w( www google com )],
].freeze
def test_ignore_case
CASE_CASES.each do |name, results|
domain = PublicSuffix.parse(name)
trd, sld, tld = results
assert_equal tld, domain.tld, "Invalid tld for `#{name}'"
assert_equal sld, domain.sld, "Invalid sld for `#{name}'"
assert_equal trd, domain.trd, "Invalid trd for `#{name}'"
assert PublicSuffix.valid?(name)
end
end
INCLUDE_PRIVATE_CASES = [
["blogspot.com", true, "blogspot.com"],
["blogspot.com", false, nil],
["subdomain.blogspot.com", true, "blogspot.com"],
["subdomain.blogspot.com", false, "subdomain.blogspot.com"],
].freeze
def test_ignore_private
# test domain and parse
INCLUDE_PRIVATE_CASES.each do |given, ignore_private, expected|
if expected.nil?
assert_nil PublicSuffix.domain(given, ignore_private: ignore_private)
else
assert_equal expected, PublicSuffix.domain(given, ignore_private: ignore_private)
end
end
# test valid?
INCLUDE_PRIVATE_CASES.each do |given, ignore_private, expected|
assert_equal !expected.nil?, PublicSuffix.valid?(given, ignore_private: ignore_private)
end
end
def valid_uri?(name)
uri = URI.parse(name)
!uri.host.nil?
rescue
false
end
def valid_domain?(name)
uri = URI.parse(name)
!uri.host.nil? && uri.scheme.nil?
rescue
false
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_find.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_find.rb | require 'benchmark'
require_relative "../../lib/public_suffix"
NAME_SHORT = "example.de"
NAME_MEDIUM = "www.subdomain.example.de"
NAME_LONG = "one.two.three.four.five.example.de"
NAME_WILD = "one.two.three.four.five.example.bd"
NAME_EXCP = "one.two.three.four.five.www.ck"
IAAA = "www.example.ac"
IZZZ = "www.example.zone"
PAAA = "one.two.three.four.five.example.beep.pl"
PZZZ = "one.two.three.four.five.example.now.sh"
JP = "www.yokoshibahikari.chiba.jp"
IT = "www.example.it"
COM = "www.example.com"
TIMES = (ARGV.first || 50_000).to_i
# Initialize
PublicSuffixList = PublicSuffix::List.default
PublicSuffixList.find("example.com")
Benchmark.bmbm(25) do |x|
x.report("NAME_SHORT") do
TIMES.times { PublicSuffixList.find(NAME_SHORT) != nil }
end
x.report("NAME_MEDIUM") do
TIMES.times { PublicSuffixList.find(NAME_MEDIUM) != nil }
end
x.report("NAME_LONG") do
TIMES.times { PublicSuffixList.find(NAME_LONG) != nil }
end
x.report("NAME_WILD") do
TIMES.times { PublicSuffixList.find(NAME_WILD) != nil }
end
x.report("NAME_EXCP") do
TIMES.times { PublicSuffixList.find(NAME_EXCP) != nil }
end
x.report("IAAA") do
TIMES.times { PublicSuffixList.find(IAAA) != nil }
end
x.report("IZZZ") do
TIMES.times { PublicSuffixList.find(IZZZ) != nil }
end
x.report("PAAA") do
TIMES.times { PublicSuffixList.find(PAAA) != nil }
end
x.report("PZZZ") do
TIMES.times { PublicSuffixList.find(PZZZ) != nil }
end
x.report("JP") do
TIMES.times { PublicSuffixList.find(JP) != nil }
end
x.report("IT") do
TIMES.times { PublicSuffixList.find(IT) != nil }
end
x.report("COM") do
TIMES.times { PublicSuffixList.find(COM) != nil }
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_valid.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_valid.rb | require 'benchmark'
require_relative "../../lib/public_suffix"
NAME_SHORT = "example.de"
NAME_MEDIUM = "www.subdomain.example.de"
NAME_LONG = "one.two.three.four.five.example.de"
NAME_WILD = "one.two.three.four.five.example.bd"
NAME_EXCP = "one.two.three.four.five.www.ck"
IAAA = "www.example.ac"
IZZZ = "www.example.zone"
PAAA = "one.two.three.four.five.example.beep.pl"
PZZZ = "one.two.three.four.five.example.now.sh"
JP = "www.yokoshibahikari.chiba.jp"
IT = "www.example.it"
COM = "www.example.com"
TIMES = (ARGV.first || 50_000).to_i
# Initialize
PublicSuffix.valid?("example.com")
Benchmark.bmbm(25) do |x|
x.report("NAME_SHORT") do
TIMES.times { PublicSuffix.valid?(NAME_SHORT) == true }
end
x.report("NAME_SHORT (noprivate)") do
TIMES.times { PublicSuffix.valid?(NAME_SHORT, ignore_private: true) == true }
end
x.report("NAME_MEDIUM") do
TIMES.times { PublicSuffix.valid?(NAME_MEDIUM) == true }
end
x.report("NAME_MEDIUM (noprivate)") do
TIMES.times { PublicSuffix.valid?(NAME_MEDIUM, ignore_private: true) == true }
end
x.report("NAME_LONG") do
TIMES.times { PublicSuffix.valid?(NAME_LONG) == true }
end
x.report("NAME_LONG (noprivate)") do
TIMES.times { PublicSuffix.valid?(NAME_LONG, ignore_private: true) == true }
end
x.report("NAME_WILD") do
TIMES.times { PublicSuffix.valid?(NAME_WILD) == true }
end
x.report("NAME_WILD (noprivate)") do
TIMES.times { PublicSuffix.valid?(NAME_WILD, ignore_private: true) == true }
end
x.report("NAME_EXCP") do
TIMES.times { PublicSuffix.valid?(NAME_EXCP) == true }
end
x.report("NAME_EXCP (noprivate)") do
TIMES.times { PublicSuffix.valid?(NAME_EXCP, ignore_private: true) == true }
end
x.report("IAAA") do
TIMES.times { PublicSuffix.valid?(IAAA) == true }
end
x.report("IAAA (noprivate)") do
TIMES.times { PublicSuffix.valid?(IAAA, ignore_private: true) == true }
end
x.report("IZZZ") do
TIMES.times { PublicSuffix.valid?(IZZZ) == true }
end
x.report("IZZZ (noprivate)") do
TIMES.times { PublicSuffix.valid?(IZZZ, ignore_private: true) == true }
end
x.report("PAAA") do
TIMES.times { PublicSuffix.valid?(PAAA) == true }
end
x.report("PAAA (noprivate)") do
TIMES.times { PublicSuffix.valid?(PAAA, ignore_private: true) == true }
end
x.report("PZZZ") do
TIMES.times { PublicSuffix.valid?(PZZZ) == true }
end
x.report("PZZZ (noprivate)") do
TIMES.times { PublicSuffix.valid?(PZZZ, ignore_private: true) == true }
end
x.report("JP") do
TIMES.times { PublicSuffix.valid?(JP) == true }
end
x.report("JP (noprivate)") do
TIMES.times { PublicSuffix.valid?(JP, ignore_private: true) == true }
end
x.report("IT") do
TIMES.times { PublicSuffix.valid?(IT) == true }
end
x.report("IT (noprivate)") do
TIMES.times { PublicSuffix.valid?(IT, ignore_private: true) == true }
end
x.report("COM") do
TIMES.times { PublicSuffix.valid?(COM) == true }
end
x.report("COM (noprivate)") do
TIMES.times { PublicSuffix.valid?(COM, ignore_private: true) == true }
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_find_all.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_find_all.rb | require 'benchmark'
require_relative "../../lib/public_suffix"
NAME_SHORT = "example.de"
NAME_MEDIUM = "www.subdomain.example.de"
NAME_LONG = "one.two.three.four.five.example.de"
NAME_WILD = "one.two.three.four.five.example.bd"
NAME_EXCP = "one.two.three.four.five.www.ck"
IAAA = "www.example.ac"
IZZZ = "www.example.zone"
PAAA = "one.two.three.four.five.example.beep.pl"
PZZZ = "one.two.three.four.five.example.now.sh"
JP = "www.yokoshibahikari.chiba.jp"
IT = "www.example.it"
COM = "www.example.com"
TIMES = (ARGV.first || 50_000).to_i
# Initialize
PublicSuffixList = PublicSuffix::List.default
PublicSuffixList.find("example.com")
Benchmark.bmbm(25) do |x|
x.report("NAME_SHORT") do
TIMES.times { PublicSuffixList.find(NAME_SHORT) != nil }
end
x.report("NAME_SHORT (noprivate)") do
TIMES.times { PublicSuffixList.find(NAME_SHORT, ignore_private: true) != nil }
end
x.report("NAME_MEDIUM") do
TIMES.times { PublicSuffixList.find(NAME_MEDIUM) != nil }
end
x.report("NAME_MEDIUM (noprivate)") do
TIMES.times { PublicSuffixList.find(NAME_MEDIUM, ignore_private: true) != nil }
end
x.report("NAME_LONG") do
TIMES.times { PublicSuffixList.find(NAME_LONG) != nil }
end
x.report("NAME_LONG (noprivate)") do
TIMES.times { PublicSuffixList.find(NAME_LONG, ignore_private: true) != nil }
end
x.report("NAME_WILD") do
TIMES.times { PublicSuffixList.find(NAME_WILD) != nil }
end
x.report("NAME_WILD (noprivate)") do
TIMES.times { PublicSuffixList.find(NAME_WILD, ignore_private: true) != nil }
end
x.report("NAME_EXCP") do
TIMES.times { PublicSuffixList.find(NAME_EXCP) != nil }
end
x.report("NAME_EXCP (noprivate)") do
TIMES.times { PublicSuffixList.find(NAME_EXCP, ignore_private: true) != nil }
end
x.report("IAAA") do
TIMES.times { PublicSuffixList.find(IAAA) != nil }
end
x.report("IAAA (noprivate)") do
TIMES.times { PublicSuffixList.find(IAAA, ignore_private: true) != nil }
end
x.report("IZZZ") do
TIMES.times { PublicSuffixList.find(IZZZ) != nil }
end
x.report("IZZZ (noprivate)") do
TIMES.times { PublicSuffixList.find(IZZZ, ignore_private: true) != nil }
end
x.report("PAAA") do
TIMES.times { PublicSuffixList.find(PAAA) != nil }
end
x.report("PAAA (noprivate)") do
TIMES.times { PublicSuffixList.find(PAAA, ignore_private: true) != nil }
end
x.report("PZZZ") do
TIMES.times { PublicSuffixList.find(PZZZ) != nil }
end
x.report("PZZZ (noprivate)") do
TIMES.times { PublicSuffixList.find(PZZZ, ignore_private: true) != nil }
end
x.report("JP") do
TIMES.times { PublicSuffixList.find(JP) != nil }
end
x.report("JP (noprivate)") do
TIMES.times { PublicSuffixList.find(JP, ignore_private: true) != nil }
end
x.report("IT") do
TIMES.times { PublicSuffixList.find(IT) != nil }
end
x.report("IT (noprivate)") do
TIMES.times { PublicSuffixList.find(IT, ignore_private: true) != nil }
end
x.report("COM") do
TIMES.times { PublicSuffixList.find(COM) != nil }
end
x.report("COM (noprivate)") do
TIMES.times { PublicSuffixList.find(COM, ignore_private: true) != nil }
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_select.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_select.rb | require 'benchmark'
require_relative "../../lib/public_suffix"
JP = "www.yokoshibahikari.chiba.jp"
TIMES = (ARGV.first || 50_000).to_i
# Initialize
class PublicSuffix::List
public :select
end
PublicSuffixList = PublicSuffix::List.default
PublicSuffixList.select("example.jp")
PublicSuffixList.find("example.jp")
Benchmark.bmbm(25) do |x|
x.report("JP select") do
TIMES.times { PublicSuffixList.select(JP) }
end
x.report("JP find") do
TIMES.times { PublicSuffixList.find(JP) }
end
# x.report("JP (noprivate)") do
# TIMES.times { PublicSuffixList.find(JP, ignore_private: true) != nil }
# end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_names.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_names.rb | require 'benchmark/ips'
STRING = "www.subdomain.example.com"
ARRAY = %w(
com
example.com
subdomain.example.com
www.subdomain.example.com
)
def tokenizer1(string)
parts = string.split(".").reverse!
index = 0
query = parts[index]
names = []
loop do
names << query
index += 1
break if index >= parts.size
query = parts[index] + "." + query
end
names
end
def tokenizer2(string)
parts = string.split(".")
index = parts.size - 1
query = parts[index]
names = []
loop do
names << query
index -= 1
break if index < 0
query = parts[index] + "." + query
end
names
end
def tokenizer3(string)
isx = string.size
idx = string.size - 1
names = []
loop do
isx = string.rindex(".", isx - 1) || -1
names << string[isx + 1, idx - isx]
break if isx <= 0
end
names
end
def tokenizer4(string)
isx = string.size
idx = string.size - 1
names = []
loop do
isx = string.rindex(".", isx - 1) || -1
names << string[(isx+1)..idx]
break if isx <= 0
end
names
end
(x = tokenizer1(STRING)) == ARRAY or fail("tokenizer1 failed: #{x.inspect}")
(x = tokenizer2(STRING)) == ARRAY or fail("tokenizer2 failed: #{x.inspect}")
(x = tokenizer3(STRING)) == ARRAY or fail("tokenizer3 failed: #{x.inspect}")
(x = tokenizer4(STRING)) == ARRAY or fail("tokenizer4 failed: #{x.inspect}")
Benchmark.ips do |x|
x.report("tokenizer1") do
tokenizer1(STRING).is_a?(Array)
end
x.report("tokenizer2") do
tokenizer2(STRING).is_a?(Array)
end
x.report("tokenizer3") do
tokenizer3(STRING).is_a?(Array)
end
x.report("tokenizer4") do
tokenizer4(STRING).is_a?(Array)
end
x.compare!
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_select_incremental.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/benchmarks/bm_select_incremental.rb | require 'benchmark'
require_relative "../../lib/public_suffix"
JP = "www.yokoshibahikari.chiba.jp"
TIMES = (ARGV.first || 50_000).to_i
# Initialize
class PublicSuffix::List
public :select
end
PublicSuffixList = PublicSuffix::List.default
PublicSuffixList.select("example.jp")
Benchmark.bmbm(25) do |x|
x.report("select jp") do
TIMES.times { PublicSuffixList.select("jp") }
end
x.report("select example.jp") do
TIMES.times { PublicSuffixList.select("example.jp") }
end
x.report("select www.example.jp") do
TIMES.times { PublicSuffixList.select("www.example.jp") }
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/unit/errors_test.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/unit/errors_test.rb | require "test_helper"
class ErrorsTest < Minitest::Test
# Inherits from StandardError
def test_error_inheritance
assert_kind_of StandardError,
PublicSuffix::Error.new
end
# Inherits from PublicSuffix::Error
def test_domain_invalid_inheritance
assert_kind_of PublicSuffix::Error,
PublicSuffix::DomainInvalid.new
end
# Inherits from PublicSuffix::DomainInvalid
def test_domain_not_allowed_inheritance
assert_kind_of PublicSuffix::DomainInvalid,
PublicSuffix::DomainNotAllowed.new
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/unit/domain_test.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/unit/domain_test.rb | require "test_helper"
class PublicSuffix::DomainTest < Minitest::Test
def setup
@klass = PublicSuffix::Domain
end
# Tokenizes given input into labels.
def test_self_name_to_labels
assert_equal %w( someone spaces live com ),
PublicSuffix::Domain.name_to_labels("someone.spaces.live.com")
assert_equal %w( leontina23samiko wiki zoho com ),
PublicSuffix::Domain.name_to_labels("leontina23samiko.wiki.zoho.com")
end
# Converts input into String.
def test_self_name_to_labels_converts_input_to_string
assert_equal %w( someone spaces live com ),
PublicSuffix::Domain.name_to_labels(:"someone.spaces.live.com")
end
def test_initialize_with_tld
domain = @klass.new("com")
assert_equal "com", domain.tld
assert_nil domain.sld
assert_nil domain.trd
end
def test_initialize_with_tld_and_sld
domain = @klass.new("com", "google")
assert_equal "com", domain.tld
assert_equal "google", domain.sld
assert_nil domain.trd
end
def test_initialize_with_tld_and_sld_and_trd
domain = @klass.new("com", "google", "www")
assert_equal "com", domain.tld
assert_equal "google", domain.sld
assert_equal "www", domain.trd
end
def test_to_s
assert_equal "com", @klass.new("com").to_s
assert_equal "google.com", @klass.new("com", "google").to_s
assert_equal "www.google.com", @klass.new("com", "google", "www").to_s
end
def test_to_a
assert_equal [nil, nil, "com"], @klass.new("com").to_a
assert_equal [nil, "google", "com"], @klass.new("com", "google").to_a
assert_equal ["www", "google", "com"], @klass.new("com", "google", "www").to_a
end
def test_tld
assert_equal "com", @klass.new("com", "google", "www").tld
end
def test_sld
assert_equal "google", @klass.new("com", "google", "www").sld
end
def test_trd
assert_equal "www", @klass.new("com", "google", "www").trd
end
def test_name
assert_equal "com", @klass.new("com").name
assert_equal "google.com", @klass.new("com", "google").name
assert_equal "www.google.com", @klass.new("com", "google", "www").name
end
def test_domain
assert_nil @klass.new("com").domain
assert_nil @klass.new("tldnotlisted").domain
assert_equal "google.com", @klass.new("com", "google").domain
assert_equal "google.tldnotlisted", @klass.new("tldnotlisted", "google").domain
assert_equal "google.com", @klass.new("com", "google", "www").domain
assert_equal "google.tldnotlisted", @klass.new("tldnotlisted", "google", "www").domain
end
def test_subdomain
assert_nil @klass.new("com").subdomain
assert_nil @klass.new("tldnotlisted").subdomain
assert_nil @klass.new("com", "google").subdomain
assert_nil @klass.new("tldnotlisted", "google").subdomain
assert_equal "www.google.com", @klass.new("com", "google", "www").subdomain
assert_equal "www.google.tldnotlisted", @klass.new("tldnotlisted", "google", "www").subdomain
end
def test_domain_question
assert !@klass.new("com").domain?
assert @klass.new("com", "example").domain?
assert @klass.new("com", "example", "www").domain?
assert @klass.new("tldnotlisted", "example").domain?
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/unit/rule_test.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/unit/rule_test.rb | require "test_helper"
class PublicSuffix::RuleTest < Minitest::Test
def test_factory_should_return_rule_normal
rule = PublicSuffix::Rule.factory("com")
assert_instance_of PublicSuffix::Rule::Normal, rule
rule = PublicSuffix::Rule.factory("verona.it")
assert_instance_of PublicSuffix::Rule::Normal, rule
end
def test_factory_should_return_rule_exception
rule = PublicSuffix::Rule.factory("!british-library.uk")
assert_instance_of PublicSuffix::Rule::Exception, rule
end
def test_factory_should_return_rule_wildcard
rule = PublicSuffix::Rule.factory("*.do")
assert_instance_of PublicSuffix::Rule::Wildcard, rule
rule = PublicSuffix::Rule.factory("*.sch.uk")
assert_instance_of PublicSuffix::Rule::Wildcard, rule
end
def test_default_returns_default_wildcard
default = PublicSuffix::Rule.default
assert_equal PublicSuffix::Rule::Wildcard.build("*"), default
assert_equal %w( example tldnotlisted ), default.decompose("example.tldnotlisted")
assert_equal %w( www.example tldnotlisted ), default.decompose("www.example.tldnotlisted")
end
end
class PublicSuffix::RuleBaseTest < Minitest::Test
class ::PublicSuffix::Rule::Test < ::PublicSuffix::Rule::Base
end
def setup
@klass = PublicSuffix::Rule::Base
end
def test_initialize
rule = @klass.new(value: "verona.it")
assert_instance_of @klass, rule
assert_equal "verona.it", rule.value
end
def test_equality_with_self
rule = PublicSuffix::Rule::Base.new(value: "foo")
assert_equal rule, rule
end
# rubocop:disable Style/SingleLineMethods
def test_equality_with_internals
assert_equal @klass.new(value: "foo"), @klass.new(value: "foo")
refute_equal @klass.new(value: "foo"), @klass.new(value: "bar")
refute_equal @klass.new(value: "foo"), PublicSuffix::Rule::Test.new(value: "foo")
refute_equal @klass.new(value: "foo"), PublicSuffix::Rule::Test.new(value: "bar")
refute_equal @klass.new(value: "foo"), Class.new { def name; foo; end }.new
end
# rubocop:enable Style/SingleLineMethods
def test_match
[
# standard match
[PublicSuffix::Rule.factory("uk"), "uk", true],
[PublicSuffix::Rule.factory("uk"), "example.uk", true],
[PublicSuffix::Rule.factory("uk"), "example.co.uk", true],
[PublicSuffix::Rule.factory("co.uk"), "example.co.uk", true],
# FIXME
# [PublicSuffix::Rule.factory("*.com"), "com", false],
[PublicSuffix::Rule.factory("*.com"), "example.com", true],
[PublicSuffix::Rule.factory("*.com"), "foo.example.com", true],
[PublicSuffix::Rule.factory("!example.com"), "com", false],
[PublicSuffix::Rule.factory("!example.com"), "example.com", true],
[PublicSuffix::Rule.factory("!example.com"), "foo.example.com", true],
# TLD mismatch
[PublicSuffix::Rule.factory("gk"), "example.uk", false],
[PublicSuffix::Rule.factory("gk"), "example.co.uk", false],
[PublicSuffix::Rule.factory("co.uk"), "uk", false],
# general mismatch
[PublicSuffix::Rule.factory("uk.co"), "example.co.uk", false],
[PublicSuffix::Rule.factory("go.uk"), "example.co.uk", false],
[PublicSuffix::Rule.factory("co.uk"), "uk", false],
# partial matches/mismatches
[PublicSuffix::Rule.factory("co"), "example.co.uk", false],
[PublicSuffix::Rule.factory("example"), "example.uk", false],
[PublicSuffix::Rule.factory("le.it"), "example.it", false],
[PublicSuffix::Rule.factory("le.it"), "le.it", true],
[PublicSuffix::Rule.factory("le.it"), "foo.le.it", true],
].each do |rule, input, expected|
assert_equal expected, rule.match?(input)
end
end
def test_parts
assert_raises(NotImplementedError) { @klass.new(value: "com").parts }
end
def test_decompose
assert_raises(NotImplementedError) { @klass.new(value: "com").decompose("google.com") }
end
end
class PublicSuffix::RuleNormalTest < Minitest::Test
def setup
@klass = PublicSuffix::Rule::Normal
end
def test_build
rule = @klass.build("verona.it")
assert_instance_of @klass, rule
assert_equal "verona.it", rule.value
assert_equal "verona.it", rule.rule
end
def test_length
assert_equal 1, @klass.build("com").length
assert_equal 2, @klass.build("co.com").length
assert_equal 3, @klass.build("mx.co.com").length
end
def test_parts
assert_equal %w(com), @klass.build("com").parts
assert_equal %w(co com), @klass.build("co.com").parts
assert_equal %w(mx co com), @klass.build("mx.co.com").parts
end
def test_decompose
assert_equal [nil, nil], @klass.build("com").decompose("com")
assert_equal %w( example com ), @klass.build("com").decompose("example.com")
assert_equal %w( foo.example com ), @klass.build("com").decompose("foo.example.com")
end
end
class PublicSuffix::RuleExceptionTest < Minitest::Test
def setup
@klass = PublicSuffix::Rule::Exception
end
def test_initialize
rule = @klass.build("!british-library.uk")
assert_instance_of @klass, rule
assert_equal "british-library.uk", rule.value
assert_equal "!british-library.uk", rule.rule
end
def test_length
assert_equal 2, @klass.build("!british-library.uk").length
assert_equal 3, @klass.build("!foo.british-library.uk").length
end
def test_parts
assert_equal %w( uk ), @klass.build("!british-library.uk").parts
assert_equal %w( tokyo jp ), @klass.build("!metro.tokyo.jp").parts
end
def test_decompose
assert_equal [nil, nil], @klass.build("!british-library.uk").decompose("uk")
assert_equal %w( british-library uk ), @klass.build("!british-library.uk").decompose("british-library.uk")
assert_equal %w( foo.british-library uk ), @klass.build("!british-library.uk").decompose("foo.british-library.uk")
end
end
class PublicSuffix::RuleWildcardTest < Minitest::Test
def setup
@klass = PublicSuffix::Rule::Wildcard
end
def test_initialize
rule = @klass.build("*.aichi.jp")
assert_instance_of @klass, rule
assert_equal "aichi.jp", rule.value
assert_equal "*.aichi.jp", rule.rule
end
def test_length
assert_equal 2, @klass.build("*.uk").length
assert_equal 3, @klass.build("*.co.uk").length
end
def test_parts
assert_equal %w( uk ), @klass.build("*.uk").parts
assert_equal %w( co uk ), @klass.build("*.co.uk").parts
end
def test_decompose
assert_equal [nil, nil], @klass.build("*.do").decompose("nic.do")
assert_equal %w( google co.uk ), @klass.build("*.uk").decompose("google.co.uk")
assert_equal %w( foo.google co.uk ), @klass.build("*.uk").decompose("foo.google.co.uk")
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/unit/public_suffix_test.rb | _vendor/ruby/2.6.0/gems/public_suffix-3.0.3/test/unit/public_suffix_test.rb | require "test_helper"
class PublicSuffixTest < Minitest::Test
def test_private_domains_enabled_by_default
domain = PublicSuffix.parse("www.example.blogspot.com")
assert_equal "blogspot.com", domain.tld
end
def test_private_domains_disable
data = File.read(PublicSuffix::List::DEFAULT_LIST_PATH)
PublicSuffix::List.default = PublicSuffix::List.parse(data, private_domains: false)
domain = PublicSuffix.parse("www.example.blogspot.com")
assert_equal "com", domain.tld
ensure
PublicSuffix::List.default = nil
end
def test_self_parse_a_domain_with_tld_and_sld
domain = PublicSuffix.parse("example.com")
assert_instance_of PublicSuffix::Domain, domain
assert_equal "com", domain.tld
assert_equal "example", domain.sld
assert_nil domain.trd
domain = PublicSuffix.parse("example.co.uk")
assert_instance_of PublicSuffix::Domain, domain
assert_equal "co.uk", domain.tld
assert_equal "example", domain.sld
assert_nil domain.trd
end
def test_self_parse_a_domain_with_tld_and_sld_and_trd
domain = PublicSuffix.parse("alpha.example.com")
assert_instance_of PublicSuffix::Domain, domain
assert_equal "com", domain.tld
assert_equal "example", domain.sld
assert_equal "alpha", domain.trd
domain = PublicSuffix.parse("alpha.example.co.uk")
assert_instance_of PublicSuffix::Domain, domain
assert_equal "co.uk", domain.tld
assert_equal "example", domain.sld
assert_equal "alpha", domain.trd
end
def test_self_parse_a_domain_with_tld_and_sld_and_4rd
domain = PublicSuffix.parse("one.two.example.com")
assert_instance_of PublicSuffix::Domain, domain
assert_equal "com", domain.tld
assert_equal "example", domain.sld
assert_equal "one.two", domain.trd
domain = PublicSuffix.parse("one.two.example.co.uk")
assert_instance_of PublicSuffix::Domain, domain
assert_equal "co.uk", domain.tld
assert_equal "example", domain.sld
assert_equal "one.two", domain.trd
end
def test_self_parse_name_fqdn
domain = PublicSuffix.parse("www.example.com.")
assert_instance_of PublicSuffix::Domain, domain
assert_equal "com", domain.tld
assert_equal "example", domain.sld
assert_equal "www", domain.trd
end
def test_self_parse_with_custom_list
list = PublicSuffix::List.new
list << PublicSuffix::Rule.factory("test")
domain = PublicSuffix.parse("www.example.test", list: list)
assert_instance_of PublicSuffix::Domain, domain
assert_equal "test", domain.tld
assert_equal "example", domain.sld
assert_equal "www", domain.trd
end
def test_self_parse_with_notlisted_name
domain = PublicSuffix.parse("example.tldnotlisted")
assert_instance_of PublicSuffix::Domain, domain
assert_equal "tldnotlisted", domain.tld
assert_equal "example", domain.sld
assert_nil domain.trd
end
def test_self_parse_with_unallowed_domain
error = assert_raises(PublicSuffix::DomainNotAllowed) { PublicSuffix.parse("example.bd") }
assert_match(/example\.bd/, error.message)
end
def test_self_parse_with_uri
error = assert_raises(PublicSuffix::DomainInvalid) { PublicSuffix.parse("http://google.com") }
assert_match(%r{http://google\.com}, error.message)
end
def test_self_valid
assert PublicSuffix.valid?("google.com")
assert PublicSuffix.valid?("www.google.com")
assert PublicSuffix.valid?("google.co.uk")
assert PublicSuffix.valid?("www.google.co.uk")
end
def test_self_valid_with_notlisted_name
assert PublicSuffix.valid?("google.tldnotlisted")
assert PublicSuffix.valid?("www.google.tldnotlisted")
end
# def test_self_valid_with_fully_qualified_domain_name
# assert PublicSuffix.valid?("google.com.")
# assert PublicSuffix.valid?("google.co.uk.")
# assert !PublicSuffix.valid?("google.tldnotlisted.")
# end
def test_self_domain
assert_equal "google.com", PublicSuffix.domain("google.com")
assert_equal "google.com", PublicSuffix.domain("www.google.com")
assert_equal "google.co.uk", PublicSuffix.domain("google.co.uk")
assert_equal "google.co.uk", PublicSuffix.domain("www.google.co.uk")
end
def test_self_domain_with_notlisted_name
assert_equal "example.tldnotlisted", PublicSuffix.domain("example.tldnotlisted")
end
def test_self_domain_with_unallowed_name
assert_nil PublicSuffix.domain("example.bd")
end
def test_self_domain_with_blank_sld
assert_nil PublicSuffix.domain("com")
assert_nil PublicSuffix.domain(".com")
end
def test_self_normalize
[
["com", "com"],
["example.com", "example.com"],
["www.example.com", "www.example.com"],
["example.com.", "example.com"], # strip FQDN
[" example.com ", "example.com"], # strip spaces
["Example.COM", "example.com"], # downcase
].each do |input, output|
assert_equal output, PublicSuffix.normalize(input)
end
end
def test_normalize_blank
[
nil,
"",
" ",
].each do |input|
error = PublicSuffix.normalize(input)
assert_instance_of PublicSuffix::DomainInvalid, error
assert_equal "Name is blank", error.message
end
end
def test_normalize_scheme
[
"https://google.com",
].each do |input|
error = PublicSuffix.normalize(input)
assert_instance_of PublicSuffix::DomainInvalid, error
assert_match(/scheme/, error.message)
end
end
def test_normalize_leading_dot
[
".google.com",
].each do |input|
error = PublicSuffix.normalize(input)
assert_instance_of PublicSuffix::DomainInvalid, error
assert_match "Name starts with a dot", error.message
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.