From 133d92ca3f75e9a4d641abadf46a3cd9e8e25250 Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Tue, 24 Nov 2026 23:20:34 +0000 Subject: [PATCH 1/2] fix(getting-started): use PersistedSecure and reject unknown session IDs in FirestoreSession - Subclass Rack::Session::Abstract::PersistedSecure, validate SessionId values, and key Firestore documents by sid.private_id rather than raw cookie strings. - Return [generate_sid, {}] in find_session when no Firestore document exists, overwrite session documents without merge: true, and honor options[:drop] in delete_session. - Pass httponly: true, same_site: :lax, secure: production? when mounting Rack::Session::FirestoreSession in app.rb, and add hermetic Minitest unit tests. --- getting-started/sessions/app.rb | 2 +- getting-started/sessions/firestore_session.rb | 34 ++- getting-started/sessions/test/app_test.rb | 248 ++++++++++++++++++ 3 files changed, 272 insertions(+), 12 deletions(-) create mode 100644 getting-started/sessions/test/app_test.rb diff --git a/getting-started/sessions/app.rb b/getting-started/sessions/app.rb index d108fd272..8c5b689fa 100644 --- a/getting-started/sessions/app.rb +++ b/getting-started/sessions/app.rb @@ -16,7 +16,7 @@ require_relative "firestore_session" -use Rack::Session::FirestoreSession +use Rack::Session::FirestoreSession, httponly: true, same_site: :lax, secure: production? set :greetings, ["Hello World", "Hallo Welt", "Ciao Mondo", "Salut le Monde", "Hola Mundo"] diff --git a/getting-started/sessions/firestore_session.rb b/getting-started/sessions/firestore_session.rb index 5ae028cd2..619e91398 100644 --- a/getting-started/sessions/firestore_session.rb +++ b/getting-started/sessions/firestore_session.rb @@ -17,7 +17,7 @@ module Rack module Session - class FirestoreSession < Abstract::Persisted + class FirestoreSession < Abstract::PersistedSecure def initialize app, options = {} super @@ -26,23 +26,33 @@ def initialize app, options = {} end def find_session _req, session_id - return [generate_sid, {}] if session_id.nil? + return [generate_sid, {}] unless valid_session_id? session_id - doc = @col.doc session_id - fields = doc.get.fields || {} - [session_id, stringify_keys(fields)] + snapshot = @col.doc(session_id.private_id).get + return [generate_sid, {}] unless snapshot.exists? + + [session_id, stringify_keys(snapshot.fields || {})] end def write_session _req, session_id, new_session, _opts - doc = @col.doc session_id - doc.set new_session, merge: true + session_id = generate_sid unless valid_session_id? session_id + doc = @col.doc session_id.private_id + doc.set stringify_keys(new_session) session_id end - def delete_session _req, session_id, _opts - doc = @col.doc session_id - doc.delete - generate_sid + def delete_session _req, session_id, opts + if valid_session_id? session_id + doc = @col.doc session_id.private_id + doc.delete + end + generate_sid unless opts && opts[:drop] + end + + def valid_session_id? session_id + session_id.is_a?(SessionId) && + session_id.public_id.is_a?(String) && + !session_id.public_id.empty? end def stringify_keys hash @@ -51,6 +61,8 @@ def stringify_keys hash new_hash[k.to_s] = if v.is_a? Hash stringify_keys v + elsif v.is_a? Array + v.map { |el| el.is_a?(Hash) ? stringify_keys(el) : el } else v end diff --git a/getting-started/sessions/test/app_test.rb b/getting-started/sessions/test/app_test.rb new file mode 100644 index 000000000..9bad50c18 --- /dev/null +++ b/getting-started/sessions/test/app_test.rb @@ -0,0 +1,248 @@ +# frozen_string_literal: true + +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +ENV["RACK_ENV"] = "test" + +require "digest/sha2" +require "minitest/autorun" +require "rack/test" + +require_relative "../app" + +class FakeFirestoreSnapshot + attr_reader :fields + + def initialize fields + @fields = fields + end + + def exists? + !@fields.nil? + end +end + +class FakeFirestoreDocRef + attr_reader :path + + def initialize store, path + @store = store + @path = path + end + + def get + raw = @store.documents[@path] + FakeFirestoreSnapshot.new(raw ? symbolize_value(raw) : nil) + end + + def set data, merge: false + normalized = stringify_value data + @store.documents[@path] = + if merge && @store.documents.key?(@path) + @store.documents[@path].merge normalized + else + normalized + end + end + + def delete + @store.documents.delete @path + end + + private + + def symbolize_value value + case value + when Hash + result = {} + value.each { |k, v| result[k.to_sym] = symbolize_value v } + result + when Array + value.map { |el| symbolize_value el } + else + value + end + end + + def stringify_value value + case value + when Hash + result = {} + value.each { |k, v| result[k.to_s] = stringify_value v } + result + when Array + value.map { |el| stringify_value el } + else + value + end + end +end + +class FakeFirestoreCollection + def initialize store, name + @store = store + @name = name + end + + def doc document_path + full_path = "#{@name}/#{document_path}" + segments = full_path.split "/", -1 + if segments.empty? || segments.size.odd? || segments.any?(&:empty?) + raise ArgumentError, "A document must have an even number of path elements" + end + FakeFirestoreDocRef.new @store, full_path + end +end + +class FakeFirestore + attr_reader :documents + + def initialize + @documents = {} + end + + def col name + FakeFirestoreCollection.new self, name + end +end + +describe "sessions app" do + include Rack::Test::Methods + + before do + @fake_firestore = FakeFirestore.new + Sinatra::Application.instance_variable_set :@prototype, nil + @app = nil + end + + def app + @app ||= Google::Cloud::Firestore.stub :new, @fake_firestore do + Sinatra::Application.prototype + end + end + + def extract_cookie_sid set_cookie_header + match = set_cookie_header.to_s.match(/rack\.session=([^;]+)/) + match ? match[1] : nil + end + + it "displays a greeting and increments views across requests" do + get "/" + assert_equal 200, last_response.status + assert_match(/\A

1 views for ".*"<\/h1>\z/, last_response.body) + first_greeting = last_response.body[/views for ("[^"]+")/, 1] + + 4.times do |idx| + get "/" + assert_equal 200, last_response.status + assert_includes last_response.body, "#{idx + 2} views for #{first_greeting}" + end + end + + it "sets HttpOnly and SameSite=Lax cookie flags and hashes Firestore document IDs" do + get "/" + set_cookie = last_response.headers["Set-Cookie"] + public_sid = extract_cookie_sid set_cookie + + refute_nil public_sid + assert_includes set_cookie, "HttpOnly" + assert_includes set_cookie, "SameSite=Lax" + + expected_doc_path = "sessions/2::#{Digest::SHA256.hexdigest public_sid}" + assert_equal [expected_doc_path], @fake_firestore.documents.keys + refute_includes @fake_firestore.documents.keys, "sessions/#{public_sid}" + end + + it "sets Secure cookie attribute when mounted with secure: true over HTTPS" do + secure_app = Google::Cloud::Firestore.stub :new, @fake_firestore do + Rack::Session::FirestoreSession.new( + lambda { |env| + env["rack.session"][:views] = 1 + [200, { "Content-Type" => "text/plain" }, ["ok"]] + }, + httponly: true, + same_site: :lax, + secure: true + ) + end + + env = Rack::MockRequest.env_for "https://example.org/" + _status, headers, _body = secure_app.call env + assert_match(/;\s*secure/i, headers["Set-Cookie"].to_s) + end + + it "rejects unauthenticated client-chosen session IDs (session fixation)" do + set_cookie "rack.session=ATTACKER_CHOSEN_SID" + get "/" + + assert_equal 200, last_response.status + new_sid = extract_cookie_sid last_response.headers["Set-Cookie"] + refute_nil new_sid + refute_equal "ATTACKER_CHOSEN_SID", new_sid + refute_includes @fake_firestore.documents.keys, "sessions/ATTACKER_CHOSEN_SID" + attacker_hash = "sessions/2::#{Digest::SHA256.hexdigest 'ATTACKER_CHOSEN_SID'}" + refute_includes @fake_firestore.documents.keys, attacker_hash + end + + it "rejects replay of a leaked Firestore private_id document key as a cookie" do + get "/" + victim_greeting = last_response.body[/views for ("[^"]+")/, 1] + get "/" + assert_includes last_response.body, "2 views for #{victim_greeting}" + + leaked_private_id = @fake_firestore.documents.keys.first.sub "sessions/", "" + clear_cookies + set_cookie "rack.session=#{leaked_private_id}" + get "/" + + assert_match(/\A

1 views for /, last_response.body) + assert_equal 2, @fake_firestore.documents.size + end + + it "handles slash path-traversal and empty cookies safely without escaping sessions" do + ["a/subcol/b", "a/b", ""].each do |malicious_cookie| + clear_cookies + set_cookie "rack.session=#{malicious_cookie}" + get "/" + + assert_equal 200, last_response.status + @fake_firestore.documents.each_key do |path| + assert_match(/\Asessions\/2::[0-9a-f]{64}\z/, path) + end + end + end + + it "overwrites deleted session keys without merge: true and honors drop: true" do + store = Google::Cloud::Firestore.stub :new, @fake_firestore do + Rack::Session::FirestoreSession.new ->(_env) { [200, {}, ["ok"]] } + end + + sid, initial = store.find_session nil, nil + assert_equal({}, initial) + + store.write_session nil, sid, { "user_id" => "u1", "tags" => [{ "role" => "admin" }] }, {} + _sid, loaded = store.find_session nil, sid + assert_equal({ "user_id" => "u1", "tags" => [{ "role" => "admin" }] }, loaded) + + store.write_session nil, sid, { "tags" => [{ "role" => "viewer" }] }, {} + _sid, after_delete = store.find_session nil, sid + assert_equal({ "tags" => [{ "role" => "viewer" }] }, after_delete) + refute_includes after_delete.keys, "user_id" + + dropped_result = store.delete_session nil, sid, { drop: true } + assert_nil dropped_result + assert_empty @fake_firestore.documents + end +end From 1bc948bede336d1ff6d370698049bfa5f5cd6dbc Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Wed, 25 Nov 2026 02:43:26 +0000 Subject: [PATCH 2/2] chore(getting-started): swap rspec_junit_formatter for minitest-junit in sessions Gemfile --- getting-started/sessions/Gemfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/getting-started/sessions/Gemfile b/getting-started/sessions/Gemfile index 87d1bc953..376d9509e 100644 --- a/getting-started/sessions/Gemfile +++ b/getting-started/sessions/Gemfile @@ -11,7 +11,7 @@ gem "sinatra", "~> 2.0" group :development do gem "minitest", "~> 5.13" + gem "minitest-junit", "~> 1.1" gem "rack-test", "~> 1.1" gem "rake", "~> 13.0" - gem "rspec_junit_formatter" end