clayzermk1 / rails-cookie-parser

Express middleware to parse Rails session cookies
MIT License
16 stars 2 forks source link

Does not work with mastodon's devise warden #3

Open VityaSchel opened 11 months ago

VityaSchel commented 11 months ago

hi I spent 6 hours and I didn't figured out how to parse this cookie. it's basically the same. mastodon on rails writes session id and then to cookie:

eyJfcmFpbHMiOnsibWVzc2FnZSI6IkltSXpOVEkwT0dKbU5qRTBNVFF3TVdWaE4yTTFaREU1TXpFNFlqVXhNbU14SWc9PSIsImV4cCI6IjIwMjQtMDgtMDNUMTk6NDg6NTEuNDg3WiIsInB1ciI6ImNvb2tpZS5fc2Vzc2lvbl9pZCJ9fQ==--d57404d1ed5a838373166d5c0a43522f452d261f

I execute this code:

const cookieValue = 'eyJfcmFpbHMiOnsibWVzc2FnZSI6IkltSXpOVEkwT0dKbU5qRTBNVFF3TVdWaE4yTTFaREU1TXpFNFlqVXhNbU14SWc9PSIsImV4cCI6IjIwMjQtMDgtMDNUMTk6NDg6NTEuNDg3WiIsInB1ciI6ImNvb2tpZS5fc2Vzc2lvbl9pZCJ9fQ==--d57404d1ed5a838373166d5c0a43522f452d261f'

const secretKey = '[128-chars secret code obtained from .env.production]'

function unpackRailsCookie (cookie: string, secret: string) {
  const [data, digest] = cookie.split('--')

  const hmac = crypto.createHmac('sha1', secret)
  hmac.update(data)

  console.log(digest, hmac.digest('hex'))
  if (secret && (digest == hmac.digest('hex'))) {
    return Buffer.from(data, 'base64')
  } else {
    return false
  }
}

console.log(unpackRailsCookie(cookieValue, secretKey))

and it returns

d57404d1ed5a838373166d5c0a43522f452d261f 81f79ea721a63b20e7db4c56de226b4e2de2347c
false

which means that digest from cookie value is not equals to generated hex digest with sha1. please help. I don't know rails nor ruby nor backend at all. what are the possible ways of solving this issue?

here are some files in mastodon's ruby directory:

config/secrets.yml


# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

config/initializers/devise.rb

warden.cookies.signed['_session_id'] = {
    value: session_id,
    expires: 1.year.from_now,
    httponly: true,
    same_site: :lax,
  }

I double-checked that data in cookie value is valid and when decoded becomes json object with sessionid, but signature can't be verified

clayzermk1 commented 11 months ago

Hi @VityaSchel,

This package only works with signed cookies. It is quite old at this point. It looks like when Rails 4 came out they introduced encrypted cookies. In Rails 5.2, the signing algorithm changed from SHA1 to SHA256. I'm not sure which version of Rails you are using, but you could try changing sha1 to sha256 node docs.