Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

Add the nightly reset and the upload and AI limits of the demo

Guido Boyke018a67266bbb
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.yml
index 8958fea..91aa238 100644
--- a/.github/workflows/guards.yml
+++ b/.github/workflows/guards.yml
@@ -185,12 +185,14 @@ jobs:
spec/jobs/tenant_propagation_spec.rb
spec/jobs/import_users_from_codebase_job_spec.rb
spec/jobs/embedding_processing_job_spec.rb
+ spec/jobs/demo_reset_job_spec.rb
spec/locales/
spec/lib/lalabase/admin_extensions_spec.rb
spec/lib/lalabase/release_spec.rb
spec/lib/lalabase/release_script_spec.rb
spec/lib/lalabase/leak_guard_spec.rb
spec/lib/lalabase/leak_guard_script_spec.rb
+ spec/lib/lalabase/demo/
spec/lib/tasks/bmp_attachments_convert_spec.rb
spec/lib/tasks/chats_backfill_scope_references_spec.rb
spec/lib/tasks/organisations_backfill_code_indexing_spec.rb
diff --git a/app/controllers/concerns/direct_uploads_guard.rb b/app/controllers/concerns/direct_uploads_guard.rb
index 3c1d338..173816a 100644
--- a/app/controllers/concerns/direct_uploads_guard.rb
+++ b/app/controllers/concerns/direct_uploads_guard.rb
@@ -13,7 +13,8 @@
# a signed-in user (Devise scope :user; the admin area does not direct-upload) and an
# upper bound on byte_size. Type rules do NOT belong here: the same endpoint serves
# documents (PDF, Office) and codebase archives, so "images only" is a rule of the
-# carrier (rich-text embed validator, spike plan E1), not of the upload.
+# carrier (rich-text embed validator, spike plan E1), not of the upload. The one
+# exception is the public demo, see #reject_demo_blob.
module DirectUploadsGuard
extend ActiveSupport::Concern
@@ -28,6 +29,7 @@ module DirectUploadsGuard
included do
before_action :require_signed_in_user
before_action :reject_oversized_blob
+ before_action :reject_demo_blob, if: -> { Lalabase::Demo.enabled? }
end
private
@@ -45,6 +47,24 @@ module DirectUploadsGuard
head :unprocessable_entity
end
+ # The public demo (Lalabase::Demo) takes less: its codebase import is blocked, so
+ # nothing legitimate there is larger than a screenshot or a PDF, and a shared
+ # instance is no file host. Lalabase::Demo::UploadLimit refuses the bytes of a
+ # larger file, or of any file once the storage budget is spent; this refuses the
+ # blob before it exists.
+ def reject_demo_blob
+ return if declared_byte_size <= Lalabase::Demo::MAX_UPLOAD_BYTES &&
+ Lalabase::Demo::UPLOAD_CONTENT_TYPES.include?(declared_content_type) &&
+ !Lalabase::Demo.storage_full?(declared_byte_size)
+
+ head :unprocessable_entity
+ end
+
+ def declared_content_type
+ blob = params[:blob]
+ blob.is_a?(ActionController::Parameters) ? blob[:content_type].to_s : ''
+ end
+
def declared_byte_size
blob = params[:blob]
return 0 unless blob.is_a?(ActionController::Parameters)
diff --git a/app/jobs/demo_reset_job.rb b/app/jobs/demo_reset_job.rb
new file mode 100644
index 0000000..7bb67d8
--- /dev/null
+++ b/app/jobs/demo_reset_job.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+# The nightly reset of the public demo (Lalabase::Demo::Reset), scheduled in
+# config/recurring.yml at Lalabase::Demo::RESET_HOUR_UTC.
+#
+# Scheduled on every production instance, and a no-op on all but the demo: without
+# both latches (the flag and the marker) it returns before touching anything.
+class DemoResetJob < ApplicationJob
+ queue_as :default
+
+ def perform
+ return unless Lalabase::Demo.resettable?
+
+ world = Lalabase::Demo::Reset.call
+ Rails.logger.info("[Demo] reset done, organisation #{world.organisation.id}")
+ end
+end
diff --git a/app/views/layouts/_demo_banner.html.erb b/app/views/layouts/_demo_banner.html.erb
index 8324024..f5b77dd 100644
--- a/app/views/layouts/_demo_banner.html.erb
+++ b/app/views/layouts/_demo_banner.html.erb
@@ -6,7 +6,7 @@
<i class="bi bi-info-circle-fill text-xl" aria-hidden="true"></i>
<p>
<strong><%= t('views.demo.banner.title') %></strong>
- <span class="ms-2"><%= t('views.demo.banner.body') %></span>
+ <span class="ms-2"><%= t('views.demo.banner.body', time: Lalabase::Demo.reset_time) %></span>
</p>
</div>
</div>
diff --git a/config/initializers/demo.rb b/config/initializers/demo.rb
index ccbb2cd..55ffdf2 100644
--- a/config/initializers/demo.rb
+++ b/config/initializers/demo.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-# Demo mode (Lalabase::Demo). Both pieces are installed on every instance and ask
-# the flag on each mail and each response, so an instance without LALABASE_DEMO
+# Demo mode (Lalabase::Demo). All three pieces are installed on every instance and ask
+# the flag on each mail, request and response, so an instance without LALABASE_DEMO
# delivers and answers as before.
#
# Explicit require: initializers run before the autoloader serves lib/ (same as
@@ -9,4 +9,7 @@
require 'lalabase/demo'
Rails.application.config.middleware.use Lalabase::Demo::NoIndex
+# First in the stack: Rack::MethodOverride parses a form body long before any
+# controller could refuse it.
+Rails.application.config.middleware.insert_before 0, Lalabase::Demo::UploadLimit
ActiveSupport.on_load(:action_mailer) { register_interceptor(Lalabase::Demo::MailDrop) }
diff --git a/config/initializers/rack_attack.rb b/config/initializers/rack_attack.rb
index ffb7437..21ddac3 100644
--- a/config/initializers/rack_attack.rb
+++ b/config/initializers/rack_attack.rb
@@ -41,6 +41,19 @@ class Rack::Attack
DIRECT_UPLOADS_PATH = %r{\A/rails/active_storage/direct_uploads#{FORMAT_SUFFIX}\z}
# The byte channel of a direct upload: PUT with the signed token from the POST above.
DISK_UPLOADS_PATH = %r{\A/rails/active_storage/disk/[^/]+\z}
+ # The requests a visitor of the public demo can make that call a model: the
+ # assistant (a new thread carries the first question, a message, a regenerated
+ # answer, an analysis, a retried run of ticket suggestions), the summaries of tickets
+ # and meetings, meeting analyses, ticket suggestions from a meeting, participant
+ # detection, customer descriptions of a time group. Adding a reference or reading
+ # asks no model. A comment asks one only with ask_ai (DEMO_ASK_AI_POSTS_PATH).
+ DEMO_MODEL_CALL_PATHS = [
+ %r{\A/org/[^/]+/assistant_chats(/[^/]+/(chatposts(/[^/]+/(regenerate|analysis))?|ticket_suggestion_runs/[^/]+/retry))?#{FORMAT_SUFFIX}\z},
+ %r{\A/org/[^/]+/projects/[^/]+/tickets/(bulk_summary|[^/]+/create_summary)#{FORMAT_SUFFIX}\z},
+ %r{\A/org/[^/]+/projects/[^/]+/meetings/(detect_participants|[^/]+/(create_summary|analyses(/[^/]+)?|ticket_suggestions/run))#{FORMAT_SUFFIX}\z},
+ %r{\A/org/[^/]+/time_session_groups/[^/]+/generate_customer_descriptions#{FORMAT_SUFFIX}\z}
+ ].freeze
+ DEMO_ASK_AI_POSTS_PATH = %r{\A/org/[^/]+/projects/[^/]+/tickets/[^/]+/posts#{FORMAT_SUFFIX}\z}
# Signup allowance per IP. Deliberately generous: a whole invited team can sit
# behind one office NAT and accept their invitations within the hour (the
@@ -74,6 +87,16 @@ class Rack::Attack
REGISTRATIONS_GLOBAL_ALERT_LIMIT = 40
REGISTRATIONS_GLOBAL_ALERT_PERIOD = 1.hour
+ # The public demo (Lalabase::Demo) pays for every visitor's questions out of one
+ # daily quota. Without a per-visitor share, the first visitor of the day could
+ # spend it all and leave the AI dead for everybody after them.
+ DEMO_MODEL_CALL_LIMIT = 10
+ DEMO_MODEL_CALL_PERIOD = 10.minutes
+ # Files in the demo: 30 an hour of at most 5 MB each per address. The storage
+ # budget (Lalabase::Demo::STORAGE_BUDGET_BYTES) is the ceiling for all of them.
+ DEMO_UPLOAD_LIMIT = 30
+ DEMO_UPLOAD_PERIOD = 1.hour
+
# Confirmation resend mails an ARBITRARY address on request — without a limit
# it is an open relay for harassment and the fastest way to burn the sender
# reputation. Mirrors the password-reset limit, which has the same property.
@@ -256,6 +279,19 @@ class Rack::Attack
req.ip if put_to?(req, DISK_UPLOADS_PATH)
end
+ ### Throttle what calls a model per IP in the public demo ###
+ # Per IP and not per user: every visitor of the demo is the same user.
+ throttle('demo_model_calls/ip', limit: DEMO_MODEL_CALL_LIMIT, period: DEMO_MODEL_CALL_PERIOD) do |req|
+ req.ip if Lalabase::Demo.enabled? && demo_model_call?(req)
+ end
+
+ ### Throttle files per IP in the public demo ###
+ # direct_uploads/user counts one user, and in the demo that is every visitor.
+ throttle('demo_uploads/ip', limit: DEMO_UPLOAD_LIMIT, period: DEMO_UPLOAD_PERIOD) do |req|
+ req.ip if Lalabase::Demo.enabled? && !(req.get? || req.head?) &&
+ req.content_length.to_i > Lalabase::Demo::LARGE_BODY_BYTES
+ end
+
### General throttling per IP (all requests) ###
throttle('requests/ip', limit: 300, period: 5.minutes) do |req|
req.ip unless normalized_path(req).start_with?('/assets')
@@ -314,6 +350,17 @@ class Rack::Attack
nil
end
+ # Any method but GET and HEAD: an analysis is updated with PATCH, and a form can
+ # carry its method in _method.
+ def self.demo_model_call?(req)
+ return false if req.get? || req.head?
+
+ path = normalized_path(req)
+ return true if DEMO_MODEL_CALL_PATHS.any? { |pattern| path.match?(pattern) }
+
+ path.match?(DEMO_ASK_AI_POSTS_PATH) && req.params['ask_ai'] == '1'
+ end
+
def self.put_to?(req, pattern)
req.put? && normalized_path(req).match?(pattern)
end
diff --git a/config/locales/views/demo.de.yml b/config/locales/views/demo.de.yml
index dd32106..3ed4591 100644
--- a/config/locales/views/demo.de.yml
+++ b/config/locales/views/demo.de.yml
@@ -4,7 +4,7 @@ de:
blocked: "In der Demo nicht verfügbar."
banner:
title: "Demo"
- body: "Alle Besucher melden sich mit diesem Konto an, andere sehen also, was du änderst. Jede Nacht wird alles zurückgesetzt."
+ body: "Alle Besucher melden sich mit diesem Konto an, andere sehen also, was du änderst. Jede Nacht um %{time} Uhr UTC wird alles zurückgesetzt."
sign_in:
lead: "Probier die Demo aus: Melde dich als %{name} an, Projektleitung bei einer erfundenen Softwarefirma."
email: "E-Mail"
diff --git a/config/locales/views/demo.en.yml b/config/locales/views/demo.en.yml
index da2e72a..2c7de6f 100644
--- a/config/locales/views/demo.en.yml
+++ b/config/locales/views/demo.en.yml
@@ -4,7 +4,7 @@ en:
blocked: "Not available in the demo."
banner:
title: "Demo"
- body: "Every visitor signs in to this account, so others see what you change. Everything is reset every night."
+ body: "Every visitor signs in to this account, so others see what you change. Everything is reset every night at %{time} UTC."
sign_in:
lead: "Try the demo: sign in as %{name}, project lead at an invented software company."
email: "Email"
diff --git a/config/puma.rb b/config/puma.rb
index a952768..04ce5d0 100644
--- a/config/puma.rb
+++ b/config/puma.rb
@@ -34,6 +34,12 @@ plugin :solid_queue if ENV['SOLID_QUEUE_IN_PUMA']
# to it, an SSH tunnel does. The flag is read by Lalabase::OperatorConsole, the
# predicate the Rails settings use too, so socket and settings cannot disagree.
require File.expand_path('../lib/lalabase/operator_console', __dir__)
+require File.expand_path('../lib/lalabase/demo', __dir__)
+
+# The public demo (Lalabase::Demo) takes no body above its upload limit. Here, because
+# Puma reads a whole body into a temporary file before the application sees it, so a
+# limit further in would still let anybody fill the disk with one request.
+http_content_length_limit Lalabase::Demo::MAX_UPLOAD_BYTES if Lalabase::Demo.enabled?
# Our servers run a Capistrano release, <deploy root>/releases/<timestamp>,
# reached through <deploy root>/current, with shared/ next to them. The root is
diff --git a/config/recurring.yml b/config/recurring.yml
index bc22290..5658ea7 100644
--- a/config/recurring.yml
+++ b/config/recurring.yml
@@ -173,6 +173,15 @@ production:
queue: default
schedule: every day at 3:40am
+ # The public demo (Lalabase::Demo::Reset): empties what visitors wrote and builds
+ # the world again. A no-op on every instance without both demo latches. The hour
+ # is Lalabase::Demo::RESET_HOUR_UTC, which the banner names; the schedule spec
+ # holds the two together.
+ demo_reset:
+ class: DemoResetJob
+ queue: default
+ schedule: "0 3 * * * UTC"
+
staging:
# Here too, so the dry-run log exists somewhere before enforcement is armed.
unconfirmed_signup_purge:
diff --git a/lib/lalabase/demo.rb b/lib/lalabase/demo.rb
index af7fe5e..a2748b5 100644
--- a/lib/lalabase/demo.rb
+++ b/lib/lalabase/demo.rb
@@ -7,7 +7,11 @@ module Lalabase
# Off unless LALABASE_DEMO=1. Everything that changes in demo mode asks
# enabled? when it runs, not at boot: the mail interceptor, the restrictions
# (DemoRestrictions), the sign-in page, the banner, the lockout and the
- # per-address login throttle. An instance without the flag behaves as before.
+ # per-address login throttle, the upload limits and budget, and the throttle on
+ # everything that calls a model. An instance without the flag behaves as before.
+ #
+ # The nightly reset (Lalabase::Demo::Reset) needs a second latch, the marker
+ # that `bin/rails lalabase:demo:setup` writes (Lalabase::Demo::Setup).
#
# The published login is shared by every visitor at once, so it must not be
# lockable, throttled per address, renamed or given a new password, and the
@@ -23,6 +27,24 @@ module Lalabase
# signed-in person of the fiction carries it; the others get a random one,
# or a visitor could sign in as the account admin.
PASSWORD = 'nordlicht-demo'
+ # The hour (UTC) of the nightly reset (DemoResetJob). The banner reads it from
+ # here; spec/config/recurring_schedule_spec.rb holds config/recurring.yml to it.
+ RESET_HOUR_UTC = 3
+ # The second latch of the reset (Lalabase::Demo::Reset): a row in system_settings
+ # that only `bin/rails lalabase:demo:setup` writes, and only on an instance
+ # without organisations. The flag alone never empties a database.
+ MARKER_KEY = 'demo_instance'
+ # The largest request body a visitor may send, and what a direct upload may be.
+ # Disk space on a public instance is shared by everybody, and the demo is no
+ # file host. Plain numbers: config/puma.rb reads them before Rails is loaded.
+ MAX_UPLOAD_BYTES = 5 * 1024 * 1024
+ # What all stored files of the demo may add up to until the next reset. The
+ # per-address throttles follow a header a client can set; this one cannot be
+ # walked around.
+ STORAGE_BUDGET_BYTES = 1024 * 1024 * 1024
+ # A body above this size carries a file; below it, a form or a message.
+ LARGE_BODY_BYTES = 64 * 1024
+ UPLOAD_CONTENT_TYPES = %w[image/png image/jpeg image/gif image/webp application/pdf].freeze
class << self
def enabled?(env = ENV)
@@ -35,6 +57,20 @@ module Lalabase
def published_login?(email)
enabled? && email.is_a?(String) && email.strip.casecmp?(login_email)
end
+
+ def marked? = SystemSetting.exists?(key: MARKER_KEY)
+
+ # Both latches: the flag and the marker. Asked by the reset itself, not only by
+ # the job that schedules it.
+ def resettable? = enabled? && marked?
+
+ # Whether `adding` more bytes would take the stored files past the budget.
+ def storage_full?(adding = 0)
+ ActiveStorage::Blob.sum(:byte_size) + adding > STORAGE_BUDGET_BYTES
+ end
+
+ # The clock reads the same in both languages, so no locale format.
+ def reset_time = format('%02d:00', RESET_HOUR_UTC)
end
# Drops every outgoing mail while demo mode is on. An invitation or a
@@ -47,6 +83,32 @@ module Lalabase
end
end
+ # Refuses a request body above MAX_UPLOAD_BYTES in demo mode, and any body that
+ # carries a file once the stored files have reached STORAGE_BUDGET_BYTES. Covers
+ # every way a file comes in: the byte channel of direct uploads, and the forms that
+ # post a file themselves (documents, comment attachments).
+ #
+ # Puma has read the body by then (into a temporary file, and it turns a chunked
+ # body into one with a length), so this is the answer, not the disk protection:
+ # config/puma.rb sets the same limit for Puma itself in demo mode.
+ class UploadLimit
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ return @app.call(env) unless Demo.enabled? && refused?(env['CONTENT_LENGTH'].to_i)
+
+ [413, { 'content-type' => 'text/plain' }, ["Request too large for the demo.\n"]]
+ end
+
+ private
+
+ def refused?(length)
+ length > MAX_UPLOAD_BYTES || (length > LARGE_BODY_BYTES && Demo.storage_full?(length))
+ end
+ end
+
# X-Robots-Tag on every response in demo mode, attachments included: the
# pages show whatever visitors wrote, and that should not end up in a search
# engine.
diff --git a/lib/lalabase/demo/reset.rb b/lib/lalabase/demo/reset.rb
new file mode 100644
index 0000000..d9018d3
--- /dev/null
+++ b/lib/lalabase/demo/reset.rb
@@ -0,0 +1,155 @@
+# frozen_string_literal: true
+
+module Lalabase
+ module Demo
+ # The nightly reset of the public demo (DemoResetJob, `bin/rails lalabase:demo:reset`):
+ # empties every table that holds what visitors wrote, deletes the stored files, and
+ # builds the Nordlicht world again.
+ #
+ # Refuses unless both latches hold (Demo.resettable?): the flag LALABASE_DEMO and the
+ # marker row that only Lalabase::Demo::Setup writes. A self-hoster who sets the flag
+ # by mistake loses nothing.
+ #
+ # Everything is wiped unless KEPT_TABLES names it, so a new table of visitor content
+ # is wiped without anybody remembering it. The kept ones belong to the instance: the
+ # schema, the queue the job runs in, the admins, the settings with the marker, and
+ # the AI credentials and packages the operator configured.
+ #
+ # One TRUNCATE without CASCADE, in one transaction with the new world: Postgres
+ # refuses it when a kept table still references a wiped one (CASCADE would empty
+ # the kept table instead, silently), and a world that fails to build leaves the old
+ # one in place. The files of kept records survive (StoredFiles), their rich text
+ # would not, which the guard in spec/architecture/demo_reset_tables_guard_spec.rb
+ # rules out together with the foreign keys.
+ #
+ # Not Organisation#destroy: it has known blockers (projects with documents) and runs
+ # every callback for data that is about to go anyway.
+ class Reset
+ class Refused < StandardError; end
+
+ KEPT_TABLES = %w[
+ schema_migrations ar_internal_metadata
+ beusers system_settings
+ ai_credentials ai_credential_contracts ai_credential_documents ai_credential_contract_documents
+ ai_packages ai_package_tiers
+ price_lists price_tiers
+ product_knowledge_entries
+ ].freeze
+ # Solid Queue runs this very job; its tables are the scheduler's, not the visitors'.
+ KEPT_PREFIX = 'solid_queue_'
+
+ # AI on, through the instance's system credential: no own key, no package.
+ ORGANISATION = { ai_enabled: true, assistant_enabled: true, ai_provider: 'openai' }.freeze
+ LOCALE = :en
+
+ def self.call(**) = new(**).call
+
+ def self.kept_table?(table) = KEPT_TABLES.include?(table) || table.start_with?(KEPT_PREFIX)
+
+ def self.wiped_tables(connection = ActiveRecord::Base.connection)
+ connection.tables.reject { |table| kept_table?(table) }.sort
+ end
+
+ def initialize(now: Time.current)
+ @now = now
+ end
+
+ # @return [Lalabase::Demo::World] the world built afterwards
+ def call
+ raise Refused, 'Demo mode is off or this instance was never set up as a demo.' unless Demo.resettable?
+
+ # The job, the task and the setup run without a tenant, and the commit fires
+ # callbacks of every record of the world (ProjectPermission subscribes its
+ # person) outside World#build's own with_tenant.
+ ActsAsTenant.without_tenant { reset }
+ end
+
+ private
+
+ def reset
+ files = nil
+ world = ActiveRecord::Base.transaction do
+ files = StoredFiles.new(self.class)
+ wipe
+ files.restore_kept
+ reseed
+ World.new(locale: LOCALE, now: @now, organisation: ORGANISATION, embeddings: true,
+ password: PASSWORD).build
+ end
+ # After the commit: a world that failed to build keeps its files. The
+ # embeddings first, so a file that cannot be deleted costs nothing else.
+ Embeddings::ActivationBackfill.call(world.organisation)
+ files.delete_wiped
+ world
+ end
+
+ def wipe
+ connection = ActiveRecord::Base.connection
+ tables = self.class.wiped_tables(connection).map { |table| connection.quote_table_name(table) }
+ connection.execute("TRUNCATE #{tables.join(', ')}")
+ end
+
+ # The global persona pool hangs on organisations by a foreign key, so it goes
+ # with them and comes back from the seed every instance loads. Wrapped, so the
+ # seed's constant is not redefined in the worker every night.
+ def reseed
+ load Rails.root.join('db/seeds/prompt_personas.rb').to_s, true
+ end
+
+ # The stored files across a reset. Attachments and blobs live in wiped tables, also
+ # those of a kept record (the terms of an AI credential), so those rows are copied
+ # aside and written back after the TRUNCATE, and their files stay. A preview or
+ # variant of a kept file hangs on the blob, not on the record, and is made again
+ # when somebody asks for it.
+ #
+ # Read under a lock: a blob created between the read and the TRUNCATE would lose
+ # its row and keep its file.
+ class StoredFiles
+ STORAGE_TABLES = %w[active_storage_blobs active_storage_attachments].freeze
+
+ def initialize(reset_class)
+ @connection = ActiveRecord::Base.connection
+ @connection.execute("LOCK TABLE #{STORAGE_TABLES.join(', ')} IN ACCESS EXCLUSIVE MODE")
+ kept = ActiveStorage::Attachment.where(record_type: kept_record_types(reset_class))
+ @kept_blob_ids = kept.pluck(:blob_id)
+ @wiped = ActiveStorage::Blob.where.not(id: @kept_blob_ids).pluck(:service_name, :key)
+ set_aside(kept)
+ end
+
+ def restore_kept
+ @connection.execute('INSERT INTO active_storage_blobs SELECT * FROM demo_kept_blobs')
+ @connection.execute('INSERT INTO active_storage_attachments SELECT * FROM demo_kept_attachments')
+ end
+
+ # One file that cannot be deleted does not keep the others.
+ def delete_wiped
+ @wiped.each do |service_name, key|
+ ActiveStorage::Blob.services.fetch(service_name).delete(key)
+ rescue StandardError => e
+ Rails.logger.warn("[Demo] reset could not delete stored file #{key}: #{e.class}")
+ end
+ end
+
+ private
+
+ def kept_record_types(reset_class)
+ ActiveStorage::Attachment.distinct.pluck(:record_type).select do |type|
+ model = type.safe_constantize
+ model.respond_to?(:table_name) && reset_class.kept_table?(model.table_name)
+ end
+ end
+
+ # Temporary tables of this transaction, gone with its commit.
+ def set_aside(kept)
+ @connection.execute(<<~SQL.squish)
+ CREATE TEMPORARY TABLE demo_kept_attachments ON COMMIT DROP AS #{kept.to_sql}
+ SQL
+ @connection.execute(<<~SQL.squish)
+ CREATE TEMPORARY TABLE demo_kept_blobs ON COMMIT DROP AS
+ #{ActiveStorage::Blob.where(id: @kept_blob_ids).to_sql}
+ SQL
+ end
+ end
+ end
+ end
+end
diff --git a/lib/lalabase/demo/setup.rb b/lib/lalabase/demo/setup.rb
new file mode 100644
index 0000000..380011a
--- /dev/null
+++ b/lib/lalabase/demo/setup.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module Lalabase
+ module Demo
+ # Turns a fresh instance into the public demo, once: `bin/rails lalabase:demo:setup`.
+ #
+ # Writes the marker (Demo::MARKER_KEY), the second latch of Lalabase::Demo::Reset,
+ # closes the registration, and runs the first reset. Refuses without the flag, and
+ # on an instance that has any organisation: whatever is in there would be gone by
+ # the next morning.
+ class Setup
+ class Refused < StandardError; end
+
+ def self.call(**) = new(**).call
+
+ def initialize(now: Time.current)
+ @now = now
+ end
+
+ # @return [Lalabase::Demo::World]
+ def call
+ raise Refused, "Set #{ENV_FLAG}=#{ENABLED_VALUE} first." unless Demo.enabled?
+ raise Refused, 'This instance is a demo already; it resets every night.' if Demo.marked?
+ raise Refused, 'This instance has organisations. A demo resets every night, so it starts empty.' if Organisation.exists?
+
+ SystemSetting.set(:allow_registration, false)
+ SystemSetting.set(MARKER_KEY, true)
+ Reset.call(now: @now)
+ end
+ end
+ end
+end
diff --git a/lib/tasks/demo.rake b/lib/tasks/demo.rake
new file mode 100644
index 0000000..fdeeef5
--- /dev/null
+++ b/lib/tasks/demo.rake
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+# The public demo (Lalabase::Demo). Both tasks need LALABASE_DEMO=1.
+#
+# bin/rails lalabase:demo:setup once, on a fresh instance: marker, registration
+# closed, first world
+# bin/rails lalabase:demo:reset the nightly reset, by hand
+namespace :lalabase do
+ namespace :demo do
+ desc 'Turn a fresh instance into the public demo (needs LALABASE_DEMO=1, no organisations)'
+ task setup: :environment do
+ world = Lalabase::Demo::Setup.call
+ puts "Demo ready. Sign in as #{world.signed_in.email}; it resets every night at " \
+ "#{Lalabase::Demo.reset_time} UTC."
+ rescue Lalabase::Demo::Setup::Refused => e
+ abort "lalabase:demo:setup: #{e.message}"
+ end
+
+ desc 'Reset the public demo now (needs LALABASE_DEMO=1 and lalabase:demo:setup)'
+ task reset: :environment do
+ Lalabase::Demo::Reset.call
+ puts 'Demo reset.'
+ rescue Lalabase::Demo::Reset::Refused => e
+ abort "lalabase:demo:reset: #{e.message}"
+ end
+ end
+end
diff --git a/spec/architecture/demo_reset_tables_guard_spec.rb b/spec/architecture/demo_reset_tables_guard_spec.rb
new file mode 100644
index 0000000..eed154a
--- /dev/null
+++ b/spec/architecture/demo_reset_tables_guard_spec.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# Which tables the demo reset (Lalabase::Demo::Reset) keeps. Everything else is wiped,
+# so a new table of visitor content needs no entry; a kept table is the exception and
+# has to stay one that holds nothing a visitor wrote.
+RSpec.describe 'Demo reset tables', :ci_guard, type: :model do
+ let(:connection) { ActiveRecord::Base.connection }
+ let(:kept) { connection.tables.select { |table| Lalabase::Demo::Reset.kept_table?(table) } }
+ let(:wiped) { Lalabase::Demo::Reset.wiped_tables(connection) }
+
+ it 'keeps only tables that exist' do
+ expect(Lalabase::Demo::Reset::KEPT_TABLES - connection.tables).to be_empty
+ end
+
+ # TRUNCATE without CASCADE refuses such a pair; with CASCADE it would empty the kept
+ # table. Either way the reset could not keep it.
+ it 'keeps no table that references a wiped one' do
+ references = kept.flat_map do |table|
+ connection.foreign_keys(table).filter_map { |fk| "#{table} -> #{fk.to_table}" if wiped.include?(fk.to_table) }
+ end
+ expect(references).to be_empty
+ end
+
+ # A row that names an organisation or a person belongs to the world of one day.
+ it 'keeps no table with rows of an organisation or a person' do
+ owned = kept.select { |table| connection.columns(table).map(&:name).intersect?(%w[organisation_id user_id]) }
+ expect(owned).to be_empty
+ end
+
+ # Files of kept records are copied across the reset (Reset::StoredFiles); rich text
+ # is not, its table is wiped, and a kept record would come back without its text.
+ it 'keeps no record with rich text' do
+ Rails.application.eager_load!
+ with_rich_text = ApplicationRecord.descendants.reject(&:abstract_class?).select do |model|
+ model.reflect_on_all_associations.any? { |association| association.class_name == 'ActionText::RichText' }
+ end
+ # The scan has to see rich text at all, or an empty answer below proves nothing.
+ expect(with_rich_text).to include(Ticket)
+ expect(with_rich_text.select { |model| Lalabase::Demo::Reset.kept_table?(model.table_name) }).to be_empty
+ end
+
+ it 'wipes the tables of the world' do
+ expect(wiped).to include('organisations', 'users', 'tickets', 'active_storage_blobs', 'prompt_personas')
+ end
+end
diff --git a/spec/config/puma_bind_guard_spec.rb b/spec/config/puma_bind_guard_spec.rb
index 0e4a0d6..a4566f8 100644
--- a/spec/config/puma_bind_guard_spec.rb
+++ b/spec/config/puma_bind_guard_spec.rb
@@ -27,7 +27,7 @@ require 'rails_helper'
# console apart. Everything else Puma's DSL offers (threads, plugins) is
# irrelevant here and gets swallowed.
class PumaConfigProbe
- attr_reader :binds, :ports, :pidfile_path, :state_file, :worker_count
+ attr_reader :binds, :ports, :pidfile_path, :state_file, :worker_count, :content_length_limit
def initialize
@binds = []
@@ -59,15 +59,19 @@ class PumaConfigProbe
@preloaded = true
end
+ def http_content_length_limit(bytes)
+ @content_length_limit = bytes
+ end
+
def preloaded?
@preloaded
end
# The probe evaluates config/puma.rb under a release path that does not exist
- # here, so its require of the operator console resolves to nowhere. Rails has
- # loaded that file already.
+ # here, so its requires of the operator console and the demo resolve to nowhere.
+ # Rails has loaded those files already.
def require(path)
- path.end_with?('lib/lalabase/operator_console') || super
+ path.end_with?('lib/lalabase/operator_console', 'lib/lalabase/demo') || super
end
def method_missing(_name, *_args, &_block)
@@ -223,4 +227,21 @@ RSpec.describe 'config/puma.rb bindings' do
expect(config.binds).to be_empty
end
end
+
+ # Puma reads a whole body into a temporary file before Rails can refuse it, so the
+ # demo's upload limit (Lalabase::Demo::UploadLimit) protects the disk only here.
+ describe 'the body limit of the public demo' do
+ def probe_demo(flag)
+ flag_was = ENV.fetch(Lalabase::Demo::ENV_FLAG, nil)
+ ENV[Lalabase::Demo::ENV_FLAG] = flag
+ probe('production', container_flag: '1')
+ ensure
+ ENV[Lalabase::Demo::ENV_FLAG] = flag_was
+ end
+
+ it 'is the upload limit in demo mode, and Puma\'s own default otherwise' do
+ expect(probe_demo(Lalabase::Demo::ENABLED_VALUE).content_length_limit).to eq(Lalabase::Demo::MAX_UPLOAD_BYTES)
+ expect(probe_demo(nil).content_length_limit).to be_nil
+ end
+ end
end
diff --git a/spec/config/recurring_schedule_spec.rb b/spec/config/recurring_schedule_spec.rb
index a273cc7..d7492e0 100644
--- a/spec/config/recurring_schedule_spec.rb
+++ b/spec/config/recurring_schedule_spec.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
require 'rails_helper'
+require 'fugit'
# What: config/recurring.yml — Solid Queue recurring schedule drift guard.
# Type: Config spec.
@@ -144,6 +145,19 @@ RSpec.describe 'config/recurring.yml' do
end
end
+ # The demo banner names the hour of the reset (Lalabase::Demo::RESET_HOUR_UTC).
+ # A schedule moved here without the constant would make the banner lie. In UTC
+ # explicitly: a cron line without a zone runs in the server's local time.
+ describe 'demo reset' do
+ it 'runs nightly at the hour the banner names' do
+ entry = schedule.fetch('production')['demo_reset']
+ expect(entry['class']).to eq('DemoResetJob')
+
+ cron = Fugit.parse_cron(entry['schedule'])
+ expect([cron.hours, cron.minutes, cron.timezone&.name]).to eq([[Lalabase::Demo::RESET_HOUR_UTC], [0], 'UTC'])
+ end
+ end
+
# A duplicated key does not raise: YAML keeps the last one and drops the first
# silently, so a task can vanish from the schedule while the file still shows
# it. Parsing cannot catch this — the duplicate is gone by then — so the check
diff --git a/spec/jobs/demo_reset_job_spec.rb b/spec/jobs/demo_reset_job_spec.rb
new file mode 100644
index 0000000..0cebe57
--- /dev/null
+++ b/spec/jobs/demo_reset_job_spec.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# Scheduled on every production instance; resets only the demo.
+RSpec.describe DemoResetJob, :ci_guard do
+ let(:demo_on) { true }
+
+ around do |example|
+ flag_was = ENV.fetch(Lalabase::Demo::ENV_FLAG, nil)
+ ENV[Lalabase::Demo::ENV_FLAG] = demo_on ? Lalabase::Demo::ENABLED_VALUE : nil
+ example.run
+ ensure
+ ENV[Lalabase::Demo::ENV_FLAG] = flag_was
+ end
+
+ before do
+ allow(Lalabase::Demo::Reset).to receive(:call)
+ .and_return(instance_double(Lalabase::Demo::World, organisation: build_stubbed(:organisation)))
+ end
+
+ it 'resets a marked demo' do
+ SystemSetting.set(Lalabase::Demo::MARKER_KEY, true)
+ described_class.perform_now
+ expect(Lalabase::Demo::Reset).to have_received(:call)
+ end
+
+ it 'does nothing on a demo that was never set up' do
+ described_class.perform_now
+ expect(Lalabase::Demo::Reset).not_to have_received(:call)
+ end
+
+ context 'without the flag' do
+ let(:demo_on) { false }
+
+ it 'does nothing, marker or not' do
+ SystemSetting.set(Lalabase::Demo::MARKER_KEY, true)
+ described_class.perform_now
+ expect(Lalabase::Demo::Reset).not_to have_received(:call)
+ end
+ end
+end
diff --git a/spec/lib/lalabase/demo/reset_spec.rb b/spec/lib/lalabase/demo/reset_spec.rb
new file mode 100644
index 0000000..c495312
--- /dev/null
+++ b/spec/lib/lalabase/demo/reset_spec.rb
@@ -0,0 +1,139 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# The nightly reset of the public demo: what visitors wrote goes, the instance's own
+# configuration stays, and nothing happens without both latches.
+#
+# No tenant and no bypass around the examples: the job, the rake task and the setup
+# call the reset that way, and a callback that needs a tenant has to fail here too.
+RSpec.describe Lalabase::Demo::Reset, :ci_guard do
+ let(:fiction) { Lalabase::Demo::Fiction }
+ let(:demo_on) { true }
+
+ around do |example|
+ flag_was = ENV.fetch(Lalabase::Demo::ENV_FLAG, nil)
+ ENV[Lalabase::Demo::ENV_FLAG] = demo_on ? Lalabase::Demo::ENABLED_VALUE : nil
+ example.run
+ ensure
+ ENV[Lalabase::Demo::ENV_FLAG] = flag_was
+ end
+
+ # What visitors left behind yesterday, and what the operator configured.
+ let!(:visitor_organisation) { create(:organisation, name: 'Written by a visitor') }
+ let!(:visitor_persona) { create(:prompt_persona, organisation: visitor_organisation) }
+ let!(:visitor_file) { ActiveStorage::Blob.create_and_upload!(io: StringIO.new('a file'), filename: 'visitor.txt') }
+ let!(:admin) { create(:beuser) }
+ let!(:credential) { create(:ai_credential) }
+ let!(:price_list) { create(:price_list) }
+ let!(:product_knowledge) { create(:product_knowledge_entry) }
+ # A kept record with a file: its attachment and blob sit in wiped tables.
+ let!(:contract_terms) do
+ create(:ai_credential_document, ai_credential: credential).tap do |document|
+ document.file.attach(io: StringIO.new('%PDF-1.4 terms'), filename: 'terms.pdf', content_type: 'application/pdf')
+ end
+ end
+
+ before { allow(Embeddings::ActivationBackfill).to receive(:call) }
+
+ def mark = SystemSetting.set(Lalabase::Demo::MARKER_KEY, true)
+
+ # The world is written record by record through the actors (see world_spec.rb).
+ def reset = Prosopite.pause { described_class.call }
+
+ def stored?(blob) = blob.service.exist?(blob.key)
+
+ describe 'with both latches' do
+ before { mark }
+
+ it 'empties what visitors wrote and builds the world again' do
+ world = reset
+
+ expect(Organisation.pluck(:id)).to eq([world.organisation.id])
+ expect(User.pluck(:email)).to match_array(fiction::PEOPLE.keys.map { fiction.email(_1) })
+ expect(PromptPersona.exists?(visitor_persona.id)).to be(false)
+ expect(ActiveStorage::Blob.exists?(visitor_file.id)).to be(false)
+ expect(stored?(visitor_file)).to be(false)
+ expect(Embeddings::ActivationBackfill).to have_received(:call).with(world.organisation)
+ end
+
+ it 'gives the world the assistant and the published login' do
+ world = reset
+
+ expect(world.organisation).to have_attributes(described_class::ORGANISATION)
+ expect(world.signed_in.email).to eq(Lalabase::Demo.login_email)
+ expect(world.signed_in.valid_password?(Lalabase::Demo::PASSWORD)).to be(true)
+ expect(world.notes).to all(have_attributes(create_embeddings: true))
+ end
+
+ it 'keeps the configuration of the instance, the marker among it' do
+ reset
+
+ expect(Beuser.exists?(admin.id)).to be(true)
+ expect(AiCredential.exists?(credential.id)).to be(true)
+ expect(PriceList.exists?(price_list.id)).to be(true)
+ expect(ProductKnowledgeEntry.exists?(product_knowledge.id)).to be(true)
+ expect(Lalabase::Demo).to be_marked
+ end
+
+ it 'keeps the files of what it keeps' do
+ blob = contract_terms.file.blob
+ reset
+
+ expect(AiCredentialDocument.find(contract_terms.id).file.blob).to eq(blob)
+ expect(stored?(blob)).to be(true)
+ end
+
+ it 'brings the global personas back' do
+ reset
+
+ expect(PromptPersona.where(organisation_id: nil).pluck(:key)).to include(PromptPersona::DEFAULT_KEY)
+ end
+
+ # CASCADE would empty a kept table that references a wiped one instead of refusing.
+ it 'never cascades' do
+ statements = []
+ callback = ->(*, payload) { statements << payload[:sql] if payload[:sql].start_with?('TRUNCATE') }
+ ActiveSupport::Notifications.subscribed(callback, 'sql.active_record') { reset }
+
+ expect(statements.size).to eq(1)
+ expect(statements.first).not_to match(/CASCADE/i)
+ end
+
+ it 'still starts the embeddings when a file cannot be deleted' do
+ allow_any_instance_of(ActiveStorage::Service::DiskService).to receive(:delete).and_raise(Errno::EACCES)
+
+ world = reset
+ expect(Embeddings::ActivationBackfill).to have_received(:call).with(world.organisation)
+ end
+
+ it 'leaves yesterday in place when the world fails to build' do
+ allow_any_instance_of(Lalabase::Demo::World).to receive(:build).and_raise('broken')
+
+ expect { reset }.to raise_error('broken')
+ expect(Organisation.exists?(visitor_organisation.id)).to be(true)
+ expect(stored?(visitor_file)).to be(true)
+ end
+ end
+
+ describe 'refuses and touches nothing' do
+ def expect_refused
+ expect { reset }.to raise_error(described_class::Refused)
+ expect(Organisation.exists?(visitor_organisation.id)).to be(true)
+ expect(stored?(visitor_file)).to be(true)
+ end
+
+ it 'without the marker' do
+ expect_refused
+ end
+
+ context 'without the flag' do
+ let(:demo_on) { false }
+
+ it 'even with the marker' do
+ mark
+ expect_refused
+ end
+ end
+ end
+end
diff --git a/spec/lib/lalabase/demo/setup_spec.rb b/spec/lib/lalabase/demo/setup_spec.rb
new file mode 100644
index 0000000..213f03f
--- /dev/null
+++ b/spec/lib/lalabase/demo/setup_spec.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# `bin/rails lalabase:demo:setup`: the only writer of the reset's second latch, and
+# only on an instance with nothing to lose.
+RSpec.describe Lalabase::Demo::Setup, :ci_guard do
+ let(:demo_on) { true }
+ let(:world) { instance_double(Lalabase::Demo::World) }
+
+ around do |example|
+ flag_was = ENV.fetch(Lalabase::Demo::ENV_FLAG, nil)
+ ENV[Lalabase::Demo::ENV_FLAG] = demo_on ? Lalabase::Demo::ENABLED_VALUE : nil
+ example.run
+ ensure
+ ENV[Lalabase::Demo::ENV_FLAG] = flag_was
+ end
+
+ before { allow(Lalabase::Demo::Reset).to receive(:call).and_return(world) }
+
+ it 'marks the instance, closes the registration and runs the first reset' do
+ expect(described_class.call).to eq(world)
+
+ expect(Lalabase::Demo).to be_marked
+ expect(SystemSetting.allow_registration?).to be(false)
+ expect(Lalabase::Demo::Reset).to have_received(:call)
+ end
+
+ it 'refuses on an instance with an organisation' do
+ create(:organisation)
+
+ expect { described_class.call }.to raise_error(described_class::Refused, /organisations/)
+ expect(Lalabase::Demo).not_to be_marked
+ expect(Lalabase::Demo::Reset).not_to have_received(:call)
+ end
+
+ it 'refuses a second time' do
+ described_class.call
+
+ expect { described_class.call }.to raise_error(described_class::Refused, /demo already/)
+ end
+
+ # The real reset, called the way the rake task calls it: no tenant, no stub.
+ it 'leaves a world to sign in to' do
+ allow(Lalabase::Demo::Reset).to receive(:call).and_call_original
+ allow(Embeddings::ActivationBackfill).to receive(:call)
+
+ world = Prosopite.pause { described_class.call }
+ expect(world.signed_in.valid_password?(Lalabase::Demo::PASSWORD)).to be(true)
+ expect(Lalabase::Demo).to be_resettable
+ end
+
+ context 'without the flag' do
+ let(:demo_on) { false }
+
+ it 'refuses and writes nothing' do
+ expect { described_class.call }.to raise_error(described_class::Refused, /LALABASE_DEMO/)
+ expect(Lalabase::Demo).not_to be_marked
+ end
+ end
+end
diff --git a/spec/requests/demo_mode_spec.rb b/spec/requests/demo_mode_spec.rb
index 37e0f3b..e5a9590 100644
--- a/spec/requests/demo_mode_spec.rb
+++ b/spec/requests/demo_mode_spec.rb
@@ -53,7 +53,9 @@ RSpec.describe 'Demo mode', :ci_guard, type: :request do
follow_redirect!
expect(response).to have_http_status(:ok)
- expect(response.body).to include('data-testid="demo-banner"')
+ banner = Nokogiri::HTML(response.body).at_css('[data-testid="demo-banner"]')
+ expect(banner.text).to include("#{Lalabase::Demo.reset_time} UTC")
+ expect(Lalabase::Demo.reset_time).to match(/\A\d{2}:00\z/)
end
context 'without the flag' do
@@ -172,6 +174,206 @@ RSpec.describe 'Demo mode', :ci_guard, type: :request do
end
end
+ describe 'uploads' do
+ let(:limit) { Lalabase::Demo::MAX_UPLOAD_BYTES }
+
+ def post_blob(byte_size: 5, content_type: 'image/png')
+ blob = { filename: 'shot', byte_size: byte_size, checksum: 'XUFAKrxLKna5cZ2REBfFkg==', content_type: content_type }
+ post rails_direct_uploads_path, params: { blob: blob }.to_json,
+ headers: { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }
+ end
+
+ def post_body(bytes)
+ post user_session_path, params: 'x' * bytes, headers: { 'Content-Type' => 'application/octet-stream' }
+ end
+
+ before { sign_in demo_user }
+
+ it 'takes an image or a PDF up to the limit' do
+ post_blob(byte_size: limit)
+ expect(response).to have_http_status(:ok)
+ post_blob(content_type: 'application/pdf')
+ expect(response).to have_http_status(:ok)
+ end
+
+ # SVG is an image that runs script.
+ it 'refuses a larger file and any other type before the blob exists' do
+ Prosopite.pause do
+ expect do
+ post_blob(byte_size: limit + 1)
+ expect(response).to have_http_status(:unprocessable_content)
+ %w[text/html image/svg+xml].each do |type|
+ post_blob(content_type: type)
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end.not_to change(ActiveStorage::Blob, :count)
+ end
+ end
+
+ # The forms that post a file themselves, and the byte channel of direct uploads.
+ it 'refuses any request body above the limit, and only above it' do
+ post_body(limit)
+ expect(response).not_to have_http_status(:content_too_large)
+ post_body(limit + 1)
+ expect(response).to have_http_status(:content_too_large)
+ end
+
+ # Rack::MethodOverride parses a form body before any controller could refuse it.
+ it 'refuses the body before anything parses it' do
+ expect(Rails.application.middleware.first.klass).to eq(Lalabase::Demo::UploadLimit)
+ end
+
+ describe 'once the stored files reach the budget' do
+ let(:file_size) { Lalabase::Demo::LARGE_BODY_BYTES + 1 }
+
+ before do
+ stub_const('Lalabase::Demo::STORAGE_BUDGET_BYTES', file_size)
+ ActiveStorage::Blob.create_and_upload!(io: StringIO.new('x' * file_size), filename: 'earlier.png')
+ end
+
+ it 'takes no further file, by either way' do
+ post_blob(byte_size: 1)
+ expect(response).to have_http_status(:unprocessable_content)
+ post_body(file_size)
+ expect(response).to have_http_status(:content_too_large)
+ end
+
+ it 'still takes a form or a message' do
+ post_body(Lalabase::Demo::LARGE_BODY_BYTES)
+ expect(response).not_to have_http_status(:content_too_large)
+ end
+ end
+
+ context 'without the flag' do
+ let(:demo_on) { false }
+
+ it 'takes what any instance takes' do
+ post_blob(byte_size: limit + 1, content_type: 'text/html')
+ expect(response).to have_http_status(:ok)
+ post_body(limit + 1)
+ expect(response).not_to have_http_status(:content_too_large)
+ end
+ end
+ end
+
+ describe 'the per-address throttles' do
+ around do |example|
+ enabled_was = Rack::Attack.enabled
+ store_was = Rack::Attack.cache.store
+ Rack::Attack.enabled = true
+ Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
+ travel_to(Time.current) { example.run }
+ Rack::Attack.cache.store = store_was
+ Rack::Attack.enabled = enabled_was
+ end
+
+ # Many requests to one handler; the repeated queries are not a page's N+1.
+ def from(ip, path, count = 1, method: :post, params: nil)
+ Prosopite.pause { count.times { send(method, path, params: params, headers: { 'REMOTE_ADDR' => ip }) } }
+ end
+
+ def throttled? = response.status == 429
+
+ # One daily quota for every visitor: one of them must not spend it alone.
+ describe 'on what calls a model' do
+ let(:limit) { Rack::Attack::DEMO_MODEL_CALL_LIMIT }
+ let(:org) { "/org/#{SecureRandom.uuid}" }
+ let(:project) { "#{org}/projects/#{SecureRandom.uuid}" }
+ let(:model_calls) do
+ ["#{org}/assistant_chats", "#{org}/assistant_chats/c1/chatposts", "#{org}/assistant_chats/c1/chatposts/p1/regenerate",
+ "#{org}/assistant_chats/c1/chatposts/p1/analysis", "#{org}/assistant_chats/c1/ticket_suggestion_runs/r1/retry",
+ "#{project}/tickets/t1/create_summary", "#{project}/tickets/bulk_summary", "#{project}/meetings/m1/create_summary",
+ "#{project}/meetings/m1/analyses", "#{project}/meetings/m1/ticket_suggestions/run",
+ "#{project}/meetings/detect_participants", "#{org}/time_session_groups/g1/generate_customer_descriptions"]
+ end
+
+ it 'counts every one of them, per address' do
+ model_calls.each do |path|
+ Rack::Attack.cache.store.clear
+ from('10.0.2.1', path, limit)
+ expect(throttled?).to be(false), path
+ from('10.0.2.1', path)
+ expect(throttled?).to be(true), path
+ from('10.0.2.2', path)
+ expect(throttled?).to be(false), path
+ end
+ end
+
+ it 'counts an analysis changed and a comment that asks the AI' do
+ from('10.0.2.1', "#{project}/meetings/m1/analyses/a1", 5, method: :patch)
+ from('10.0.2.1', "#{project}/tickets/t1/posts", 5, params: { ask_ai: '1' })
+ expect(throttled?).to be(false)
+ from('10.0.2.1', "#{org}/assistant_chats.json")
+ expect(throttled?).to be(true)
+ end
+
+ # rack-test tidies a padded path before the request is made, so the padding is
+ # handed to the rule as Rack would hand it.
+ it 'counts a padded path like the plain one' do
+ padded = Rack::Attack::Request.new(Rack::MockRequest.env_for('/', method: 'POST'))
+ padded.path_info = "/#{org}//assistant_chats/c1/chatposts/"
+ expect(Rack::Attack.demo_model_call?(padded)).to be(true)
+ end
+
+ it 'does not count what asks no model' do
+ [["#{org}/assistant_chats/c1/references", {}], ["#{project}/tickets/t1/posts", { params: { content: 'hi' } }],
+ ["#{org}/assistant_chats/c1", { method: :get }]].each do |path, options|
+ Rack::Attack.cache.store.clear
+ from('10.0.2.1', path, limit + 1, **options)
+ expect(throttled?).to be(false), path
+ end
+ end
+
+ # Everybody in the demo is the same user: a bucket per user would be one for all.
+ it 'counts signed-in visitors by their address, not by the shared user' do
+ sign_in demo_user
+ from('10.0.2.1', "#{org}/assistant_chats/c1/chatposts", limit)
+ from('10.0.2.2', "#{org}/assistant_chats/c1/chatposts")
+ expect(throttled?).to be(false)
+ end
+
+ context 'without the flag' do
+ let(:demo_on) { false }
+
+ it 'counts nothing' do
+ from('10.0.2.1', "#{org}/assistant_chats", limit + 1)
+ expect(throttled?).to be(false)
+ end
+ end
+ end
+
+ describe 'on files' do
+ let(:limit) { Rack::Attack::DEMO_UPLOAD_LIMIT }
+ let(:file) { 'x' * (Lalabase::Demo::LARGE_BODY_BYTES + 1) }
+
+ # A path no other throttle counts.
+ let(:documents) { "/org/#{SecureRandom.uuid}/projects/#{SecureRandom.uuid}/documents" }
+
+ it 'counts every body that carries a file, per address' do
+ from('10.0.3.1', documents, limit, params: file)
+ expect(throttled?).to be(false)
+ from('10.0.3.1', documents, params: file)
+ expect(throttled?).to be(true)
+ from('10.0.3.2', documents, params: file)
+ expect(throttled?).to be(false)
+ end
+
+ it 'does not count a form or a message' do
+ from('10.0.3.1', documents, limit + 1, params: 'x' * Lalabase::Demo::LARGE_BODY_BYTES)
+ expect(throttled?).to be(false)
+ end
+
+ context 'without the flag' do
+ let(:demo_on) { false }
+
+ it 'counts nothing' do
+ from('10.0.3.1', documents, limit + 1, params: file)
+ expect(throttled?).to be(false)
+ end
+ end
+ end
+ end
+
# One request per kind of restriction (DemoRestrictions::BLOCKED); the guard in
# spec/architecture/demo_restrictions_guard_spec.rb covers the rest of the list.
describe 'what a visitor cannot do' do