Reimplementing Rails’ CSRF protection in Sinatra

CSRF?

My app

A screenshot of my online version of the game Snatch
A screenshot of my work-in-progress app
ws.send(JSON.stringify({
action: 'word',
room: '2',
handle: 'my arch nemesis',
word: 'floccinaucinihilipification' }));
module Snatch
class App < Sinatra::Base
enable :sessions
use Snatch::SnatchBackend
# ...
end
end
get '/' do
create_authenticity_token
erb :"index.html"
end

private

def create_authenticity_token
@authenticity_token = rand().to_s
session[:authenticity_token] = @authenticity_token
end
ws.send(JSON.stringify({
authenticity_token: '0.123456789',
action: 'word',
room: '2',
handle: 'my arch nemesis',
word: 'floccinaucinihilipification' }));
module Snatch
class SnatchBackend
...



def call(env)
@session = Rack::Request.new(env).session

if Faye::WebSocket.websocket?(env)
ws = Faye::WebSocket.new(env, nil, { ping: KEEPALIVE_TIME })

...

ws.on :message do |event|
@data = JSON.parse(event.data).transform_values { |value| ERB::Util.html_escape(value) }

if authenticated?
initialize_room if @redis.hget(room_key, 'tiles').nil?
perform_any_actions

@redis.publish(CHANNEL, JSON.generate(data_to_publish))
end
end
...
end
end

private

def authenticated?
@session['authenticity_token'] == data['authenticity_token']
end

...
end
end

It’s not exactly Rails

  • Aforementioned cryptography
  • I’m not resending the session cookie with each request (I think?), because I’m not using HTTP. So the session data used in SnatchBackend is probably unchanged since the most recent page load.

Questions to investigate further

--

--

--

This is my programming blog. www.github.com/david-mears

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

MilkyCars — Earn $CryptoCars rewards while holding $MILKYCARS

{UPDATE} Sex Actions Premium - Online Hack Free Resources Generator

Securing Semiconductors and the Future of the Semiconductor Ecosystem

{UPDATE} Train Merger Hack Free Resources Generator

📢 📣 Dear #Pcoin Supporters Thanks for your support - major issue here when Airdrop Distribution?

Flash Stock Firmware on Samsung GALAXY Note4 SM-N910K

Flash Stock Rom on Samsung Galaxy

Shining a Light on Third-Party Tracking

CoinW will list SHIT on 6/6 10:00 (UTC). Share 2,000 USDT-SHIT for a limited time!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
David Mears

David Mears

This is my programming blog. www.github.com/david-mears

More from Medium

Using Delayed-Job With Elasticsearch As a Backend

Using .split in Ruby to transform strings into arrays

Computer code on a computer screen

Sinatra: Basic Get, Post, Patch, and Delete request

CURD actions with Ruby Sinatra