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 a demo mode behind LALABASE_DEMO

Guido Boyke424a41ffe153
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.yml
index c93f0e2..285d7f1 100644
--- a/.github/workflows/guards.yml
+++ b/.github/workflows/guards.yml
@@ -425,6 +425,7 @@ jobs:
spec/requests/organisations/time_sessions_subject_popover_edit_spec.rb
spec/requests/ticket_time_columns_spec.rb
spec/requests/auth_throttle_spec.rb
+ spec/requests/demo_mode_spec.rb
spec/requests/legal_identity_spec.rb
spec/requests/admin/system_settings_legal_identity_spec.rb
spec/requests/organisations/accept_invitations_consent_spec.rb
diff --git a/app/assets/stylesheets/auth.css b/app/assets/stylesheets/auth.css
index 525ca95..c9da44f 100644
--- a/app/assets/stylesheets/auth.css
+++ b/app/assets/stylesheets/auth.css
@@ -372,3 +372,16 @@
.lp-auth-legal { justify-content: center; }
}
+
+/* Demo mode: the published login on the sign-in page (devise/sessions/_demo_login) */
+.lp-demo-login {
+ margin: 0;
+ display: grid;
+ grid-template-columns: max-content 1fr;
+ gap: 4px 14px;
+ font-size: 14px;
+}
+
+.lp-demo-login dt { color: var(--lp-text-3); }
+.lp-demo-login dd { margin: 0; font-family: 'JetBrains Mono', monospace; overflow-wrap: anywhere; }
+.lp-auth-notice .lp-btn { align-self: flex-start; }
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index 16c205c..7ac70b7 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -80,6 +80,8 @@ class ApplicationController < ActionController::Base
# AFTER the callbacks above so it never runs ahead of the tenant/locale setup
# for a signed-in request -- it skips those entirely anyway.
include AcquisitionTracking
+ # After switch_locale, so the refusal speaks the visitor's language.
+ include DemoRestrictions
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
diff --git a/app/controllers/concerns/demo_restrictions.rb b/app/controllers/concerns/demo_restrictions.rb
new file mode 100644
index 0000000..df0d766
--- /dev/null
+++ b/app/controllers/concerns/demo_restrictions.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+# What a visitor of the public demo (Lalabase::Demo) cannot do. Everybody signs in
+# to the same account, so whatever is stored on the person is stored for every
+# visitor at once, and whatever leaves the instance leaves with its name on it.
+#
+# A closed list of controller actions, inactive unless demo mode is on. Each
+# entry says why. spec/architecture/demo_restrictions_guard_spec.rb holds that
+# every entry names a routed action of a controller that runs this check; a new
+# entry is a decision, not a convenience.
+#
+# Not here, because a policy already says no to the demo person (team role, no
+# account admin): organisation settings, roles, AI settings and packages,
+# billing. Mail needs no entry either: Lalabase::Demo::MailDrop drops all of it.
+module DemoRestrictions
+ extend ActiveSupport::Concern
+
+ ALL = :all
+
+ BLOCKED = {
+ # Sign-up (no accounts outside the demo), email and password change (one
+ # visitor would lock out the rest), deleting the account. `edit` shows the
+ # page; nothing on it can be saved.
+ 'users/registrations' => %w[new create update destroy cancel],
+ # The reset link goes out by mail; the page would promise one that never comes.
+ 'users/passwords' => ALL,
+ 'account_deletions' => ALL,
+ 'cancel_account_deletions' => ALL,
+ # Scripted access (API, MCP) to an account that belongs to everybody.
+ 'users/personal_access_tokens' => ALL,
+ # Language, session timeout, date format: stored on the shared person.
+ 'user_preferences' => %w[update],
+ 'user_data_exports' => ALL,
+ # The demo stays one world.
+ 'organisations' => %w[new create],
+ 'organisations/invitations' => ALL,
+ # Each of these makes the instance fetch from an address a visitor types.
+ 'organisations/project_repositories' => %w[new create update_token reindex],
+ 'organisations/documentation_sets' => %w[new create edit update sync],
+ 'organisations/codebase_import_files' => ALL
+ }.freeze
+
+ included do
+ before_action :refuse_in_demo, if: -> { Lalabase::Demo.enabled? }
+ end
+
+ def self.blocked?(controller_path, action)
+ actions = BLOCKED[controller_path]
+ actions == ALL || Array(actions).include?(action.to_s)
+ end
+
+ private
+
+ def refuse_in_demo
+ return unless DemoRestrictions.blocked?(controller_path, action_name)
+
+ message = t('views.demo.blocked')
+ return render(json: { error: message }, status: :forbidden) if request.format.json?
+
+ redirect_back_or_to(user_signed_in? ? user_home_path(current_user) : new_user_session_path,
+ alert: message, status: :see_other)
+ end
+end
diff --git a/app/javascript/controllers/demo_login_controller.js b/app/javascript/controllers/demo_login_controller.js
new file mode 100644
index 0000000..178153b
--- /dev/null
+++ b/app/javascript/controllers/demo_login_controller.js
@@ -0,0 +1,15 @@
+import { Controller } from "@hotwired/stimulus"
+
+// Demo mode: puts the published login into the sign-in form around it
+// (devise/sessions/_demo_login). The values come from the server; nothing is
+// submitted here, the visitor still presses "Sign in".
+export default class extends Controller {
+ static values = { email: String, password: String }
+
+ fill() {
+ const form = this.element.closest("form")
+ form.elements["user[email]"].value = this.emailValue
+ form.elements["user[password]"].value = this.passwordValue
+ form.querySelector('[type="submit"]').focus()
+ }
+}
diff --git a/app/models/user.rb b/app/models/user.rb
index d57edce..ec9bab0 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -148,6 +148,14 @@ class User < ApplicationRecord
session_timeout_minutes.minutes
end
+ # The published login of the demo (Lalabase::Demo) is shared by every visitor,
+ # so counting failed attempts would let anybody lock it for everybody. Defined
+ # here for the same ancestor reason as timeout_in: `devise :lockable` lands
+ # above the concerns.
+ def lock_strategy_enabled?(strategy)
+ super && !Lalabase::Demo.published_login?(email)
+ end
+
# confirmation_period_valid? lives here for the SAME ancestor reason as
# timeout_in above: `devise :confirmable` mixes Devise::Models::Confirmable
# into User from inside User::Authenticatable's `included do`, so it lands
diff --git a/app/views/devise/sessions/_demo_login.html.erb b/app/views/devise/sessions/_demo_login.html.erb
new file mode 100644
index 0000000..0edc815
--- /dev/null
+++ b/app/views/devise/sessions/_demo_login.html.erb
@@ -0,0 +1,18 @@
+<%# Demo mode (Lalabase::Demo): the published login, and a button that puts it
+ into the fields below. The normal sign-in does the rest. Inside the form, so
+ the button finds its fields without an id. %>
+<div class="lp-auth-notice" data-testid="demo-login"
+ data-controller="demo-login"
+ data-demo-login-email-value="<%= Lalabase::Demo.login_email %>"
+ data-demo-login-password-value="<%= Lalabase::Demo::PASSWORD %>">
+ <p class="lp-auth-notice-lead"><%= t('views.demo.sign_in.lead', name: Lalabase::Demo.login_name) %></p>
+ <dl class="lp-demo-login">
+ <dt><%= t('views.demo.sign_in.email') %></dt>
+ <dd><%= Lalabase::Demo.login_email %></dd>
+ <dt><%= t('views.demo.sign_in.password') %></dt>
+ <dd><%= Lalabase::Demo::PASSWORD %></dd>
+ </dl>
+ <button type="button" class="lp-btn lp-btn--ghost" data-action="demo-login#fill">
+ <%= t('views.demo.sign_in.fill') %>
+ </button>
+</div>
diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb
index fd9b8d1..ea311e7 100644
--- a/app/views/devise/sessions/new.html.erb
+++ b/app/views/devise/sessions/new.html.erb
@@ -12,11 +12,14 @@
is DELIBERATELY not implemented: it is marked there as an optional
suggestion, not an existing feature; with it the OR divider goes away too. %>
-<% content_for :auth_cross do %>
- <p class="lp-auth-cross">
- <%= t('.no_account') %>
- <%= link_to t('.register'), new_registration_path(resource_name), class: 'lp-auth-cross-link' %>
- </p>
+<%# The demo has no sign-up: everybody uses the login shown in the form. %>
+<% unless Lalabase::Demo.enabled? %>
+ <% content_for :auth_cross do %>
+ <p class="lp-auth-cross">
+ <%= t('.no_account') %>
+ <%= link_to t('.register'), new_registration_path(resource_name), class: 'lp-auth-cross-link' %>
+ </p>
+ <% end %>
<% end %>
<div class="lp-eyebrow"><%= t('.eyebrow') %></div>
@@ -24,6 +27,8 @@
<%= form_for(resource, as: resource_name, url: session_path(resource_name),
html: { class: 'lp-auth-form', novalidate: true }) do |f| %>
+ <%= render 'devise/sessions/demo_login' if Lalabase::Demo.enabled? %>
+
<div class="lp-field">
<label for="user_email" class="lp-field-label"><%= t('.email_label') %></label>
<%= f.email_field :email,
diff --git a/app/views/layouts/_demo_banner.html.erb b/app/views/layouts/_demo_banner.html.erb
new file mode 100644
index 0000000..8324024
--- /dev/null
+++ b/app/views/layouts/_demo_banner.html.erb
@@ -0,0 +1,12 @@
+<%# Demo mode (Lalabase::Demo): every visitor shares this account. Shaped like
+ layouts/_email_confirmation and rendered in the same place, in the flow. Not
+ dismissible: it is the one place that says why things change on their own. %>
+<div class="bg-sky-200 text-black border-2 border-black" data-testid="demo-banner">
+ <div class="px-4 py-3 flex items-center gap-3 text-sm">
+ <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>
+ </p>
+ </div>
+</div>
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index a6ed455..17cc872 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -259,6 +259,7 @@
confirmation deadline only ends access. %>
<%= render 'layouts/deletion_warning' if user_signed_in? && current_user.deletion_scheduled? %>
<%= render 'layouts/email_confirmation' if user_signed_in? && current_user.awaiting_confirmation? && !current_user.deletion_scheduled? %>
+ <%= render 'layouts/demo_banner' if user_signed_in? && Lalabase::Demo.enabled? %>
<%# Mount notification dropdown in test env so system specs can interact with it %>
<% if Rails.env.test? && user_signed_in? && @current_organisation.present? %>
diff --git a/config/importmap.rb b/config/importmap.rb
index f77589f..d2aabd4 100644
--- a/config/importmap.rb
+++ b/config/importmap.rb
@@ -152,6 +152,7 @@ else
pin 'controllers/custom_period_controller', to: 'controllers/custom_period_controller.js'
pin 'controllers/customer_description_edit_controller', to: 'controllers/customer_description_edit_controller.js'
pin 'controllers/dashboard_inline_edit_controller', to: 'controllers/dashboard_inline_edit_controller.js'
+ pin 'controllers/demo_login_controller', to: 'controllers/demo_login_controller.js'
pin 'controllers/detail_settings_modal_controller', to: 'controllers/detail_settings_modal_controller.js'
pin 'controllers/details_autoclose_controller', to: 'controllers/details_autoclose_controller.js'
pin 'controllers/dropdown_controller', to: 'controllers/dropdown_controller.js'
diff --git a/config/initializers/demo.rb b/config/initializers/demo.rb
new file mode 100644
index 0000000..ccbb2cd
--- /dev/null
+++ b/config/initializers/demo.rb
@@ -0,0 +1,12 @@
+# 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
+# delivers and answers as before.
+#
+# Explicit require: initializers run before the autoloader serves lib/ (same as
+# operator_console.rb).
+require 'lalabase/demo'
+
+Rails.application.config.middleware.use Lalabase::Demo::NoIndex
+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 db86b2e..ffb7437 100644
--- a/config/initializers/rack_attack.rb
+++ b/config/initializers/rack_attack.rb
@@ -86,8 +86,12 @@ class Rack::Attack
end
### Throttle login attempts per email ###
+ # The published login of the demo (Lalabase::Demo) is exempt: every visitor
+ # signs in with that one address, and five of them a minute would lock out the
+ # sixth. logins/ip still counts each of them.
throttle('logins/email', limit: 5, period: 60.seconds) do |req|
- login_email(req) if post_to?(req, SIGN_IN_PATH)
+ email = login_email(req) if post_to?(req, SIGN_IN_PATH)
+ email unless Lalabase::Demo.published_login?(email)
end
### Throttle the one-time signup link per IP ###
diff --git a/config/locales/views/demo.de.yml b/config/locales/views/demo.de.yml
new file mode 100644
index 0000000..dd32106
--- /dev/null
+++ b/config/locales/views/demo.de.yml
@@ -0,0 +1,12 @@
+de:
+ views:
+ demo:
+ 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."
+ sign_in:
+ lead: "Probier die Demo aus: Melde dich als %{name} an, Projektleitung bei einer erfundenen Softwarefirma."
+ email: "E-Mail"
+ password: "Passwort"
+ fill: "Eintragen"
diff --git a/config/locales/views/demo.en.yml b/config/locales/views/demo.en.yml
new file mode 100644
index 0000000..da2e72a
--- /dev/null
+++ b/config/locales/views/demo.en.yml
@@ -0,0 +1,12 @@
+en:
+ views:
+ demo:
+ 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."
+ sign_in:
+ lead: "Try the demo: sign in as %{name}, project lead at an invented software company."
+ email: "Email"
+ password: "Password"
+ fill: "Fill in"
diff --git a/lib/lalabase/demo.rb b/lib/lalabase/demo.rb
new file mode 100644
index 0000000..af7fe5e
--- /dev/null
+++ b/lib/lalabase/demo.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+module Lalabase
+ # Demo mode: a public instance that anybody enters with one published login,
+ # the signed-in person of the Nordlicht fiction (Lalabase::Demo::World).
+ #
+ # 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.
+ #
+ # 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
+ # account must not reach outside the instance (mail, tokens, repositories).
+ #
+ # Explicit require in config/initializers/demo.rb: the interceptor is
+ # registered before the autoloader serves lib/.
+ module Demo
+ ENV_FLAG = 'LALABASE_DEMO'
+ # The only value that switches it on (same rule as Lalabase::OperatorConsole).
+ ENABLED_VALUE = '1'
+ # Shown on the sign-in page of the demo, so it is no secret. Only the
+ # 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'
+
+ class << self
+ def enabled?(env = ENV)
+ env[ENV_FLAG].to_s.strip == ENABLED_VALUE
+ end
+
+ def login_email = Fiction.email(Fiction::SIGNED_IN)
+ def login_name = Fiction.full_name(Fiction::SIGNED_IN)
+
+ def published_login?(email)
+ enabled? && email.is_a?(String) && email.strip.casecmp?(login_email)
+ end
+ end
+
+ # Drops every outgoing mail while demo mode is on. An invitation or a
+ # notification would otherwise go out with this instance as its sender, to
+ # any address a visitor types. Registered on every instance and asked per
+ # mail, so the flag decides it, not the boot.
+ module MailDrop
+ def self.delivering_email(message)
+ message.perform_deliveries = false if Demo.enabled?
+ 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.
+ class NoIndex
+ HEADER = 'x-robots-tag'
+ VALUE = 'noindex, nofollow'
+
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ status, headers, body = @app.call(env)
+ headers[HEADER] = VALUE if Demo.enabled?
+ [status, headers, body]
+ end
+ end
+ end
+end
diff --git a/lib/lalabase/demo/world.rb b/lib/lalabase/demo/world.rb
index 92cd125..69ec946 100644
--- a/lib/lalabase/demo/world.rb
+++ b/lib/lalabase/demo/world.rb
@@ -20,7 +20,9 @@ module Lalabase
# `now` is the moment the world is seen from (frozen for the screenshots, the time
# of the reset for the demo). `organisation` takes extra attributes for the
# organisation, such as the AI switches. `embeddings` marks notes, comments and
- # meetings for the assistant's search.
+ # meetings for the assistant's search. `password` is the signed-in person's
+ # (the demo publishes it); everybody else gets a random one of their own, so
+ # nobody signs in as the account admin with it.
class World
ORGANISATION_NAME = 'Nordlicht Software GmbH'
@@ -31,7 +33,7 @@ module Lalabase
@now = now
@organisation_attributes = organisation
@embeddings = embeddings
- @password = password || SecureRandom.base58(24)
+ @password = password || random_password
@people = {}
@projects = {}
@tickets = []
@@ -81,8 +83,9 @@ module Lalabase
# Confirmed right away: there is no inbox behind nordlicht.example.
def add_user(key)
+ password = key == Fiction::SIGNED_IN ? @password : random_password
User.create!(**Fiction::PEOPLE.fetch(key), email: Fiction.email(key),
- password: @password, password_confirmation: @password,
+ password: password, password_confirmation: password,
language_preference: @locale.to_s, terms_accepted_at: @now,
&:skip_confirmation!)
end
@@ -204,6 +207,8 @@ module Lalabase
@chat.chatposts.update_all(created_at: @now - 20.minutes)
end
+ def random_password = SecureRandom.base58(24)
+
def dated(text) = Fiction.dated(text, @locale, @now)
def backdate(record, at)
diff --git a/spec/architecture/demo_restrictions_guard_spec.rb b/spec/architecture/demo_restrictions_guard_spec.rb
new file mode 100644
index 0000000..5839ac5
--- /dev/null
+++ b/spec/architecture/demo_restrictions_guard_spec.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# The list of what the public demo refuses (DemoRestrictions::BLOCKED) is only
+# worth something while each entry still reaches a request. A renamed controller,
+# a removed action, or a controller that stops inheriting the check would leave
+# an entry that blocks nothing and reads as if it did.
+RSpec.describe DemoRestrictions, :ci_guard, type: :model do
+ let(:routed) do
+ # Routes load lazily in test.
+ Rails.application.reload_routes_unless_loaded
+ Rails.application.routes.routes.filter_map do |route|
+ controller, action = route.defaults.values_at(:controller, :action)
+ [controller, action] if controller && action
+ end
+ end
+
+ described_class::BLOCKED.each do |controller_path, actions|
+ describe controller_path do
+ let(:controller_class) { "#{controller_path.camelize}Controller".constantize }
+ let(:routed_actions) { routed.select { _1.first == controller_path }.map(&:last).uniq }
+
+ it 'names a routed action for every entry' do
+ expect(routed_actions).not_to be_empty
+ expect(routed_actions).to include(*actions) unless actions == described_class::ALL
+ end
+
+ it 'runs the check' do
+ expect(controller_class.ancestors).to include(described_class)
+ expect(controller_class._process_action_callbacks.map(&:filter)).to include(:refuse_in_demo)
+ end
+ end
+ end
+
+ # A skip limited to some actions would leave the callback in the chain above and
+ # still turn an entry off. No controller skips it at all. A tripwire: it reads
+ # the source.
+ it 'is skipped nowhere' do
+ sources = Rails.root.glob('{app,lib}/**/*.rb').map(&:read)
+ expect(sources.grep(/skip_(before_)?action\s*:refuse_in_demo/)).to be_empty
+ end
+
+ it 'answers per action' do
+ expect(described_class.blocked?('users/registrations', 'update')).to be(true)
+ expect(described_class.blocked?('users/registrations', 'edit')).to be(false)
+ expect(described_class.blocked?('users/personal_access_tokens', 'index')).to be(true)
+ expect(described_class.blocked?('organisations/tickets', 'create')).to be(false)
+ end
+end
diff --git a/spec/lib/lalabase/demo/world_spec.rb b/spec/lib/lalabase/demo/world_spec.rb
index 6a3cf5b..352eb20 100644
--- a/spec/lib/lalabase/demo/world_spec.rb
+++ b/spec/lib/lalabase/demo/world_spec.rb
@@ -53,11 +53,13 @@ RSpec.describe Lalabase::Demo::World do
.to eq(:own)
end
- it 'lets every person sign in with the given password, confirmed' do
- organisation.users.each do |user|
- expect(user.valid_password?(password)).to be(true)
- expect(user).to be_confirmed
- end
+ # The demo publishes the password. With it on the owner, a visitor would sign
+ # in as the account admin.
+ it 'gives the password to the signed-in person only, and confirms everybody' do
+ expect(world.signed_in.valid_password?(password)).to be(true)
+ others = organisation.users.where.not(id: world.signed_in.id)
+ expect(others.map { _1.valid_password?(password) }).to all(be(false))
+ expect(organisation.users).to all(be_confirmed)
end
it 'adds one meeting with its summary and one waiting for it, with guests among the participants' do
diff --git a/spec/requests/demo_mode_spec.rb b/spec/requests/demo_mode_spec.rb
new file mode 100644
index 0000000..37e0f3b
--- /dev/null
+++ b/spec/requests/demo_mode_spec.rb
@@ -0,0 +1,245 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# The public demo (Lalabase::Demo): one published login that every visitor shares.
+# Each part is pinned twice, with the flag (what the demo needs) and without it
+# (an instance that never set LALABASE_DEMO behaves as before).
+RSpec.describe 'Demo mode', :ci_guard, type: :request do
+ include ActiveSupport::Testing::TimeHelpers
+
+ let(:organisation) { create(:organisation) }
+ let(:role) { create(:role, organisation: organisation) }
+ # English, like the demo world: the refusal below is read in that language.
+ let(:demo_user) do
+ member(email: Lalabase::Demo.login_email, password: Lalabase::Demo::PASSWORD, language_preference: 'en')
+ end
+ 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
+
+ def member(**attributes)
+ user = create(:user, **attributes)
+ ActsAsTenant.with_tenant(organisation) do
+ create(:membership, user: user, organisation: organisation, role: role, active: true)
+ end
+ user
+ end
+
+ def sign_in_with(email, password, session: self)
+ session.post user_session_path, params: { user: { email: email, password: password } }
+ end
+
+ describe 'the sign-in page' do
+ it 'shows the published login and no way to sign up' do
+ get new_user_session_path
+
+ demo = Nokogiri::HTML(response.body).at_css('form [data-testid="demo-login"]')
+ expect(demo).to be_present
+ expect(demo.text).to include(Lalabase::Demo.login_email, Lalabase::Demo::PASSWORD)
+ expect(demo['data-demo-login-password-value']).to eq(Lalabase::Demo::PASSWORD)
+ expect(response.body).not_to include(new_user_registration_path)
+ end
+
+ it 'lets a visitor in with it' do
+ demo_user
+ sign_in_with(Lalabase::Demo.login_email, Lalabase::Demo::PASSWORD)
+ follow_redirect!
+
+ expect(response).to have_http_status(:ok)
+ expect(response.body).to include('data-testid="demo-banner"')
+ end
+
+ context 'without the flag' do
+ let(:demo_on) { false }
+
+ it 'shows neither the login nor the banner' do
+ get new_user_session_path
+ expect(response.body).not_to include('data-testid="demo-login"')
+ expect(response.body).to include(new_user_registration_path)
+
+ sign_in demo_user
+ get organisation_root_path(organisation)
+ expect(response).to have_http_status(:ok)
+ expect(response.body).not_to include('data-testid="demo-banner"')
+ end
+ end
+ end
+
+ describe 'search engines' do
+ it 'are told not to index any response' do
+ get new_user_session_path
+ expect(response.headers['x-robots-tag']).to eq('noindex, nofollow')
+ end
+
+ context 'without the flag' do
+ let(:demo_on) { false }
+
+ it 'are told nothing' do
+ get new_user_session_path
+ expect(response.headers['x-robots-tag']).to be_nil
+ end
+ end
+ end
+
+ # One account for everybody: Devise's lockout and the per-address throttle
+ # would let any visitor shut out all the others.
+ describe 'the shared login' do
+ let(:too_many) { Devise.maximum_attempts + 5 }
+
+ it 'is never locked by failed attempts' do
+ demo_user
+ Prosopite.pause { too_many.times { sign_in_with(Lalabase::Demo.login_email, 'wrong-password-123') } }
+
+ expect(demo_user.reload).not_to be_access_locked
+ sign_in_with(Lalabase::Demo.login_email, Lalabase::Demo::PASSWORD)
+ expect(response).to redirect_to(organisation_root_path(organisation))
+ end
+
+ it 'leaves the lockout of every other address as it is' do
+ other = member(email: '[email protected]')
+ Prosopite.pause { too_many.times { sign_in_with(other.email, 'wrong-password-123') } }
+
+ expect(other.reload).to be_access_locked
+ end
+
+ it 'stays signed in for one visitor while another signs in and out' do
+ demo_user
+ first = open_session
+ second = open_session
+ sign_in_with(Lalabase::Demo.login_email, Lalabase::Demo::PASSWORD, session: first)
+ sign_in_with(Lalabase::Demo.login_email, Lalabase::Demo::PASSWORD, session: second)
+ second.delete destroy_user_session_path
+
+ first.get organisation_root_path(organisation)
+ expect(first.response).to have_http_status(:ok)
+ second.get organisation_root_path(organisation)
+ expect(second.response.location).to eq(new_user_session_url)
+ end
+
+ describe 'per-address throttle' 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
+ # One throttle bucket for the whole loop (see auth_throttle_spec.rb).
+ travel_to(Time.current) { example.run }
+ Prosopite.resume
+ Rack::Attack.cache.store = store_was
+ Rack::Attack.enabled = enabled_was
+ end
+
+ def attempts_from_many_addresses(email, count)
+ Prosopite.pause
+ count.times do |i|
+ post user_session_path, params: { user: { email: email, password: 'wrong-password-123' } },
+ headers: { 'REMOTE_ADDR' => "10.0.1.#{i + 1}" }
+ end
+ end
+
+ it 'does not count the published address' do
+ attempts_from_many_addresses(Lalabase::Demo.login_email.upcase, 10)
+ expect(response).not_to have_http_status(:too_many_requests)
+ end
+
+ it 'still counts every other address' do
+ attempts_from_many_addresses('[email protected]', 6)
+ expect(response).to have_http_status(:too_many_requests)
+ end
+ end
+ end
+
+ describe 'mail' do
+ it 'goes nowhere' do
+ with_delivered_mails { Devise::Mailer.reset_password_instructions(demo_user, 'token').deliver_later }
+ expect(ActionMailer::Base.deliveries).to be_empty
+ end
+
+ context 'without the flag' do
+ let(:demo_on) { false }
+
+ it 'is delivered' do
+ with_delivered_mails { Devise::Mailer.reset_password_instructions(demo_user, 'token').deliver_later }
+ expect(ActionMailer::Base.deliveries.size).to eq(1)
+ 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
+ let(:blocked) { I18n.t('views.demo.blocked', locale: :en) }
+
+ before do
+ sign_in demo_user
+ ActsAsTenant.current_tenant = organisation
+ end
+
+ def expect_refused
+ expect(response).to have_http_status(:see_other)
+ expect(flash[:alert]).to eq(blocked)
+ end
+
+ it 'cannot change the email address or the password' do
+ patch user_registration_path, params: { user: { email: '[email protected]', password: 'another-password-1',
+ password_confirmation: 'another-password-1',
+ current_password: Lalabase::Demo::PASSWORD } }
+ expect_refused
+ expect(demo_user.reload.email).to eq(Lalabase::Demo.login_email)
+ expect(demo_user.valid_password?(Lalabase::Demo::PASSWORD)).to be(true)
+ end
+
+ it 'cannot create an access token' do
+ expect do
+ post users_personal_access_tokens_path, params: { current_password: Lalabase::Demo::PASSWORD,
+ personal_access_token: { name: 'Script', expires_preset: '30' } }
+ end.not_to change(PersonalAccessToken, :count)
+ expect_refused
+ end
+
+ it 'cannot change the preferences stored on the shared person' do
+ patch user_preferences_path, params: { current_section: 'language', user: { language_preference: 'de' } }
+ expect_refused
+ expect(demo_user.reload.language_preference).to eq('en')
+ end
+
+ it 'cannot invite anybody' do
+ expect do
+ post organisation_invitations_path(organisation), params: { invitation: { email: '[email protected]' } }
+ end.not_to change(Invitation, :count)
+ expect_refused
+ end
+
+ it 'cannot create an organisation' do
+ expect { post create_organisation_path, params: { organisation: { name: 'Mine' } } }
+ .not_to change(Organisation, :count)
+ expect_refused
+ end
+
+ it 'answers a JSON request with 403' do
+ post users_personal_access_tokens_path(format: :json)
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it 'can still read the account page' do
+ get edit_user_registration_path
+ expect(response).to have_http_status(:ok)
+ end
+
+ context 'without the flag' do
+ let(:demo_on) { false }
+
+ it 'is not refused' do
+ get new_users_personal_access_token_path
+ expect(response).to have_http_status(:ok)
+ end
+ end
+ end
+end