diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..0737c6ab6 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,48 @@ +# See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files. + +# Ignore git directory. +/.git/ +/.gitignore + +# Ignore bundler config. +/.bundle + +# Ignore all environment files. +/.env* + +# Ignore all default key files. +/config/master.key +/config/credentials/*.key + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/.keep + +# Ignore assets. +/node_modules/ +/app/assets/builds/* +!/app/assets/builds/.keep +/public/assets + +# Ignore Kamal files. +/config/deploy*.yml +/.kamal + +# Ignore development files +/.devcontainer + +# Ignore Docker-related files +/.dockerignore +/Dockerfile* diff --git a/.env.example b/.env.example new file mode 100644 index 000000000..41b83eae1 --- /dev/null +++ b/.env.example @@ -0,0 +1,16 @@ +DB_HOST=127.0.0.1 +DB_PORT=5432 +DB_USERNAME=postgres +DB_PASSWORD=postgres +SECRET_KEY_BASE= +DOCKER_SUBNET=198.18.113.0/24 +RAILS_MAX_THREADS=5 +APP_HOST=localhost +APP_PROTOCOL=http + +# Optional in production. Without these values, local Docker delivery is +# written to storage/mails instead of contacting an external mail server. +SMTP_ADDRESS= +SMTP_PORT=587 +SMTP_USERNAME= +SMTP_PASSWORD= diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..a0e6dbbf0 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,19 @@ +version: 2 +updates: + - package-ecosystem: bundler + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 5 + + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 5 + + - package-ecosystem: docker + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 5 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..9da0d4f86 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,53 @@ +name: CI + +on: + push: + branches: [master, feature/senior-user-management] + pull_request: + branches: [master] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:17-alpine + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + env: + RAILS_ENV: test + DB_HOST: 127.0.0.1 + DB_USERNAME: postgres + DB_PASSWORD: postgres + steps: + - uses: actions/checkout@v6 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: 4.0.6 + bundler-cache: true + - run: bin/rails db:prepare + - run: bin/ci + + docker: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: docker/setup-buildx-action@v4 + - uses: docker/build-push-action@v7 + with: + context: . + push: false + tags: umanni-users:test + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml deleted file mode 100644 index 4b950cc66..000000000 --- a/.github/workflows/codeql-analysis.yml +++ /dev/null @@ -1,51 +0,0 @@ -name: "Code scanning - action" - -on: - push: - pull_request: - schedule: - - cron: '0 7 * * 0' - -jobs: - CodeQL-Build: - - runs-on: ubuntu-latest - - steps: - - name: Checkout repository - uses: actions/checkout@v2 - with: - # We must fetch at least the immediate parents so that if this is - # a pull request then we can checkout the head. - fetch-depth: 2 - - # If this run was triggered by a pull request event, then checkout - # the head of the pull request instead of the merge commit. - - run: git checkout HEAD^2 - if: ${{ github.event_name == 'pull_request' }} - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v1 - # Override language selection by uncommenting this and choosing your languages - # with: - # languages: go, javascript, csharp, python, cpp, java - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v1 - - # â„šī¸ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl - - # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language - - #- run: | - # make bootstrap - # make release - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 000000000..f02063296 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,24 @@ +name: CodeQL + +on: + push: + branches: [master, feature/senior-user-management] + pull_request: + branches: [master] + schedule: + - cron: "0 7 * * 0" + +permissions: + contents: read + security-events: write + +jobs: + analyze: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: github/codeql-action/init@v4 + with: + languages: ruby + queries: security-extended + - uses: github/codeql-action/analyze@v4 diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..103ce8b06 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +/.bundle +/.env* +!/.env.example +/coverage +/log/* +!/log/.keep +/storage/* +!/storage/.keep +/tmp/* +!/tmp/.keep +!/tmp/pids +/tmp/pids/* +!/tmp/pids/.keep +/tmp/storage/* +!/tmp/storage/.keep +/config/master.key +/config/credentials/*.key +/node_modules +/app/assets/builds/* +!/app/assets/builds/.keep +/public/assets +/.kamal/secrets +/.kamal/hooks/* +!/.kamal/hooks/*.sample +.DS_Store diff --git a/.kamal/hooks/docker-setup.sample b/.kamal/hooks/docker-setup.sample new file mode 100755 index 000000000..a0b053784 --- /dev/null +++ b/.kamal/hooks/docker-setup.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Docker set up on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-app-boot.sample b/.kamal/hooks/post-app-boot.sample new file mode 100755 index 000000000..7d2a13db2 --- /dev/null +++ b/.kamal/hooks/post-app-boot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Booted app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-deploy.sample b/.kamal/hooks/post-deploy.sample new file mode 100755 index 000000000..17b0567a5 --- /dev/null +++ b/.kamal/hooks/post-deploy.sample @@ -0,0 +1,14 @@ +#!/usr/bin/env sh + +# A sample post-deploy hook +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +echo "$KAMAL_PERFORMER deployed $KAMAL_VERSION to $KAMAL_DESTINATION in $KAMAL_RUNTIME seconds" diff --git a/.kamal/hooks/post-proxy-reboot.sample b/.kamal/hooks/post-proxy-reboot.sample new file mode 100755 index 000000000..84548ed04 --- /dev/null +++ b/.kamal/hooks/post-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Rebooted kamal-proxy on $KAMAL_HOSTS" diff --git a/.kamal/hooks/pre-app-boot.sample b/.kamal/hooks/pre-app-boot.sample new file mode 100755 index 000000000..1f9fe844c --- /dev/null +++ b/.kamal/hooks/pre-app-boot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Booting app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/pre-build.sample b/.kamal/hooks/pre-build.sample new file mode 100755 index 000000000..d53d28cf7 --- /dev/null +++ b/.kamal/hooks/pre-build.sample @@ -0,0 +1,51 @@ +#!/usr/bin/env sh + +# A sample pre-build hook +# +# Checks: +# 1. We have a clean checkout +# 2. A remote is configured +# 3. The branch has been pushed to the remote +# 4. The version we are deploying matches the remote +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) + +if [ -n "$(git status --porcelain)" ]; then + echo "Git checkout is not clean, aborting..." >&2 + git status --porcelain >&2 + exit 1 +fi + +first_remote=$(git remote) + +if [ -z "$first_remote" ]; then + echo "No git remote set, aborting..." >&2 + exit 1 +fi + +current_branch=$(git branch --show-current) + +if [ -z "$current_branch" ]; then + echo "Not on a git branch, aborting..." >&2 + exit 1 +fi + +remote_head=$(git ls-remote $first_remote --tags $current_branch | cut -f1) + +if [ -z "$remote_head" ]; then + echo "Branch not pushed to remote, aborting..." >&2 + exit 1 +fi + +if [ "$KAMAL_VERSION" != "$remote_head" ]; then + echo "Version ($KAMAL_VERSION) does not match remote HEAD ($remote_head), aborting..." >&2 + exit 1 +fi + +exit 0 diff --git a/.kamal/hooks/pre-connect.sample b/.kamal/hooks/pre-connect.sample new file mode 100755 index 000000000..77744bdca --- /dev/null +++ b/.kamal/hooks/pre-connect.sample @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby + +# A sample pre-connect check +# +# Warms DNS before connecting to hosts in parallel +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +hosts = ENV["KAMAL_HOSTS"].split(",") +results = nil +max = 3 + +elapsed = Benchmark.realtime do + results = hosts.map do |host| + Thread.new do + tries = 1 + + begin + Socket.getaddrinfo(host, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME) + rescue SocketError + if tries < max + puts "Retrying DNS warmup: #{host}" + tries += 1 + sleep rand + retry + else + puts "DNS warmup failed: #{host}" + host + end + end + + tries + end + end.map(&:value) +end + +retries = results.sum - hosts.size +nopes = results.count { |r| r == max } + +puts "Prewarmed %d DNS lookups in %.2f sec: %d retries, %d failures" % [ hosts.size, elapsed, retries, nopes ] diff --git a/.kamal/hooks/pre-deploy.sample b/.kamal/hooks/pre-deploy.sample new file mode 100755 index 000000000..05b3055b7 --- /dev/null +++ b/.kamal/hooks/pre-deploy.sample @@ -0,0 +1,122 @@ +#!/usr/bin/env ruby + +# A sample pre-deploy hook +# +# Checks the Github status of the build, waiting for a pending build to complete for up to 720 seconds. +# +# Fails unless the combined status is "success" +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_COMMAND +# KAMAL_SUBCOMMAND +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) + +# Only check the build status for production deployments +if ENV["KAMAL_COMMAND"] == "rollback" || ENV["KAMAL_DESTINATION"] != "production" + exit 0 +end + +require "bundler/inline" + +# true = install gems so this is fast on repeat invocations +gemfile(true, quiet: true) do + source "https://rubygems.org" + + gem "octokit" + gem "faraday-retry" +end + +MAX_ATTEMPTS = 72 +ATTEMPTS_GAP = 10 + +def exit_with_error(message) + $stderr.puts message + exit 1 +end + +class GithubStatusChecks + attr_reader :remote_url, :git_sha, :github_client, :combined_status + + def initialize + @remote_url = github_repo_from_remote_url + @git_sha = `git rev-parse HEAD`.strip + @github_client = Octokit::Client.new(access_token: ENV["GITHUB_TOKEN"]) + refresh! + end + + def refresh! + @combined_status = github_client.combined_status(remote_url, git_sha) + end + + def state + combined_status[:state] + end + + def first_status_url + first_status = combined_status[:statuses].find { |status| status[:state] == state } + first_status && first_status[:target_url] + end + + def complete_count + combined_status[:statuses].count { |status| status[:state] != "pending"} + end + + def total_count + combined_status[:statuses].count + end + + def current_status + if total_count > 0 + "Completed #{complete_count}/#{total_count} checks, see #{first_status_url} ..." + else + "Build not started..." + end + end + + private + def github_repo_from_remote_url + url = `git config --get remote.origin.url`.strip.delete_suffix(".git") + if url.start_with?("https://github.com/") + url.delete_prefix("https://github.com/") + elsif url.start_with?("git@github.com:") + url.delete_prefix("git@github.com:") + else + url + end + end +end + + +$stdout.sync = true + +begin + puts "Checking build status..." + + attempts = 0 + checks = GithubStatusChecks.new + + loop do + case checks.state + when "success" + puts "Checks passed, see #{checks.first_status_url}" + exit 0 + when "failure" + exit_with_error "Checks failed, see #{checks.first_status_url}" + when "pending" + attempts += 1 + end + + exit_with_error "Checks are still pending, gave up after #{MAX_ATTEMPTS * ATTEMPTS_GAP} seconds" if attempts == MAX_ATTEMPTS + + puts checks.current_status + sleep(ATTEMPTS_GAP) + checks.refresh! + end +rescue Octokit::NotFound + exit_with_error "Build status could not be found" +end diff --git a/.kamal/hooks/pre-proxy-reboot.sample b/.kamal/hooks/pre-proxy-reboot.sample new file mode 100755 index 000000000..93e11991d --- /dev/null +++ b/.kamal/hooks/pre-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Rebooting kamal-proxy on $KAMAL_HOSTS..." diff --git a/.kamal/secrets.example b/.kamal/secrets.example new file mode 100644 index 000000000..b9601748f --- /dev/null +++ b/.kamal/secrets.example @@ -0,0 +1,6 @@ +# Copy to .kamal/secrets and populate values from environment variables or a +# password manager. Never commit real values. +KAMAL_REGISTRY_PASSWORD=$KAMAL_REGISTRY_PASSWORD +SECRET_KEY_BASE=$SECRET_KEY_BASE +DB_PASSWORD=$DB_PASSWORD +SMTP_PASSWORD=$SMTP_PASSWORD diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 000000000..b3b75c18d --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,32 @@ +# Omakase Ruby styling for Rails +inherit_gem: { rubocop-rails-omakase: rubocop.yml } + +AllCops: + NewCops: enable + TargetRubyVersion: 4.0 + SuggestExtensions: false + +Layout/LineLength: + Max: 140 + Exclude: + - "db/schema.rb" + - "db/*_schema.rb" + - "config/initializers/filter_parameter_logging.rb" + +Lint/AmbiguousBlockAssociation: + Enabled: true + +Lint/UselessAssignment: + Enabled: true + +Metrics/AbcSize: + Max: 20 + Exclude: + - "db/migrate/*.rb" + - "test/**/*.rb" + +Metrics/MethodLength: + Max: 20 + Exclude: + - "db/migrate/*.rb" + - "test/**/*.rb" diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 000000000..1cf76f52b --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-4.0.6 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..203d85e8c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,99 @@ +# syntax=docker/dockerfile:1 +# check=error=true + +# This Dockerfile is designed for production, not development. Use with Kamal or build'n'run by hand: +# docker build -t app . +# docker run -d -p 80:80 -e RAILS_MASTER_KEY= --name app app + +# For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html + +# Make sure RUBY_VERSION matches the Ruby version in .ruby-version +ARG RUBY_VERSION=4.0.6 +FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base + +# Rails app lives here +WORKDIR /rails + +# Install base packages +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y curl libjemalloc2 libvips postgresql-client && \ + ln -s /usr/lib/$(uname -m)-linux-gnu/libjemalloc.so.2 /usr/local/lib/libjemalloc.so && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Set production environment variables and enable jemalloc for reduced memory usage and latency. +ENV RAILS_ENV="production" \ + BUNDLE_DEPLOYMENT="1" \ + BUNDLE_PATH="/usr/local/bundle" \ + BUNDLE_WITHOUT="development:test" \ + LD_PRELOAD="/usr/local/lib/libjemalloc.so" + +# Reusable development/test stage with the same Ruby version as production. +FROM base AS development + +USER root +ENV RAILS_ENV="development" \ + BUNDLE_DEPLOYMENT="0" \ + BUNDLE_WITHOUT="" + +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y build-essential chromium chromium-driver git libpq-dev libvips libyaml-dev pkg-config && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +COPY Gemfile Gemfile.lock ./ +RUN bundle install +COPY . . + +CMD ["./bin/dev"] + +# Throw-away build stage to reduce size of final image +FROM base AS build + +# Install packages needed to build gems +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y build-essential git libpq-dev libvips libyaml-dev pkg-config && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Install application gems +COPY vendor/* ./vendor/ +COPY Gemfile Gemfile.lock ./ + +RUN bundle install && \ + rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ + # -j 1 disable parallel compilation to avoid a QEMU bug: https://github.com/rails/bootsnap/issues/495 + bundle exec bootsnap precompile -j 1 --gemfile + +# Copy application code +COPY . . + +# Precompile bootsnap code for faster boot times. +# -j 1 disable parallel compilation to avoid a QEMU bug: https://github.com/rails/bootsnap/issues/495 +RUN bundle exec bootsnap precompile -j 1 app/ lib/ + +# Precompiling assets for production without requiring secret RAILS_MASTER_KEY +RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile + +# Final stage for app image +FROM base + +# Ruby 4's method-based JIT is enabled only in the lean runtime image. Build +# stages stay deterministic, while production benefits from hot-method native +# compilation without changing application semantics. +ENV RUBYOPT="--zjit" + +# Run and own only the runtime files as a non-root user for security +RUN groupadd --system --gid 1000 rails && \ + useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash +USER 1000:1000 + +# Copy built artifacts: gems, application +COPY --chown=rails:rails --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}" +COPY --chown=rails:rails --from=build /rails /rails + +# Entrypoint prepares the database. +ENTRYPOINT ["/rails/bin/docker-entrypoint"] + +# Start server via Thruster by default, this can be overwritten at runtime +EXPOSE 80 +HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \ + CMD curl --fail --silent http://127.0.0.1/up || exit 1 +CMD ["./bin/thrust", "./bin/rails", "server"] diff --git a/Gemfile b/Gemfile new file mode 100644 index 000000000..446d2a820 --- /dev/null +++ b/Gemfile @@ -0,0 +1,72 @@ +source "https://rubygems.org" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "8.1.3.1" +# The modern asset pipeline for Rails [https://github.com/rails/propshaft] +gem "propshaft" +# Use postgresql as the database for Active Record +gem "pg", "~> 1.1" +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", ">= 5.0" +# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] +gem "importmap-rails" +# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] +gem "turbo-rails" +# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] +gem "stimulus-rails" +# Use Tailwind CSS [https://github.com/rails/tailwindcss-rails] +gem "tailwindcss-rails" +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +gem "jbuilder" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +gem "bcrypt", "~> 3.1" + +# Read XLSX spreadsheets without introducing an external service. +gem "roo", "~> 3.0" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ windows jruby ] + +# Use the database-backed adapters for Rails.cache, Active Job, and Action Cable +gem "solid_cache" +gem "solid_queue" +gem "solid_cable" + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +# Deploy this application anywhere as a Docker container [https://kamal-deploy.org] +gem "kamal", require: false + +# Add HTTP asset caching/compression and X-Sendfile acceleration to Puma [https://github.com/basecamp/thruster/] +gem "thruster", require: false + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +gem "image_processing", "~> 1.2" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri windows ], require: "debug/prelude" + + # Audits gems for known security defects (use config/bundler-audit.yml to ignore issues) + gem "bundler-audit", require: false + + # Static analysis for security vulnerabilities [https://brakemanscanner.org/] + gem "brakeman", require: false + + # Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/] + gem "rubocop-rails-omakase", require: false +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" +end + +group :test do + # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] + gem "capybara" + gem "selenium-webdriver" + gem "simplecov", require: false +end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 000000000..72f30bdf6 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,582 @@ +GEM + remote: https://rubygems.org/ + specs: + action_text-trix (2.1.19) + railties + actioncable (8.1.3.1) + actionpack (= 8.1.3.1) + activesupport (= 8.1.3.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.1.3.1) + actionpack (= 8.1.3.1) + activejob (= 8.1.3.1) + activerecord (= 8.1.3.1) + activestorage (= 8.1.3.1) + activesupport (= 8.1.3.1) + mail (>= 2.8.0) + actionmailer (8.1.3.1) + actionpack (= 8.1.3.1) + actionview (= 8.1.3.1) + activejob (= 8.1.3.1) + activesupport (= 8.1.3.1) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.1.3.1) + actionview (= 8.1.3.1) + activesupport (= 8.1.3.1) + nokogiri (>= 1.8.5) + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + useragent (~> 0.16) + actiontext (8.1.3.1) + action_text-trix (~> 2.1.15) + actionpack (= 8.1.3.1) + activerecord (= 8.1.3.1) + activestorage (= 8.1.3.1) + activesupport (= 8.1.3.1) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.1.3.1) + activesupport (= 8.1.3.1) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (8.1.3.1) + activesupport (= 8.1.3.1) + globalid (>= 0.3.6) + activemodel (8.1.3.1) + activesupport (= 8.1.3.1) + activerecord (8.1.3.1) + activemodel (= 8.1.3.1) + activesupport (= 8.1.3.1) + timeout (>= 0.4.0) + activestorage (8.1.3.1) + actionpack (= 8.1.3.1) + activejob (= 8.1.3.1) + activerecord (= 8.1.3.1) + activesupport (= 8.1.3.1) + marcel (~> 1.0) + activesupport (8.1.3.1) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + json + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + addressable (2.9.0) + public_suffix (>= 2.0.2, < 8.0) + ast (2.4.3) + base64 (0.3.0) + bcrypt (3.1.22) + bcrypt_pbkdf (1.1.2) + bigdecimal (4.1.2) + bindex (0.8.1) + bootsnap (1.25.0) + msgpack (~> 1.5) + brakeman (8.0.6) + racc + builder (3.3.0) + bundler-audit (0.9.3) + bundler (>= 1.2.0) + thor (~> 1.0) + capybara (3.40.0) + addressable + matrix + mini_mime (>= 0.1.3) + nokogiri (~> 1.11) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (>= 1.5, < 3.0) + xpath (~> 3.2) + concurrent-ruby (1.3.8) + connection_pool (3.0.2) + crass (1.0.7) + csv (3.3.6) + date (3.5.1) + debug (1.11.1) + irb (~> 1.10) + reline (>= 0.3.8) + dotenv (3.2.0) + drb (2.2.3) + ed25519 (1.4.0) + erb (6.0.7) + erubi (1.13.1) + et-orbi (1.4.2) + tzinfo + ffi (1.17.4-aarch64-linux-gnu) + ffi (1.17.4-aarch64-linux-musl) + ffi (1.17.4-arm-linux-gnu) + ffi (1.17.4-arm-linux-musl) + ffi (1.17.4-x86_64-linux-gnu) + ffi (1.17.4-x86_64-linux-musl) + fugit (1.13.0) + et-orbi (~> 1.4) + raabro (~> 1.4) + globalid (1.4.0) + activesupport (>= 6.1) + i18n (1.15.2) + concurrent-ruby (~> 1.0) + image_processing (1.14.0) + mini_magick (>= 4.9.5, < 6) + ruby-vips (>= 2.0.17, < 3) + importmap-rails (2.2.3) + actionpack (>= 6.0.0) + activesupport (>= 6.0.0) + railties (>= 6.0.0) + io-console (0.9.2) + irb (1.18.0) + pp (>= 0.6.0) + prism (>= 1.3.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + jbuilder (2.15.1) + actionview (>= 7.0.0) + activesupport (>= 7.0.0) + json (2.21.2) + kamal (2.12.0) + activesupport (>= 7.0) + base64 (~> 0.2) + bcrypt_pbkdf (~> 1.0) + concurrent-ruby (~> 1.2) + dotenv (~> 3.1) + ed25519 (~> 1.4) + net-ssh (~> 7.3) + sshkit (>= 1.23.0, < 2.0) + thor (~> 1.3) + zeitwerk (>= 2.6.18, < 3.0) + language_server-protocol (3.17.0.6) + lint_roller (1.1.0) + logger (1.7.0) + loofah (2.25.2) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.9.1) + logger + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.2.1) + matrix (0.4.3) + mini_magick (5.4.0) + logger + mini_mime (1.1.5) + minitest (6.0.6) + drb (~> 2.0) + prism (~> 1.5) + msgpack (1.8.4) + net-imap (0.6.6) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.3.0) + timeout + net-scp (4.1.0) + net-ssh (>= 2.6.5, < 8.0.0) + net-sftp (4.0.0) + net-ssh (>= 5.0.0, < 8.0.0) + net-smtp (0.5.1) + net-protocol + net-ssh (7.3.3) + nio4r (2.7.5) + nokogiri (1.19.4-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.4-aarch64-linux-musl) + racc (~> 1.4) + nokogiri (1.19.4-arm-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.4-arm-linux-musl) + racc (~> 1.4) + nokogiri (1.19.4-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.4-x86_64-linux-musl) + racc (~> 1.4) + ostruct (0.6.3) + parallel (2.1.0) + parser (3.3.12.0) + ast (~> 2.4.1) + racc + pg (1.6.3) + pg (1.6.3-aarch64-linux) + pg (1.6.3-aarch64-linux-musl) + pg (1.6.3-x86_64-linux) + pg (1.6.3-x86_64-linux-musl) + pp (0.6.4) + prettyprint + prettyprint (0.2.0) + prism (1.9.0) + propshaft (1.3.2) + actionpack (>= 7.0.0) + activesupport (>= 7.0.0) + rack + public_suffix (7.0.5) + puma (8.0.2) + nio4r (~> 2.0) + raabro (1.5.0) + racc (1.8.1) + rack (3.2.7) + rack-session (2.1.2) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.2.0) + rack (>= 1.3) + rackup (2.3.1) + rack (>= 3) + rails (8.1.3.1) + actioncable (= 8.1.3.1) + actionmailbox (= 8.1.3.1) + actionmailer (= 8.1.3.1) + actionpack (= 8.1.3.1) + actiontext (= 8.1.3.1) + actionview (= 8.1.3.1) + activejob (= 8.1.3.1) + activemodel (= 8.1.3.1) + activerecord (= 8.1.3.1) + activestorage (= 8.1.3.1) + activesupport (= 8.1.3.1) + bundler (>= 1.15.0) + railties (= 8.1.3.1) + rails-dom-testing (2.3.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.7.1) + loofah (~> 2.25, >= 2.25.2) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + railties (8.1.3.1) + actionpack (= 8.1.3.1) + activesupport (= 8.1.3.1) + irb (~> 1.13) + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + tsort (>= 0.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.4.2) + rbs (4.2.0) + logger + prism (>= 1.6.0) + tsort + rdoc (8.0.0) + erb + prism (>= 1.6.0) + rbs (>= 4.0.0) + tsort + regexp_parser (2.12.0) + reline (0.7.0) + io-console (~> 0.5) + rexml (3.4.4) + roo (3.0.0) + base64 (~> 0.2) + csv (~> 3) + logger (~> 1) + nokogiri (~> 1) + rubyzip (>= 3.0.0, < 4.0.0) + rubocop (1.90.0) + json (>= 2.3) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.1.0) + parallel (>= 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.9.3, < 3.0) + rubocop-ast (>= 1.49.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.50.0) + parser (>= 3.3.7.2) + prism (~> 1.7) + rubocop-performance (1.27.0) + lint_roller (~> 1.1) + rubocop (>= 1.89.0, < 2.0) + rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rails (2.37.0) + activesupport (>= 4.2.0) + lint_roller (~> 1.1) + rack (>= 1.1) + rubocop (>= 1.89.0, < 2.0) + rubocop-ast (>= 1.44.0, < 2.0) + rubocop-rails-omakase (1.1.0) + rubocop (>= 1.72) + rubocop-performance (>= 1.24) + rubocop-rails (>= 2.30) + ruby-progressbar (1.13.0) + ruby-vips (2.3.0) + ffi (~> 1.12) + logger + rubyzip (3.6.0) + securerandom (0.4.1) + selenium-webdriver (4.48.0) + base64 (~> 0.2) + logger (~> 1.4) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 4.0) + websocket (~> 1.0) + simplecov (1.1.1) + solid_cable (4.0.2) + actioncable (>= 7.2) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_cache (1.0.10) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_queue (1.7.0) + activejob (>= 7.1) + activerecord (>= 7.1) + concurrent-ruby (>= 1.3.1) + fugit (~> 1.11) + railties (>= 7.1) + thor (>= 1.3.1) + sshkit (1.25.1) + base64 + logger + net-scp (>= 1.1.2) + net-sftp (>= 2.1.2) + net-ssh (>= 2.8.0) + ostruct + stimulus-rails (1.3.4) + railties (>= 6.0.0) + tailwindcss-rails (4.6.0) + railties (>= 7.0.0) + tailwindcss-ruby (~> 4.0) + tailwindcss-ruby (4.3.3) + tailwindcss-ruby (4.3.3-aarch64-linux-gnu) + tailwindcss-ruby (4.3.3-aarch64-linux-musl) + tailwindcss-ruby (4.3.3-x86_64-linux-gnu) + tailwindcss-ruby (4.3.3-x86_64-linux-musl) + thor (1.5.0) + thruster (0.1.26) + thruster (0.1.26-aarch64-linux) + thruster (0.1.26-x86_64-linux) + timeout (0.6.1) + tsort (0.2.0) + turbo-rails (2.0.23) + actionpack (>= 7.1.0) + railties (>= 7.1.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (3.2.0) + unicode-emoji (~> 4.1) + unicode-emoji (4.2.0) + uri (1.1.1) + useragent (0.16.11) + web-console (4.3.0) + actionview (>= 8.0.0) + bindex (>= 0.4.0) + railties (>= 8.0.0) + websocket (1.2.11) + websocket-driver (0.8.2) + base64 + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.8.3) + +PLATFORMS + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + x86_64-linux + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + bcrypt (~> 3.1) + bootsnap + brakeman + bundler-audit + capybara + debug + image_processing (~> 1.2) + importmap-rails + jbuilder + kamal + pg (~> 1.1) + propshaft + puma (>= 5.0) + rails (= 8.1.3.1) + roo (~> 3.0) + rubocop-rails-omakase + selenium-webdriver + simplecov + solid_cable + solid_cache + solid_queue + stimulus-rails + tailwindcss-rails + thruster + turbo-rails + tzinfo-data + web-console + +CHECKSUMS + action_text-trix (2.1.19) sha256=7012f59421009cf284aa651294896414d653a61a2417c9b8714c8476d2f74009 + actioncable (8.1.3.1) sha256=e318528295c878a3efdfe25f0f2267c80cb7a76eba41bb5f64d44aa380a3d91b + actionmailbox (8.1.3.1) sha256=5f704972097d843ade8e435e93694a1dac732b926df1717aceba1f3840082b1c + actionmailer (8.1.3.1) sha256=88ea441b28ff02a0c6c006468892642a3d9942affce9d294e81a74504aa5c43c + actionpack (8.1.3.1) sha256=974cb7154548e81f470b1b0f247b99cb38e87825899dca58610596e2817723d0 + actiontext (8.1.3.1) sha256=5da729d833d1a29cddb1eee938878e55e503d2613e00e735f5daf58c2ba98af2 + actionview (8.1.3.1) sha256=2da68b8414c47b43bfbed1ce69c5afe1c04f78c267aacb5660a4cab5ca12cfb6 + activejob (8.1.3.1) sha256=1c8dd275df930df40deecffec63d913a550a33fd94bd298f69721dd96939954a + activemodel (8.1.3.1) sha256=99cc02ce2faec371d14440949d85787ebd23a907c9baef0a9d4bcd4d21888f88 + activerecord (8.1.3.1) sha256=0a2fb6c28f4938f6b013a3a549bec0a7e37d535f3dc8990e804bcc3258c0403b + activestorage (8.1.3.1) sha256=f555254f387b1cffa499d2fd3115d12635eadc5b15206a8534316a67036163ef + activesupport (8.1.3.1) sha256=85458765f25ea48b9019c46b6bb3fa5683197bf4280d9f06710a6e8d7a831376 + addressable (2.9.0) sha256=7fdf6ac3660f7f4e867a0838be3f6cf722ace541dd97767fa42bc6cfa980c7af + ast (2.4.3) sha256=954615157c1d6a382bc27d690d973195e79db7f55e9765ac7c481c60bdb4d383 + base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b + bcrypt (3.1.22) sha256=1f0072e88c2d705d94aff7f2c5cb02eb3f1ec4b8368671e19112527489f29032 + bcrypt_pbkdf (1.1.2) sha256=c2414c23ce66869b3eb9f643d6a3374d8322dfb5078125c82792304c10b94cf6 + bigdecimal (4.1.2) sha256=53d217666027eab4280346fba98e7d5b66baaae1b9c3c1c0ffe89d48188a3fbd + bindex (0.8.1) sha256=7b1ecc9dc539ed8bccfc8cb4d2732046227b09d6f37582ff12e50a5047ceb17e + bootsnap (1.25.0) sha256=41059e7d0f9cb4023a33465d095f64b913fc9d1b808d6524c307da945fbcffcf + brakeman (8.0.6) sha256=759cc69341115e6c2dcd47b6fd8649a0b9bd540e3585ac8a0a94e31c66fee386 + builder (3.3.0) sha256=497918d2f9dca528fdca4b88d84e4ef4387256d984b8154e9d5d3fe5a9c8835f + bundler-audit (0.9.3) sha256=81c8766c71e47d0d28a0f98c7eed028539f21a6ea3cd8f685eb6f42333c9b4e9 + capybara (3.40.0) sha256=42dba720578ea1ca65fd7a41d163dd368502c191804558f6e0f71b391054aeef + concurrent-ruby (1.3.8) sha256=b2f1be836e968ccc78ccfce277ea79c72a88633f22306782c16ff23fb415d1e1 + connection_pool (3.0.2) sha256=33fff5ba71a12d2aa26cb72b1db8bba2a1a01823559fb01d29eb74c286e62e0a + crass (1.0.7) sha256=94868719948664c89ddcaf0a37c65048413dfcb1c869470a5f7a7ceb5390b295 + csv (3.3.6) sha256=aba61e7e507a66f03d45cb1f3c4b6359861c3504038b422962875dce099e4456 + date (3.5.1) sha256=750d06384d7b9c15d562c76291407d89e368dda4d4fff957eb94962d325a0dc0 + debug (1.11.1) sha256=2e0b0ac6119f2207a6f8ac7d4a73ca8eb4e440f64da0a3136c30343146e952b6 + dotenv (3.2.0) sha256=e375b83121ea7ca4ce20f214740076129ab8514cd81378161f11c03853fe619d + drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373 + ed25519 (1.4.0) sha256=16e97f5198689a154247169f3453ef4cfd3f7a47481fde0ae33206cdfdcac506 + erb (6.0.7) sha256=c5ca6dc25b0ef974a44dc8f59fe847577122483b1968a38dec305c60bf91ee92 + erubi (1.13.1) sha256=a082103b0885dbc5ecf1172fede897f9ebdb745a4b97a5e8dc63953db1ee4ad9 + et-orbi (1.4.2) sha256=bb555dae668419cb24caa2a293a170e58be6d4df1e017c51f5030bdc133cd20c + ffi (1.17.4-aarch64-linux-gnu) sha256=b208f06f91ffd8f5e1193da3cae3d2ccfc27fc36fba577baf698d26d91c080df + ffi (1.17.4-aarch64-linux-musl) sha256=9286b7a615f2676245283aef0a0a3b475ae3aae2bb5448baace630bb77b91f39 + ffi (1.17.4-arm-linux-gnu) sha256=d6dbddf7cb77bf955411af5f187a65b8cd378cb003c15c05697f5feee1cb1564 + ffi (1.17.4-arm-linux-musl) sha256=9d4838ded0465bef6e2426935f6bcc93134b6616785a84ffd2a3d82bc3cf6f95 + ffi (1.17.4-x86_64-linux-gnu) sha256=9d3db14c2eae074b382fa9c083fe95aec6e0a1451da249eab096c34002bc752d + ffi (1.17.4-x86_64-linux-musl) sha256=3fdf9888483de005f8ef8d1cf2d3b20d86626af206cbf780f6a6a12439a9c49e + fugit (1.13.0) sha256=a4f093fce740da52f216740a5041e2a594ea763cdb89e8b2754ca4399634ab18 + globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427 + i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5 + image_processing (1.14.0) sha256=754cc169c9c262980889bec6bfd325ed1dafad34f85242b5a07b60af004742fb + importmap-rails (2.2.3) sha256=7101be2a4dc97cf1558fb8f573a718404c5f6bcfe94f304bf1f39e444feeb16a + io-console (0.9.2) sha256=efa74f891dd03c0939a931dfc6e74c2813d904763d456ea9762b0525e748db08 + irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3 + jbuilder (2.15.1) sha256=2430bec28fb0cebacb5875b1009cf9d8bc3c303ccb810c4c8b062a4b51457637 + json (2.21.2) sha256=1f1d3b7cf2b3ba1a69beca0bb6db13d5438b80bff3cd54cdaaa620b9b07c1c6a + kamal (2.12.0) sha256=c51d1ab085e515470f98d0c0f043637122b5ebf76e8b610cb1fbbed0b7f9b8fa + language_server-protocol (3.17.0.6) sha256=5ef2c0c138f8267e1bc631d3328347d354f96724b0af22f2c79516120443b7f0 + lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87 + logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203 + loofah (2.25.2) sha256=2007f746959ac65552456e04b433e83deb22759ab38c838b4445c70e43425918 + mail (2.9.1) sha256=06574eca475253d6c18145dd70af80d0eb970182d55053497c5f4d797ea160e8 + marcel (1.2.1) sha256=1678e9360e32f9eafa917c80029e2f6d10b2715c66a4b87b6d0da9b9cd1f859f + matrix (0.4.3) sha256=a0d5ab7ddcc1973ff690ab361b67f359acbb16958d1dc072b8b956a286564c5b + mini_magick (5.4.0) sha256=f120af581d9ed4ec52c57f35a67a605d112bb1d8f582d1415b147fda42d11d78 + mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef + minitest (6.0.6) sha256=153ea36d1d987a62942382b61075745042a2b3123b1cd48f4c3675af9cc7d6f1 + msgpack (1.8.4) sha256=4411c22d350dd1c20250f7eada3cca2695438c2f769cf0782f0cd065d90a3e7b + net-imap (0.6.6) sha256=96aa4ee50df3060203e649efc341f53480b791d49e150f2fdebf68beb141a8df + net-pop (0.1.2) sha256=848b4e982013c15b2f0382792268763b748cce91c9e91e36b0f27ed26420dff3 + net-protocol (0.3.0) sha256=ba310c3d4f1cad46bb1ab20336b06669b1ff8f7c568d9cb9342b32a718547472 + net-scp (4.1.0) sha256=a99b0b92a1e5d360b0de4ffbf2dc0c91531502d3d4f56c28b0139a7c093d1a5d + net-sftp (4.0.0) sha256=65bb91c859c2f93b09826757af11b69af931a3a9155050f50d1b06d384526364 + net-smtp (0.5.1) sha256=ed96a0af63c524fceb4b29b0d352195c30d82dd916a42f03c62a3a70e5b70736 + net-ssh (7.3.3) sha256=831def58b2c51dcef66ec00d29397d4f210de89c19fe78f95873ca30f386e86a + nio4r (2.7.5) sha256=6c90168e48fb5f8e768419c93abb94ba2b892a1d0602cb06eef16d8b7df1dca1 + nokogiri (1.19.4-aarch64-linux-gnu) sha256=1269fb644a6de405057a53dd5c762b1209b43ca7424f839454d3dbc677c31a8f + nokogiri (1.19.4-aarch64-linux-musl) sha256=35c65b9ce72b3bb03207bdbe7067915019dc18c1b9b59139684bd6690fdd01af + nokogiri (1.19.4-arm-linux-gnu) sha256=a301313e38bb065d68239e79734bcd6f56fb6efaacebde29e9abf2a4735340ca + nokogiri (1.19.4-arm-linux-musl) sha256=588923c101bcfa78869734d247d25b598674323e7f22474fc468f6e5647311eb + nokogiri (1.19.4-x86_64-linux-gnu) sha256=379fae440b28915e3f19d752ce2dcf8465ed2b2fbefd2a7ca0dd497bc981a06a + nokogiri (1.19.4-x86_64-linux-musl) sha256=17dfb7c1fa194ae02fbf7c51a7afc8d278045ab3fdacfd86f91d02d7b274470b + ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912 + parallel (2.1.0) sha256=b35258865c2e31134c5ecb708beaaf6772adf9d5efae28e93e99260877b09356 + parser (3.3.12.0) sha256=21a6d7f755d5a24dfbdc6e6b772e4e879a52e7631a88bc5a3a134606052c9828 + pg (1.6.3) sha256=1388d0563e13d2758c1089e35e973a3249e955c659592d10e5b77c468f628a99 + pg (1.6.3-aarch64-linux) sha256=0698ad563e02383c27510b76bf7d4cd2de19cd1d16a5013f375dd473e4be72ea + pg (1.6.3-aarch64-linux-musl) sha256=06a75f4ea04b05140146f2a10550b8e0d9f006a79cdaf8b5b130cde40e3ecc2c + pg (1.6.3-x86_64-linux) sha256=5d9e188c8f7a0295d162b7b88a768d8452a899977d44f3274d1946d67920ae8d + pg (1.6.3-x86_64-linux-musl) sha256=9c9c90d98c72f78eb04c0f55e9618fe55d1512128e411035fe229ff427864009 + pp (0.6.4) sha256=dfcb0fce700c41456265922884f9fe195d7fbb0674a3578e6c0f69588e82b570 + prettyprint (0.2.0) sha256=2bc9e15581a94742064a3cc8b0fb9d45aae3d03a1baa6ef80922627a0766f193 + prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85 + propshaft (1.3.2) sha256=1d56a3e56a92c21bfc29caf07406b5386b00d4c47ddf357cf989a5a234b1389e + public_suffix (7.0.5) sha256=1a8bb08f1bbea19228d3bed6e5ed908d1cb4f7c2726d18bd9cadf60bc676f623 + puma (8.0.2) sha256=c8ed871dfbbe66448ea9ffd46692342d9804d4071522b52b5331b7b6e7b686fb + raabro (1.5.0) sha256=3f998a7bc84f9c84df3ab580634d2e0a5bda4f0841168d56035f529c9877440a + racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f + rack (3.2.7) sha256=93e13e1c24f93556671d85d2d79fa228c3485815c50d7e2f265b5330c6528fb7 + rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8 + rack-test (2.2.0) sha256=005a36692c306ac0b4a9350355ee080fd09ddef1148a5f8b2ac636c720f5c463 + rackup (2.3.1) sha256=6c79c26753778e90983761d677a48937ee3192b3ffef6bc963c0950f94688868 + rails (8.1.3.1) sha256=ccd11a36bfc171bf9c66d585d14c0ece91c0c9dde840aae60c0118d6f5c9c52a + rails-dom-testing (2.3.0) sha256=8acc7953a7b911ca44588bf08737bc16719f431a1cc3091a292bca7317925c1d + rails-html-sanitizer (1.7.1) sha256=e797a7c9b01e567307e317c576b49ab4168017e63eea4dba9ce3cb587e2f22c2 + railties (8.1.3.1) sha256=2388a232579a00cefea4487de66c8553c3408c1300abdc6cf1799d86ffb04487 + rainbow (3.1.1) sha256=039491aa3a89f42efa1d6dec2fc4e62ede96eb6acd95e52f1ad581182b79bc6a + rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701 + rbs (4.2.0) sha256=51f7b886dcc05bc09e10b901daa6a81829f6adc03101d6ca9ea4aac6103e0674 + rdoc (8.0.0) sha256=03bf8c08a9639658855a0cfd77c0abca8325c227693f7f33f82957811348c469 + regexp_parser (2.12.0) sha256=35a916a1d63190ab5c9009457136ae5f3c0c7512d60291d0d1378ba18ce08ebb + reline (0.7.0) sha256=5b012d8e55dbf9d450f12bde2cf7d15ff546ae80b3f8f3b30e570d431815583d + rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142 + roo (3.0.0) sha256=6fdd7a9158d657c69768b4168754ff2110cc21fdc01a1bec1010820cb05c91b1 + rubocop (1.90.0) sha256=9eb4c065b5c5154e4ef554c547972f3905a9eb6b53e657e580b6796b54bf8242 + rubocop-ast (1.50.0) sha256=b9ca88300da0803ee222ad20cdb30494c0a784eed06fdc35d254b06d662788db + rubocop-performance (1.27.0) sha256=eeeb1374d062a368ee1c787b70eb0b0cc4b184cb1f8565f424760946146d61ce + rubocop-rails (2.37.0) sha256=6e1645add5060e0328f8ddda0d820f55697c591394398bf14bb9dccb62f14b7e + rubocop-rails-omakase (1.1.0) sha256=2af73ac8ee5852de2919abbd2618af9c15c19b512c4cfc1f9a5d3b6ef009109d + ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33 + ruby-vips (2.3.0) sha256=e685ec02c13969912debbd98019e50492e12989282da5f37d05f5471442f5374 + rubyzip (3.6.0) sha256=268994d44d62282d1cfd99bf10eae48d7267199158ad7ea3e1fee2da9458b695 + securerandom (0.4.1) sha256=cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1 + selenium-webdriver (4.48.0) sha256=0c8376ebc8a0a4879343fe6fe6eccdcea76748611cd25de370b33eded2077a94 + simplecov (1.1.1) sha256=25825ef13f0b2e74694d769817dad6ab8e90131dabdaa666e522fea105521e78 + solid_cable (4.0.2) sha256=084636a67679ad00d23088b33c84047e614bcf41ee559db24b414d83cdc42d03 + solid_cache (1.0.10) sha256=bc05a2fb3ac78a6f43cbb5946679cf9db67dd30d22939ededc385cb93e120d41 + solid_queue (1.7.0) sha256=6566b70b801d1c317c81bba7bcdd5677c019afac584a30374b4164002ca356d3 + sshkit (1.25.1) sha256=be3f10b9d6eb0b44d5eaba3f7cbe41bc6bb894bce4339688ac20124391455b78 + stimulus-rails (1.3.4) sha256=765676ffa1f33af64ce026d26b48e8ffb2e0b94e0f50e9119e11d6107d67cb06 + tailwindcss-rails (4.6.0) sha256=d99512867173d55c5ef8890427682299d8539f550cec1408b3d8667a538bd365 + tailwindcss-ruby (4.3.3) sha256=ee0a64030749862deb501acab4c4aaf5adbee13865746a33299d46d7b5d0952a + tailwindcss-ruby (4.3.3-aarch64-linux-gnu) sha256=c86d6dd3eccc85fe0d792a832b06f2bf3c0a7a83b399308aeb9d8f5725f42a6a + tailwindcss-ruby (4.3.3-aarch64-linux-musl) sha256=72b77ca9edea82383dd09510ab520a122e3cb9f9864ca5b38e27698098d2b899 + tailwindcss-ruby (4.3.3-x86_64-linux-gnu) sha256=2337017ff8b02698480eae1e9637cf01faa0e4824db89d067a13c5a5ee38c9b2 + tailwindcss-ruby (4.3.3-x86_64-linux-musl) sha256=27d478c417bcf73828e5b544744c5bdfd5b5cb54f1a266fc4f185281c32efe6c + thor (1.5.0) sha256=e3a9e55fe857e44859ce104a84675ab6e8cd59c650a49106a05f55f136425e73 + thruster (0.1.26) sha256=6e45e807086b29d51404841bd1ad493b67cd95892fd65dc5afcdd32e82e94ce8 + thruster (0.1.26-aarch64-linux) sha256=2171cb34928c0250830008f535c4ab2ee57846cc3f5d3e96c3475f7b3de7a541 + thruster (0.1.26-x86_64-linux) sha256=3117a6ee430663f845a0457699fe9a05232dcc6c396e2cc83504de5a223c60e8 + timeout (0.6.1) sha256=78f57368a7e7bbadec56971f78a3f5ecbcfb59b7fcbb0a3ed6ddc08a5094accb + tsort (0.2.0) sha256=9650a793f6859a43b6641671278f79cfead60ac714148aabe4e3f0060480089f + turbo-rails (2.0.23) sha256=ee0d90733aafff056cf51ff11e803d65e43cae258cc55f6492020ec1f9f9315f + tzinfo (2.0.6) sha256=8daf828cc77bcf7d63b0e3bdb6caa47e2272dcfaf4fbfe46f8c3a9df087a829b + unicode-display_width (3.2.0) sha256=0cdd96b5681a5949cdbc2c55e7b420facae74c4aaf9a9815eee1087cb1853c42 + unicode-emoji (4.2.0) sha256=519e69150f75652e40bf736106cfbc8f0f73aa3fb6a65afe62fefa7f80b0f80f + uri (1.1.1) sha256=379fa58d27ffb1387eaada68c749d1426738bd0f654d812fcc07e7568f5c57c6 + useragent (0.16.11) sha256=700e6413ad4bb954bb63547fa098dddf7b0ebe75b40cc6f93b8d54255b173844 + web-console (4.3.0) sha256=e13b71301cdfc2093f155b5aa3a622db80b4672d1f2f713119cc7ec7ac6a6da4 + websocket (1.2.11) sha256=b7e7a74e2410b5e85c25858b26b3322f29161e300935f70a0e0d3c35e0462737 + websocket-driver (0.8.2) sha256=97c556b019bf3410b4961002ac501621e9322d3f8a7bc02161a09301cc4c4146 + websocket-extensions (0.1.5) sha256=1c6ba63092cda343eb53fc657110c71c754c56484aad42578495227d717a8241 + xpath (3.2.0) sha256=6dfda79d91bb3b949b947ecc5919f042ef2f399b904013eb3ef6d20dd3a4082e + zeitwerk (2.8.3) sha256=2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5 + +BUNDLED WITH + 4.0.16 diff --git a/Procfile.dev b/Procfile.dev new file mode 100644 index 000000000..c7cf64525 --- /dev/null +++ b/Procfile.dev @@ -0,0 +1,3 @@ +web: bin/rails server +css: bin/rails tailwindcss:watch +jobs: bin/jobs diff --git a/README.md b/README.md index 7829f14ff..20d65acf1 100644 --- a/README.md +++ b/README.md @@ -1,87 +1,202 @@ -# Modern Fullstack Developer Test (Rails 8 / Ruby 4) - -- Check this readme.md -- Create a branch to develop your task -- Push to remote in 1 week (date will be checked from branch creation/assigned date) - -# Requirements: -- Target Stack: **Ruby 4.0+** and **Rails 8.0+** -- Database: PostgreSQL, MySQL, or SQLite (configured for production-ready WAL mode) -- Write robust unit, integration, and system tests using parallel testing features -- Deliver with a working multi-stage Dockerfile utilizing Thruster/Kamal-ready defaults -- Show senior best practices (e.g., proper design patterns, solid architecture, strict linter configuration) - -# Our AI Policy -At Umanni, we value efficiency and the modern developer workflow. **You are allowed to use AI coding assistants (ChatGPT, Claude, Copilot, etc.) during this test.** However, transparency is part of our culture. If you use any LLM to generate, refactor, or structure your code, **you must explicitly state which model you used** in a dedicated section at the top of your submission's README.md. Failing to disclose AI usage while using it will invalidate your submission. - -# The Test -Here we'll try to simulate a "real sprint" that you'll probably be assigned while working as Fullstack at Umanni. - -# The Task -- Create a modern, responsive application to manage users. -- A user must have: - 1. full_name - 2. email - 3. avatar_image (ActiveStorage file upload or remote URL) - 4. role (admin/no-admin) - -# The App -## Admin Use cases -- As an Admin, I must be able to access a User Admin Dashboard. -- As an Admin, I must be able to see on the Dashboard (updated via real-time streams/frontend state): - - Total number of Users - - Total number of Users grouped by Role -- As an Admin, I must be redirected to the User Admin Dashboard after login. -- As an Admin, I must be able to list, create, edit, and delete Users. -- As an Admin, I must be able to toggle the User Role. -- As an Admin, I must be able to import a Spreadsheet (.csv/.xlsx) into the system in order to asynchronously create new Users. -- As an Admin, I must be able to see the live progress/status of the spreadsheet import process. - -## User Use Cases -- As a User, I must be redirected to my Profile after login. -- As a User, I must be able only to see my info, edit, and delete my profile. - -## Visitor Use Cases -- As a Visitor, I can register myself as a normal User. - - - -# The Start. -- Your deadline is 1 week after accepting this test. - -# The Rules (Strict Compliance) -These are mandatory. Failing any of them will invalidate your submission. -- **Documentation**: You must write down a detailed README.md in English explaining how to build, seed, and run your app, including your AI disclosure if applicable. -- **Frontend Stack**: You have two choices for the modern monolithic approach: - - **Option A (Classic Modern):** Hotwire (Turbo 8+ / Stimulus) with smooth, reactive UI states. - - **Option B (Modern SPA Monolith):** **React integrated via Inertia.js** (using Vite or the official Rails 8 asset pipeline integration). -- **Styling**: The Frontend must use a modern CSS framework (Tailwind CSS, Bootstrap, or any utility-first library). Keep it beautiful, responsive, and clean. -- **Real-time & Background Processing**: You must leverage native Rails 8 tools (**Solid Cable** for live dashboard counters/import bars and **Solid Queue** for the background import processing). No Redis installation should be required. -- **Authentication**: You must use the new built-in Rails 8 Authentication system (`bin/rails generate authentication`), customized to fit the role constraints. Avoid legacy heavy gems (like Devise). -- **Git Hygiene**: Clean git history with atomic commits, proper descriptions, and a Pull Request-based workflow. - -# What we're expecting to see: -- Modern asset management using **Propshaft** or **Vite Rails** (if choosing Inertia/React). -- .gitignore, .dockerignore configured correctly. -- Clean application configuration using Rails credentials. -- Comprehensive cross-browser support considerations. -- Strict form validations (Frontend interactive feedback + Backend structural validation). -- Parallel testing with at least 90% coverage (using Minitest, RSpec, and Playwright/Capybara for frontend integration). - -# Extra points -- Delivery via a clean **Kamal 2** deployment configuration (`deploy.yml`). -- Advanced SSR (Server-Side Rendering) setup if using **Inertia.js + React**. -- Use of **Thruster** as a zero-config proxy for asset caching and compression in Docker. -- Advanced performance profiling leveraging Ruby 4's **ZJIT** compilation optimizations. - -# What will be assessed -- Code's Semantics, Cleanness, and Maintainability (Senior-level object-oriented design and clean React/Stimulus component lifecycle). -- Modern Rails 8 idiom usage (e.g., Strict structural params handling, Solid architecture separation). -- Basic Security testing against traditional vectors (SQLi, XSS, XSRF) and proper encryption of sensitive DB columns where applicable. +### AI Usage Disclosure + +I used OpenAI Codex with GPT-5.6 Sol (`gpt-5.6-sol`) while designing the architecture, implementing features, writing tests, and reviewing this submission. I remained responsible for the technical decisions, reviewed the generated changes, and validated the result with automated checks, a production-mode Docker build, and hands-on browser testing. + +# Umanni Full Stack Challenge: User Management + +[![CI](https://github.com/tilipim123/Fullstack-Developer/actions/workflows/ci.yml/badge.svg?branch=feature%2Fsenior-user-management)](https://github.com/tilipim123/Fullstack-Developer/actions/workflows/ci.yml) +[![CodeQL](https://github.com/tilipim123/Fullstack-Developer/actions/workflows/codeql.yml/badge.svg?branch=feature%2Fsenior-user-management)](https://github.com/tilipim123/Fullstack-Developer/actions/workflows/codeql.yml) + +This is my implementation of Umanni's full stack challenge. I chose the Hotwire option and kept the application close to the Rails 8 defaults: authentication comes from the built-in generator, background work and live updates use Solid Queue and Solid Cable, and PostgreSQL stores both application and operational data. The result runs without Redis or a separate frontend service. + +## What I built + +- Visitors can register with a name, unique email, password, and uploaded or remote HTTPS avatar. Self-registration always creates a standard user. +- Standard users are redirected to their own profile and can only view, edit, or delete that account. +- Administrators are redirected to a live dashboard and can search, create, edit, delete, promote, and demote users. +- The final administrator is protected from concurrent demotion or deletion. +- CSV and XLSX imports run asynchronously, retain per-row outcomes, tolerate partial failure, and publish live progress. +- Dashboard totals update through Turbo Streams whenever users or roles change. +- Authentication uses the Rails 8 generator, secure signed cookies, session revocation, password recovery, and rate limiting. +- The UI is responsive, keyboard-accessible, and built with Hotwire, Stimulus, Propshaft, and Tailwind CSS. + +## Technology + +| Concern | Choice | +| --- | --- | +| Runtime | Ruby 4.0.6 with ZJIT in the production image | +| Framework | Rails 8.1.3.1 | +| Database | PostgreSQL 17 | +| Frontend | Turbo 8, Stimulus, Importmap, Propshaft, Tailwind CSS 4 | +| Background work | Solid Queue | +| Real-time updates | Solid Cable + Turbo Streams | +| Cache | Solid Cache | +| Uploads | Active Storage | +| Spreadsheet parsing | Roo (CSV and XLSX) | +| Tests | Minitest, Capybara, Selenium/Chromium, SimpleCov | +| Delivery | Multi-stage Docker, Thruster, Docker Compose, Kamal 2 | + +## Why I kept it as a monolith + +These use cases share the same users, permissions, transactions, and reporting data, so splitting them into services would add failure modes without creating a useful ownership or scaling boundary. I kept one deployable Rails application and separated responsibilities inside it: controllers handle HTTP orchestration, models protect persistence invariants, service objects own mutations, query objects compose reads, and jobs provide the asynchronous boundary. + +```mermaid +flowchart LR + Browser[Hotwire browser] --> Controllers[Rails controllers] + Controllers --> Services[Domain services] + Controllers --> Queries[Query objects] + Services --> PostgreSQL[(PostgreSQL)] + Queries --> PostgreSQL + Controllers --> Queue[Solid Queue] + Queue --> Jobs[Import and broadcast jobs] + Jobs --> PostgreSQL + Jobs --> Cable[Solid Cable] + Cable --> Browser + Controllers --> Storage[Active Storage] +``` + +The boundaries and design decisions are described in [docs/architecture.md](docs/architecture.md). Security controls are documented in [docs/security.md](docs/security.md), the browser acceptance inventory is in [docs/qa-inventory.md](docs/qa-inventory.md), and the completed validation evidence is in [docs/qa-report.md](docs/qa-report.md). + +## Run with Docker + +Docker is the recommended path because it pins Ruby, PostgreSQL, Chromium, and the native dependencies. + +```bash +git clone https://github.com/tilipim123/Fullstack-Developer.git +cd Fullstack-Developer +git switch feature/senior-user-management +docker compose up --build -d +docker compose run --rm web bin/rails db:seed +``` + +Open [http://localhost:3000](http://localhost:3000). Compose starts: + +- `database`: PostgreSQL 17 with a persistent volume and health check; +- `setup`: one-shot preparation of the application, cache, queue, and cable databases; +- `web`: non-root production Rails image behind Thruster on port 3000; +- `jobs`: a dedicated Solid Queue supervisor. + +Demo credentials created by the idempotent seed: + +| Role | Email | Password | +| --- | --- | --- | +| Administrator | `admin@example.com` | `SecurePass123!` | +| Standard user | `member@example.com` | `SecurePass123!` | + +These credentials are for local evaluation only. Stop the stack with `docker compose down`. + +## Local development + +Prerequisites are Ruby 4.0.6, PostgreSQL 17, and Chromium/Chrome for system tests. + +```bash +cp .env.example .env +set -a && source .env && set +a +bundle install +bin/setup +bin/dev +``` + +`bin/dev` starts Rails, the Tailwind watcher, and Solid Queue. Seed at any time with `bin/rails db:seed`; the operation is idempotent. + +## Configuration + +No real secret is committed. Environment variables configure the runtime, while Rails credentials may supply SMTP values in production. + +| Variable | Purpose | Local default | +| --- | --- | --- | +| `DB_HOST`, `DB_PORT` | PostgreSQL endpoint | `127.0.0.1:5432` | +| `DB_USERNAME`, `DB_PASSWORD` | PostgreSQL credentials | `postgres` / `postgres` | +| `APP_HOST`, `APP_PROTOCOL` | URL generation, host authorization, and HTTPS policy | `localhost` / `http` | +| `SECRET_KEY_BASE` | Cookie/message encryption in production | set by Compose for local evaluation only | +| `SMTP_ADDRESS`, `SMTP_PORT` | Optional SMTP endpoint | file delivery when absent | +| `SMTP_USERNAME`, `SMTP_PASSWORD` | Optional SMTP credentials | none | +| `RAILS_MAX_THREADS` | Rails database/web concurrency | `5` | +| `JOB_CONCURRENCY` | Solid Queue worker processes | `1` | +| `DOCKER_SUBNET` | Override the isolated Compose network if it conflicts with a local VPN | `198.18.113.0/24` | + +For encrypted SMTP configuration: + +```yaml +smtp: + address: smtp.example.com + port: 587 + user_name: example + password: secret +``` + +Edit it with `bin/rails credentials:edit`. Environment variables take precedence. Without SMTP, production-like local runs write mail to `storage/mails`, so background jobs remain testable without an external service. + +## Spreadsheet imports + +Download either template from the import screen or use: + +- `public/user_import_template.csv` +- `public/user_import_template.xlsx` + +Required columns are `full_name`, `email`, and `avatar_image_url`. Optional `role` accepts `admin`, `user`, `no-admin`, `true`, `false`, `1`, or `0`. Files are limited to 5 MB and 1,000 data rows. + +An import persists its status and every row before broadcasting. Valid rows commit independently; invalid or duplicate rows are displayed with an actionable error and never overwrite an existing account. Retrying a partially processed job skips rows already marked successful, and a terminal import is a no-op. The upload must have a matching extension and content type; XLSX archives are also checked for entry count, expanded size, and bounded sheet rows before parsing. If an administrator or imported user is later deleted, the audit trail remains available with anonymized references. + +## Tests and quality gates + +Run the same complete gate used by CI: + +```bash +docker compose --profile tools run --rm test bin/ci +``` + +Individual commands: + +```bash +docker compose --profile tools run --rm test bin/rails test +docker compose --profile tools run --rm test bin/rails test:system +docker compose --profile tools run --rm test bin/rubocop +docker compose --profile tools run --rm test bin/brakeman --quiet --no-pager --exit-on-warn --exit-on-error +docker compose --profile tools run --rm test bin/bundler-audit +docker compose --profile tools run --rm test bin/importmap audit +``` + +The model, service, query, job, and controller tests run in parallel and enforce at least 90% line and 80% branch coverage. System tests execute real user journeys in headless Chromium. CI also builds the production image, runs CodeQL, replants seeds, and rejects security or lint warnings. + +The latest full local execution and interactive production-browser results are recorded in [docs/qa-report.md](docs/qa-report.md). + +## Browser support + +The interface uses progressively enhanced server-rendered HTML, standard form controls, Turbo, and small Stimulus controllers. Rails' modern-browser policy is enabled, so unsupported legacy browsers receive the framework's compatibility response. The repeatable browser suite and the interactive desktop/mobile review use Chromium; the layout avoids browser-specific APIs and keeps JavaScript non-essential for authorization and persistence. + +## Security summary + +- Built-in Rails authentication with bcrypt and 12-character minimum passwords. +- Signed, HTTP-only, same-site session cookies; secure cookies on HTTPS; session reset on login; all sessions revoked after password reset. +- Central role authorization, explicit privilege-change endpoint, and strong structural parameters. +- CSRF protection, strict Content Security Policy with per-response nonces, host authorization, safe redirect validation, and login/reset rate limits. +- Parameterized user search with escaped wildcard input and default Rails HTML escaping. +- Extension, content type, size, row-count, HTTPS, and embedded-credential validation for external inputs. +- Database unique indexes, foreign keys, check constraints, and deterministic row locks around the last-admin invariant. +- Sensitive parameters, including spreadsheet row payloads, are filtered from logs. + +See [docs/security.md](docs/security.md) for the threat boundaries and production checklist. + +## Deployment with Kamal + +`config/deploy.yml` provides separate web/job roles, Thruster health checks, a PostgreSQL 17 accessory, persistent Active Storage, TLS termination, and registry configuration. + +```bash +cp .kamal/secrets.example .kamal/secrets +export KAMAL_WEB_HOST=server.example.com +export APP_HOST=users.example.com +export KAMAL_IMAGE=your-org/umanni-users +export KAMAL_REGISTRY_USERNAME=your-github-user +bin/kamal config +bin/kamal setup +``` + +Load values in `.kamal/secrets` from environment variables or a password manager. On multi-host deployments, replace local Active Storage with an object-storage service; the included named volume is intentionally scoped to a single-host evaluation deployment. + +## Trade-offs I made + +- I chose a modular monolith because transactions and authorization matter more here than independent service scaling. +- I used PostgreSQL-backed queue, cache, and cable adapters to avoid adding Redis to a challenge of this size. +- Imported users receive expiring password-setup links; I did not introduce a shared or default password. +- Uploaded avatars are durable Active Storage records. I deliberately do not fetch remote avatars on the server; the browser requests them without a referrer and falls back to initials when an image is unavailable. diff --git a/Rakefile b/Rakefile new file mode 100644 index 000000000..9a5ea7383 --- /dev/null +++ b/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative "config/application" + +Rails.application.load_tasks diff --git a/app/assets/builds/.keep b/app/assets/builds/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/assets/images/.keep b/app/assets/images/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/assets/stylesheets/application.css b/app/assets/stylesheets/application.css new file mode 100644 index 000000000..fe93333c0 --- /dev/null +++ b/app/assets/stylesheets/application.css @@ -0,0 +1,10 @@ +/* + * This is a manifest file that'll be compiled into application.css. + * + * With Propshaft, assets are served efficiently without preprocessing steps. You can still include + * application-wide styles in this file, but keep in mind that CSS precedence will follow the standard + * cascading order, meaning styles declared later in the document or manifest will override earlier ones, + * depending on specificity. + * + * Consider organizing styles into separate files for maintainability. + */ diff --git a/app/assets/tailwind/application.css b/app/assets/tailwind/application.css new file mode 100644 index 000000000..b5efd04c7 --- /dev/null +++ b/app/assets/tailwind/application.css @@ -0,0 +1,26 @@ +@import "tailwindcss"; + +@layer base { + html { + color-scheme: light; + } + + body { + font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + } + + progress::-webkit-progress-bar { + border-radius: 9999px; + background: #f1f5f9; + } + + progress::-webkit-progress-value { + border-radius: 9999px; + background: linear-gradient(to right, #6366f1, #7c3aed); + } + + progress::-moz-progress-bar { + border-radius: 9999px; + background: linear-gradient(to right, #6366f1, #7c3aed); + } +} diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb new file mode 100644 index 000000000..613882fbc --- /dev/null +++ b/app/channels/application_cable/connection.rb @@ -0,0 +1,17 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + identified_by :current_user + + def connect + set_current_user || reject_unauthorized_connection + end + + private + def set_current_user + if session = Session.find_by(id: cookies.signed[:session_id]) + self.current_user = session.user + Current.session = session + end + end + end +end diff --git a/app/controllers/admin/base_controller.rb b/app/controllers/admin/base_controller.rb new file mode 100644 index 000000000..ebc7a1fe1 --- /dev/null +++ b/app/controllers/admin/base_controller.rb @@ -0,0 +1,12 @@ +module Admin + class BaseController < ApplicationController + before_action :require_admin + + private + def require_admin + return if Current.user.admin? + + redirect_to profile_path, alert: "You are not authorized to access that page." + end + end +end diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb new file mode 100644 index 000000000..097e6142e --- /dev/null +++ b/app/controllers/admin/dashboard_controller.rb @@ -0,0 +1,8 @@ +module Admin + class DashboardController < BaseController + def show + @stats = Dashboard::Stats.call + @recent_imports = UserImport.recent_first.with_attached_spreadsheet.limit(5) + end + end +end diff --git a/app/controllers/admin/user_imports_controller.rb b/app/controllers/admin/user_imports_controller.rb new file mode 100644 index 000000000..3cbf25852 --- /dev/null +++ b/app/controllers/admin/user_imports_controller.rb @@ -0,0 +1,32 @@ +module Admin + class UserImportsController < BaseController + def index + @user_imports = UserImport.recent_first.with_attached_spreadsheet.includes(:created_by).limit(50) + end + + def new + @user_import = UserImport.new + end + + def create + @user_import = UserImport.new(created_by: Current.user, spreadsheet: import_params[:spreadsheet]) + + if @user_import.save + Imports::ProcessJob.perform_later(@user_import) + redirect_to admin_user_import_path(@user_import), notice: "Import queued for background processing." + else + render :new, status: :unprocessable_entity + end + end + + def show + @user_import = UserImport.with_attached_spreadsheet.includes(:created_by).find(params[:id]) + @failed_rows = @user_import.rows.failed.order(:row_number).limit(100) + end + + private + def import_params + params.expect(user_import: %i[ spreadsheet ]) + end + end +end diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb new file mode 100644 index 000000000..64ae9977f --- /dev/null +++ b/app/controllers/admin/users_controller.rb @@ -0,0 +1,71 @@ +module Admin + class UsersController < BaseController + before_action :set_user, only: %i[ edit update destroy toggle_role ] + + def index + @search = Users::Search.call(query: params[:query], page: params[:page]) + end + + def new + @user = User.new(role: :user) + end + + def create + @user = Users::Create.call(attributes: user_params, invite: true) + + if @user.persisted? + redirect_to admin_users_path, notice: "User created. Password setup instructions were queued." + else + render :new, status: :unprocessable_entity + end + end + + def edit + end + + def update + @user = Users::Update.call(user: @user, attributes: user_params) + + if @user.errors.empty? + redirect_to admin_users_path, notice: "User updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + user = Users::Destroy.call(user: @user) + + if user.destroyed? + if user == Current.user + terminate_session + redirect_to root_path, notice: "Your account was deleted.", status: :see_other + else + redirect_to admin_users_path, notice: "User deleted.", status: :see_other + end + else + redirect_to admin_users_path, alert: user.errors.full_messages.to_sentence + end + end + + def toggle_role + user = Users::ToggleRole.call(user: @user) + + if user.errors.empty? + destination = user == Current.user && user.user? ? profile_path : admin_users_path + redirect_to destination, notice: "Role changed to #{user.role}." + else + redirect_to admin_users_path, alert: user.errors.full_messages.to_sentence + end + end + + private + def set_user + @user = User.find(params[:id]) + end + + def user_params + params.expect(user: %i[ full_name email avatar_image avatar_image_url ]) + end + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 000000000..5f38f02f3 --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,8 @@ +class ApplicationController < ActionController::Base + include Authentication + # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. + allow_browser versions: :modern + + # Changes to the importmap will invalidate the etag for HTML responses + stale_when_importmap_changes +end diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb new file mode 100644 index 000000000..5d5d9ab90 --- /dev/null +++ b/app/controllers/concerns/authentication.rb @@ -0,0 +1,66 @@ +module Authentication + extend ActiveSupport::Concern + + included do + before_action :require_authentication + helper_method :authenticated? + end + + class_methods do + def allow_unauthenticated_access(**options) + skip_before_action :require_authentication, **options + end + end + + private + def authenticated? + resume_session + end + + def require_authentication + resume_session || request_authentication + end + + def resume_session + Current.session ||= find_session_by_cookie + end + + def find_session_by_cookie + Session.find_by(id: cookies.signed[:session_id]) if cookies.signed[:session_id] + end + + def request_authentication + session[:return_to_after_authenticating] = request.url + redirect_to new_session_path + end + + def after_authentication_url + stored_url = @return_to_after_authenticating || session.delete(:return_to_after_authenticating) + return stored_url if stored_url.present? && URI.parse(stored_url).host == request.host + + Current.user.admin? ? admin_root_url : profile_url + rescue URI::InvalidURIError + Current.user.admin? ? admin_root_url : profile_url + end + + def start_new_session_for(user) + @return_to_after_authenticating = session.delete(:return_to_after_authenticating) + reset_session + user.sessions.create!(user_agent: request.user_agent, ip_address: request.remote_ip).tap do |session| + Current.session = session + cookies.signed.permanent[:session_id] = { + value: session.id, + httponly: true, + same_site: :lax, + secure: request.ssl? + } + end + end + + def terminate_session + Current.session&.destroy + Current.reset + reset_session + cookies.delete(:session_id) + end +end diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb new file mode 100644 index 000000000..1f8e1f922 --- /dev/null +++ b/app/controllers/home_controller.rb @@ -0,0 +1,9 @@ +class HomeController < ApplicationController + allow_unauthenticated_access + + def show + return unless authenticated? + + redirect_to Current.user.admin? ? admin_root_path : profile_path + end +end diff --git a/app/controllers/passwords_controller.rb b/app/controllers/passwords_controller.rb new file mode 100644 index 000000000..cb13d4921 --- /dev/null +++ b/app/controllers/passwords_controller.rb @@ -0,0 +1,35 @@ +class PasswordsController < ApplicationController + allow_unauthenticated_access + before_action :set_user_by_token, only: %i[ edit update ] + rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_password_path, alert: "Try again later." } + + def new + end + + def create + if user = User.find_by(email: User.normalized_email(params.expect(:email))) + PasswordsMailer.reset(user).deliver_later + end + + redirect_to new_session_path, notice: "Password reset instructions sent (if user with that email address exists)." + end + + def edit + end + + def update + if @user.update(params.expect(user: %i[ password password_confirmation ])) + @user.sessions.destroy_all + redirect_to new_session_path, notice: "Password has been reset." + else + render :edit, status: :unprocessable_entity + end + end + + private + def set_user_by_token + @user = User.find_by_password_reset_token!(params[:token]) + rescue ActiveSupport::MessageVerifier::InvalidSignature + redirect_to new_password_path, alert: "Password reset link is invalid or has expired." + end +end diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb new file mode 100644 index 000000000..02659e59e --- /dev/null +++ b/app/controllers/profiles_controller.rb @@ -0,0 +1,35 @@ +class ProfilesController < ApplicationController + def show + @user = Current.user + end + + def edit + @user = Current.user + end + + def update + @user = Users::Update.call(user: Current.user, attributes: profile_params) + + if @user.errors.empty? + redirect_to profile_path, notice: "Your profile was updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + user = Users::Destroy.call(user: Current.user) + + if user.destroyed? + terminate_session + redirect_to root_path, notice: "Your account was deleted.", status: :see_other + else + redirect_to profile_path, alert: user.errors.full_messages.to_sentence + end + end + + private + def profile_params + params.expect(user: %i[ full_name email avatar_image avatar_image_url ]) + end +end diff --git a/app/controllers/registrations_controller.rb b/app/controllers/registrations_controller.rb new file mode 100644 index 000000000..d60dfb65a --- /dev/null +++ b/app/controllers/registrations_controller.rb @@ -0,0 +1,28 @@ +class RegistrationsController < ApplicationController + allow_unauthenticated_access only: %i[ new create ] + before_action :redirect_authenticated_user + + def new + @user = User.new + end + + def create + @user = Users::Create.call(attributes: registration_params.merge(role: :user)) + + if @user.persisted? + start_new_session_for(@user) + redirect_to profile_path, notice: "Welcome! Your account is ready." + else + render :new, status: :unprocessable_entity + end + end + + private + def registration_params + params.expect(user: %i[ full_name email avatar_image avatar_image_url password password_confirmation ]) + end + + def redirect_authenticated_user + redirect_to(Current.user.admin? ? admin_root_path : profile_path) if authenticated? + end +end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb new file mode 100644 index 000000000..187edeb29 --- /dev/null +++ b/app/controllers/sessions_controller.rb @@ -0,0 +1,30 @@ +class SessionsController < ApplicationController + allow_unauthenticated_access only: %i[ new create ] + before_action :redirect_authenticated_user, only: %i[ new create ] + rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_session_path, alert: "Try again later." } + + def new + end + + def create + email, password = params.expect(:email, :password) + email = User.normalized_email(email) + + if user = User.authenticate_by(email:, password:) + start_new_session_for user + redirect_to after_authentication_url + else + redirect_to new_session_path, alert: "The email or password is incorrect." + end + end + + def destroy + terminate_session + redirect_to root_path, notice: "You have been signed out.", status: :see_other + end + + private + def redirect_authenticated_user + redirect_to(Current.user.admin? ? admin_root_path : profile_path) if authenticated? + end +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 000000000..0f3385549 --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,29 @@ +module ApplicationHelper + def nav_link_classes(path) + base = "rounded-lg px-3 py-2 text-sm font-medium transition" + active = "bg-indigo-50 text-indigo-700" + inactive = "text-slate-600 hover:bg-slate-100 hover:text-slate-950" + "#{base} #{current_page?(path) ? active : inactive}" + end + + def field_classes + "mt-2 block w-full rounded-xl border border-slate-300 bg-white px-3.5 py-2.5 text-slate-950 shadow-sm outline-none transition placeholder:text-slate-400 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-100" + end + + def status_badge(status) + colors = { + "queued" => "bg-slate-100 text-slate-700", + "processing" => "bg-blue-100 text-blue-800", + "completed" => "bg-emerald-100 text-emerald-800", + "completed_with_errors" => "bg-amber-100 text-amber-800", + "failed" => "bg-rose-100 text-rose-800" + } + label = status.to_s.humanize + + tag.span(label, class: "inline-flex rounded-full px-2.5 py-1 text-xs font-semibold #{colors.fetch(status.to_s, colors['queued'])}") + end + + def import_creator_name(user_import) + user_import.created_by&.full_name || "Deleted user" + end +end diff --git a/app/javascript/application.js b/app/javascript/application.js new file mode 100644 index 000000000..0d7b49404 --- /dev/null +++ b/app/javascript/application.js @@ -0,0 +1,3 @@ +// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails +import "@hotwired/turbo-rails" +import "controllers" diff --git a/app/javascript/controllers/application.js b/app/javascript/controllers/application.js new file mode 100644 index 000000000..1213e85c7 --- /dev/null +++ b/app/javascript/controllers/application.js @@ -0,0 +1,9 @@ +import { Application } from "@hotwired/stimulus" + +const application = Application.start() + +// Configure Stimulus development experience +application.debug = false +window.Stimulus = application + +export { application } diff --git a/app/javascript/controllers/avatar_preview_controller.js b/app/javascript/controllers/avatar_preview_controller.js new file mode 100644 index 000000000..ba83c19f0 --- /dev/null +++ b/app/javascript/controllers/avatar_preview_controller.js @@ -0,0 +1,80 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + static targets = ["container", "file", "image", "message", "url"] + + disconnect() { + this.revokeObjectUrl() + } + + fileChanged() { + const file = this.fileTarget.files[0] + if (!file) { + this.fileTarget.setCustomValidity("") + this.revokeObjectUrl() + this.urlTarget.value.length > 0 ? this.urlChanged() : this.hidePreview() + return + } + + const validType = ["image/jpeg", "image/png", "image/webp"].includes(file.type) + const validSize = file.size <= 5 * 1024 * 1024 + this.fileTarget.setCustomValidity(validType && validSize ? "" : "Choose a JPEG, PNG, or WebP image smaller than 5 MB.") + if (!validType || !validSize) { + this.hidePreview() + return + } + + this.revokeObjectUrl() + this.objectUrl = URL.createObjectURL(file) + this.show(this.objectUrl, "Local image selected") + } + + urlChanged() { + if (this.urlTarget.value.length === 0) { + this.urlTarget.setCustomValidity("") + if (!this.fileTarget.files[0]) this.hidePreview() + return + } + + try { + const url = new URL(this.urlTarget.value) + const valid = url.protocol === "https:" && !url.username && !url.password + this.urlTarget.setCustomValidity(valid ? "" : "Use a public HTTPS URL without embedded credentials.") + if (valid && !this.fileTarget.files[0]) { + this.revokeObjectUrl() + this.show(url.href, "Remote image selected") + } else if (!valid) { + this.hidePreview() + } + } catch (_error) { + this.urlTarget.setCustomValidity("Enter a valid HTTPS URL.") + this.hidePreview() + } + } + + show(source, message) { + this.imageTarget.classList.remove("hidden") + this.imageTarget.src = source + this.messageTarget.textContent = message + this.containerTarget.classList.remove("hidden") + this.containerTarget.classList.add("flex") + } + + imageFailed() { + this.imageTarget.classList.add("hidden") + this.messageTarget.textContent = "Preview unavailable — verify that the image is public." + } + + hidePreview() { + this.containerTarget.classList.add("hidden") + this.containerTarget.classList.remove("flex") + this.imageTarget.removeAttribute("src") + } + + revokeObjectUrl() { + if (!this.objectUrl) return + + URL.revokeObjectURL(this.objectUrl) + this.objectUrl = null + } +} diff --git a/app/javascript/controllers/dismiss_controller.js b/app/javascript/controllers/dismiss_controller.js new file mode 100644 index 000000000..9d4172df6 --- /dev/null +++ b/app/javascript/controllers/dismiss_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + remove() { + this.element.remove() + } +} diff --git a/app/javascript/controllers/image_fallback_controller.js b/app/javascript/controllers/image_fallback_controller.js new file mode 100644 index 000000000..2c4468ec4 --- /dev/null +++ b/app/javascript/controllers/image_fallback_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + hide() { + this.element.remove() + } +} diff --git a/app/javascript/controllers/index.js b/app/javascript/controllers/index.js new file mode 100644 index 000000000..1156bf836 --- /dev/null +++ b/app/javascript/controllers/index.js @@ -0,0 +1,4 @@ +// Import and register all your controllers from the importmap via controllers/**/*_controller +import { application } from "controllers/application" +import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" +eagerLoadControllersFrom("controllers", application) diff --git a/app/javascript/controllers/password_visibility_controller.js b/app/javascript/controllers/password_visibility_controller.js new file mode 100644 index 000000000..c41ad2e7a --- /dev/null +++ b/app/javascript/controllers/password_visibility_controller.js @@ -0,0 +1,10 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + static targets = ["input"] + + toggle(event) { + const type = event.currentTarget.checked ? "text" : "password" + this.inputTargets.forEach((input) => { input.type = type }) + } +} diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 000000000..d394c3d10 --- /dev/null +++ b/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/app/jobs/dashboard/broadcast_stats_job.rb b/app/jobs/dashboard/broadcast_stats_job.rb new file mode 100644 index 000000000..bee505abb --- /dev/null +++ b/app/jobs/dashboard/broadcast_stats_job.rb @@ -0,0 +1,14 @@ +module Dashboard + class BroadcastStatsJob < ApplicationJob + queue_as :default + + def perform + Turbo::StreamsChannel.broadcast_replace_to( + "admin_dashboard", + target: "dashboard_stats", + partial: "admin/dashboard/stats", + locals: { stats: Stats.call } + ) + end + end +end diff --git a/app/jobs/imports/process_job.rb b/app/jobs/imports/process_job.rb new file mode 100644 index 000000000..f27cf8e7c --- /dev/null +++ b/app/jobs/imports/process_job.rb @@ -0,0 +1,58 @@ +module Imports + class ProcessJob < ApplicationJob + queue_as :imports + + retry_on StandardError, wait: :polynomially_longer, attempts: 3 + discard_on ActiveRecord::RecordNotFound + + after_discard do |job, error| + user_import = job.arguments.first + next unless user_import&.persisted? && !user_import.terminal? + + Rails.error.report(error, handled: true, severity: :error, context: { user_import_id: user_import.id }) + + user_import.update!( + status: :failed, + failure_message: "The import could not be completed after multiple attempts.", + finished_at: Time.current + ) + ProgressBroadcaster.call(user_import) + end + + def perform(user_import) + return if user_import.terminal? + + rows = SpreadsheetParser.call(user_import) + user_import.update!( + status: :processing, + total_rows: rows.length, + started_at: user_import.started_at || Time.current, + failure_message: nil + ) + ProgressBroadcaster.call(user_import) + + rows.each_with_index do |parsed_row, index| + import_row = user_import.rows.find_or_initialize_by(row_number: parsed_row.number) + import_row.payload = parsed_row.attributes + import_row.save! + RowProcessor.call(import_row) unless import_row.succeeded? + ProgressUpdater.call(user_import) + Dashboard::BroadcastStatsJob.perform_later if ((index + 1) % 25).zero? + end + + finalize(user_import) + rescue SpreadsheetParser::Error => error + user_import.update!(status: :failed, failure_message: error.message.truncate(500), finished_at: Time.current) + ProgressBroadcaster.call(user_import) + end + + private + def finalize(user_import) + user_import.reload + final_status = user_import.failed_rows.positive? ? :completed_with_errors : :completed + user_import.update!(status: final_status, finished_at: Time.current) + ProgressBroadcaster.call(user_import) + Dashboard::BroadcastStatsJob.perform_later + end + end +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 000000000..d9d619499 --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "Umanni Users " + layout "mailer" +end diff --git a/app/mailers/passwords_mailer.rb b/app/mailers/passwords_mailer.rb new file mode 100644 index 000000000..8bb9e4c63 --- /dev/null +++ b/app/mailers/passwords_mailer.rb @@ -0,0 +1,11 @@ +class PasswordsMailer < ApplicationMailer + def reset(user) + @user = user + mail subject: "Reset your Umanni Users password", to: user.email + end + + def invitation(user) + @user = user + mail subject: "Set up your Umanni Users account", to: user.email + end +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 000000000..b63caeb8a --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/app/models/concerns/.keep b/app/models/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/current.rb b/app/models/current.rb new file mode 100644 index 000000000..2bef56dad --- /dev/null +++ b/app/models/current.rb @@ -0,0 +1,4 @@ +class Current < ActiveSupport::CurrentAttributes + attribute :session + delegate :user, to: :session, allow_nil: true +end diff --git a/app/models/session.rb b/app/models/session.rb new file mode 100644 index 000000000..4f3fb1084 --- /dev/null +++ b/app/models/session.rb @@ -0,0 +1,6 @@ +class Session < ApplicationRecord + belongs_to :user + + validates :user_agent, length: { maximum: 1_000 }, allow_blank: true + validates :ip_address, length: { maximum: 45 }, allow_blank: true +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 000000000..2051bdee0 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,62 @@ +class User < ApplicationRecord + AVATAR_CONTENT_TYPES = %w[image/jpeg image/png image/webp].freeze + MAX_AVATAR_SIZE = 5.megabytes + MAX_AVATAR_URL_LENGTH = 2_048 + NORMALIZE_EMAIL = ->(value) { value.to_s.strip.downcase }.freeze + + has_secure_password + has_many :sessions, dependent: :destroy + has_many :created_imports, class_name: "UserImport", foreign_key: :created_by_id, + inverse_of: :created_by, dependent: :nullify + has_many :import_rows, class_name: "UserImportRow", dependent: :nullify + has_one_attached :avatar_image + + enum :role, { user: 0, admin: 1 }, default: :user, validate: true + + normalizes :email, with: NORMALIZE_EMAIL + normalizes :full_name, with: ->(name) { name.strip.gsub(/\s+/, " ") } + normalizes :avatar_image_url, with: ->(url) { url.strip.presence } + + validates :full_name, presence: true, length: { in: 2..100 } + validates :email, presence: true, length: { maximum: 254 }, + format: { with: URI::MailTo::EMAIL_REGEXP }, uniqueness: { case_sensitive: false } + validates :password, length: { minimum: 12 }, allow_nil: true + validates :avatar_image_url, length: { maximum: MAX_AVATAR_URL_LENGTH }, allow_blank: true + validate :avatar_source_present + validate :avatar_upload_is_safe + validate :remote_avatar_is_safe + + def initials + full_name.split.filter_map { |part| part[0] }.first(2).join.upcase + end + + def self.normalized_email(value) + NORMALIZE_EMAIL.call(value) + end + + private + def avatar_source_present + return if avatar_image.attached? || avatar_image_url.present? + + errors.add(:avatar_image, "or a remote avatar URL must be provided") + end + + def avatar_upload_is_safe + return unless avatar_image.attached? + + blob = avatar_image.blob + errors.add(:avatar_image, "must be a JPEG, PNG, or WebP image") unless AVATAR_CONTENT_TYPES.include?(blob.content_type) + errors.add(:avatar_image, "must be smaller than 5 MB") if blob.byte_size > MAX_AVATAR_SIZE + end + + def remote_avatar_is_safe + return if avatar_image_url.blank? + + uri = URI.parse(avatar_image_url) + return if uri.is_a?(URI::HTTPS) && uri.host.present? && uri.userinfo.blank? + + errors.add(:avatar_image_url, "must be a valid HTTPS URL without embedded credentials") + rescue URI::InvalidURIError + errors.add(:avatar_image_url, "must be a valid HTTPS URL") + end +end diff --git a/app/models/user_import.rb b/app/models/user_import.rb new file mode 100644 index 000000000..906da55ef --- /dev/null +++ b/app/models/user_import.rb @@ -0,0 +1,48 @@ +class UserImport < ApplicationRecord + MAX_FILE_SIZE = 5.megabytes + CONTENT_TYPES_BY_EXTENSION = { + ".csv" => %w[text/csv application/csv application/vnd.ms-excel].freeze, + ".xlsx" => %w[application/vnd.openxmlformats-officedocument.spreadsheetml.sheet].freeze + }.freeze + + belongs_to :created_by, class_name: "User", inverse_of: :created_imports, optional: true + has_many :rows, class_name: "UserImportRow", dependent: :destroy, inverse_of: :user_import + has_one_attached :spreadsheet + + enum :status, { + queued: 0, + processing: 1, + completed: 2, + completed_with_errors: 3, + failed: 4 + }, default: :queued, validate: true + + validates :spreadsheet, presence: true + validates :created_by, presence: true, on: :create + validate :spreadsheet_is_supported + + scope :recent_first, -> { order(created_at: :desc) } + + def progress_percentage + return 0 if total_rows.zero? + + ((processed_rows.to_f / total_rows) * 100).round.clamp(0, 100) + end + + def terminal? + completed? || completed_with_errors? || failed? + end + + private + def spreadsheet_is_supported + return unless spreadsheet.attached? + + extension = File.extname(spreadsheet.filename.to_s).downcase + supported_content_types = CONTENT_TYPES_BY_EXTENSION[extension] + errors.add(:spreadsheet, "must be a CSV or XLSX file") unless supported_content_types + unless supported_content_types&.include?(spreadsheet.blob.content_type) + errors.add(:spreadsheet, "content type does not match its extension") + end + errors.add(:spreadsheet, "must be smaller than 5 MB") if spreadsheet.blob.byte_size > MAX_FILE_SIZE + end +end diff --git a/app/models/user_import_row.rb b/app/models/user_import_row.rb new file mode 100644 index 000000000..47ec91451 --- /dev/null +++ b/app/models/user_import_row.rb @@ -0,0 +1,10 @@ +class UserImportRow < ApplicationRecord + belongs_to :user_import, inverse_of: :rows + belongs_to :user, optional: true + + enum :status, { pending: 0, succeeded: 1, failed: 2 }, default: :pending, validate: true + + validates :row_number, numericality: { only_integer: true, greater_than_or_equal_to: 2 }, + uniqueness: { scope: :user_import_id } + validates :payload, presence: true +end diff --git a/app/queries/dashboard/stats.rb b/app/queries/dashboard/stats.rb new file mode 100644 index 000000000..ba5feaca1 --- /dev/null +++ b/app/queries/dashboard/stats.rb @@ -0,0 +1,10 @@ +module Dashboard + class Stats + Result = Data.define(:total, :admins, :users) + + def self.call + counts = User.group(:role).count + Result.new(total: counts.values.sum, admins: counts.fetch("admin", 0), users: counts.fetch("user", 0)) + end + end +end diff --git a/app/queries/users/search.rb b/app/queries/users/search.rb new file mode 100644 index 000000000..f0b3913a2 --- /dev/null +++ b/app/queries/users/search.rb @@ -0,0 +1,34 @@ +module Users + class Search + PER_PAGE = 20 + Result = Data.define(:records, :query, :page, :total_pages, :total_count) + + def self.call(query:, page:) + new(query:, page:).call + end + + def initialize(query:, page:) + @query = query.to_s.strip + @page = [ page.to_i, 1 ].max + end + + def call + relation = User.with_attached_avatar_image.order(:full_name, :email) + relation = filter(relation) if query.present? + total_count = relation.count + total_pages = [ (total_count.to_f / PER_PAGE).ceil, 1 ].max + current_page = [ page, total_pages ].min + records = relation.offset((current_page - 1) * PER_PAGE).limit(PER_PAGE) + + Result.new(records:, query:, page: current_page, total_pages:, total_count:) + end + + private + attr_reader :query, :page + + def filter(relation) + term = "%#{ActiveRecord::Base.sanitize_sql_like(query)}%" + relation.where("full_name ILIKE :term OR email ILIKE :term", term:) + end + end +end diff --git a/app/services/imports/progress_broadcaster.rb b/app/services/imports/progress_broadcaster.rb new file mode 100644 index 000000000..dd66c5ff6 --- /dev/null +++ b/app/services/imports/progress_broadcaster.rb @@ -0,0 +1,18 @@ +module Imports + class ProgressBroadcaster + extend ActionView::RecordIdentifier + + def self.call(user_import) + Turbo::StreamsChannel.broadcast_replace_to( + user_import, + :progress, + target: dom_id(user_import, :progress), + partial: "admin/user_imports/progress", + locals: { + user_import:, + failed_rows: user_import.rows.failed.order(:row_number).limit(100) + } + ) + end + end +end diff --git a/app/services/imports/progress_updater.rb b/app/services/imports/progress_updater.rb new file mode 100644 index 000000000..2a1dae483 --- /dev/null +++ b/app/services/imports/progress_updater.rb @@ -0,0 +1,18 @@ +module Imports + class ProgressUpdater + def self.call(user_import) + counts = user_import.rows.group(:status).count + succeeded = counts.fetch("succeeded", 0) + failed = counts.fetch("failed", 0) + + user_import.update!( + processed_rows: succeeded + failed, + succeeded_rows: succeeded, + failed_rows: failed + ) + + ProgressBroadcaster.call(user_import) + user_import + end + end +end diff --git a/app/services/imports/row_processor.rb b/app/services/imports/row_processor.rb new file mode 100644 index 000000000..f76aff6be --- /dev/null +++ b/app/services/imports/row_processor.rb @@ -0,0 +1,55 @@ +module Imports + class RowProcessor + ROLE_MAP = { + "" => "user", + "user" => "user", + "no-admin" => "user", + "no_admin" => "user", + "false" => "user", + "0" => "user", + "admin" => "admin", + "true" => "admin", + "1" => "admin" + }.freeze + + def self.call(import_row, user_creator: Users::Create) + new(import_row, user_creator:).call + end + + def initialize(import_row, user_creator:) + @import_row = import_row + @user_creator = user_creator + end + + def call + role = ROLE_MAP[import_row.payload.fetch("role", "").downcase] + return fail_row("Role must be admin, user, or no-admin.") unless role + + UserImportRow.transaction do + user = user_creator.call( + attributes: import_row.payload.slice("full_name", "email", "avatar_image_url").merge("role" => role), + invite: true, + broadcast: false + ) + + if user.persisted? + import_row.update!(status: :succeeded, user:, error_message: nil) + else + fail_row(user.errors.full_messages.to_sentence) + end + end + + import_row + rescue ActiveRecord::RecordNotUnique + fail_row("Email has already been taken.") + end + + private + attr_reader :import_row, :user_creator + + def fail_row(message) + import_row.update!(status: :failed, user: nil, error_message: message.to_s.truncate(500)) + import_row + end + end +end diff --git a/app/services/imports/spreadsheet_parser.rb b/app/services/imports/spreadsheet_parser.rb new file mode 100644 index 000000000..722a85b21 --- /dev/null +++ b/app/services/imports/spreadsheet_parser.rb @@ -0,0 +1,105 @@ +require "csv" + +module Imports + class SpreadsheetParser + class Error < StandardError; end + + REQUIRED_HEADERS = %w[full_name email avatar_image_url].freeze + OPTIONAL_HEADERS = %w[role].freeze + MAX_ROWS = 1_000 + MAX_XLSX_ENTRIES = 1_000 + MAX_XLSX_UNCOMPRESSED_SIZE = 25.megabytes + Row = Data.define(:number, :attributes) + + def self.call(user_import) + new(user_import).call + end + + def initialize(user_import) + @user_import = user_import + end + + def call + user_import.spreadsheet.blob.open do |file| + extension = File.extname(user_import.spreadsheet.filename.to_s).downcase + rows = extension == ".csv" ? csv_rows(file.path) : xlsx_rows(file.path) + raise Error, "The spreadsheet must contain at least one data row." if rows.empty? + raise Error, "The spreadsheet cannot contain more than #{MAX_ROWS} data rows." if rows.length > MAX_ROWS + + rows + end + rescue CSV::MalformedCSVError, Roo::Error, Zip::Error + raise Error, "The spreadsheet could not be parsed. Verify the file format and try again." + end + + private + attr_reader :user_import + + def csv_rows(path) + table = CSV.read(path, headers: true, encoding: "bom|utf-8") + headers = normalized_headers(table.headers) + validate_headers!(headers) + + table.each_with_index.filter_map do |row, index| + attributes = row.to_h.transform_keys { |key| normalize_header(key) } + build_row(index + 2, attributes) unless blank_row?(attributes) + end + end + + def xlsx_rows(path) + validate_xlsx_archive!(path) + sheet = Roo::Excelx.new(path).sheet(0) + reject_oversized_sheet!(sheet) + headers = normalized_headers(sheet.row(1)) + validate_headers!(headers) + + (2..sheet.last_row).filter_map do |row_number| + attributes = headers.zip(sheet.row(row_number)).to_h + build_row(row_number, attributes) unless blank_row?(attributes) + end + end + + def validate_xlsx_archive!(path) + Zip::File.open(path) do |archive| + raise Error, "The XLSX archive contains too many entries." if archive.size > MAX_XLSX_ENTRIES + + uncompressed_size = archive.sum(&:size) + if uncompressed_size > MAX_XLSX_UNCOMPRESSED_SIZE + raise Error, "The XLSX archive expands beyond the 25 MB safety limit." + end + end + end + + def reject_oversized_sheet!(sheet) + return if sheet.last_row.to_i <= MAX_ROWS + 1 + + raise Error, "The spreadsheet cannot contain more than #{MAX_ROWS} data rows." + end + + def normalized_headers(headers) + headers.map { |header| normalize_header(header) } + end + + def normalize_header(header) + header.to_s.strip.downcase.tr(" -", "__").gsub(/_+/, "_") + end + + def validate_headers!(headers) + missing = REQUIRED_HEADERS - headers + return if missing.empty? + + raise Error, "Missing required columns: #{missing.join(', ')}." + end + + def blank_row?(attributes) + attributes.values.all? { |value| value.to_s.strip.blank? } + end + + def build_row(number, attributes) + allowed = attributes.slice(*(REQUIRED_HEADERS + OPTIONAL_HEADERS)) + .transform_values { |value| value.to_s.strip } + + Row.new(number:, attributes: allowed) + end + end +end diff --git a/app/services/users/create.rb b/app/services/users/create.rb new file mode 100644 index 000000000..0a0cdce3e --- /dev/null +++ b/app/services/users/create.rb @@ -0,0 +1,34 @@ +module Users + class Create + def self.call(attributes:, invite: false, broadcast: true) + new(attributes:, invite:, broadcast:).call + end + + def initialize(attributes:, invite:, broadcast:) + @attributes = attributes + @invite = invite + @broadcast = broadcast + end + + def call + user = User.new(attributes) + assign_random_password(user) if invite + + if user.save + Dashboard::BroadcastStatsJob.perform_later if broadcast + PasswordsMailer.invitation(user).deliver_later if invite + end + + user + end + + private + attr_reader :attributes, :invite, :broadcast + + def assign_random_password(user) + password = SecureRandom.base58(32) + user.password = password + user.password_confirmation = password + end + end +end diff --git a/app/services/users/destroy.rb b/app/services/users/destroy.rb new file mode 100644 index 000000000..6d9006662 --- /dev/null +++ b/app/services/users/destroy.rb @@ -0,0 +1,49 @@ +module Users + class Destroy + LAST_ADMIN_MESSAGE = "The last administrator cannot be deleted.".freeze + + def self.call(user:) + new(user:).call + end + + def initialize(user:) + @user = user + end + + def call + User.transaction do + lock_relevant_users! + return reject_last_admin if last_admin? + + user.destroy + end + + Dashboard::BroadcastStatsJob.perform_later if user.destroyed? + user + end + + private + attr_reader :user + + def last_admin? + user.admin? && @admin_ids.one? + end + + # Administrators are always locked in the same order. Besides protecting the + # invariant, this prevents two concurrent demotions/deletions from each + # holding a different administrator row and deadlocking on the other one. + def lock_relevant_users! + if user.admin? + @admin_ids = User.admin.order(:id).lock.pluck(:id) + else + user.lock! + @admin_ids = [] + end + end + + def reject_last_admin + user.errors.add(:base, LAST_ADMIN_MESSAGE) + user + end + end +end diff --git a/app/services/users/toggle_role.rb b/app/services/users/toggle_role.rb new file mode 100644 index 000000000..c435918e2 --- /dev/null +++ b/app/services/users/toggle_role.rb @@ -0,0 +1,46 @@ +module Users + class ToggleRole + LAST_ADMIN_MESSAGE = "The last administrator cannot be demoted.".freeze + + def self.call(user:) + new(user:).call + end + + def initialize(user:) + @user = user + end + + def call + User.transaction do + lock_relevant_users! + return reject_last_admin if last_admin? + + user.update(role: user.admin? ? :user : :admin) + end + + Dashboard::BroadcastStatsJob.perform_later if user.errors.empty? + user + end + + private + attr_reader :user + + def last_admin? + user.admin? && @admin_ids.one? + end + + def lock_relevant_users! + if user.admin? + @admin_ids = User.admin.order(:id).lock.pluck(:id) + else + user.lock! + @admin_ids = [] + end + end + + def reject_last_admin + user.errors.add(:base, LAST_ADMIN_MESSAGE) + user + end + end +end diff --git a/app/services/users/update.rb b/app/services/users/update.rb new file mode 100644 index 000000000..3d6383a73 --- /dev/null +++ b/app/services/users/update.rb @@ -0,0 +1,27 @@ +module Users + class Update + def self.call(user:, attributes:) + new(user:, attributes: attributes.to_h.symbolize_keys).call + end + + def initialize(user:, attributes:) + @user = user + @attributes = attributes + end + + def call + uploaded_avatar = attributes.delete(:avatar_image) + replace_attachment_with_url = uploaded_avatar.blank? && attributes[:avatar_image_url].present? && user.avatar_image.attached? + + user.assign_attributes(attributes) + user.avatar_image.attach(uploaded_avatar) if uploaded_avatar.present? + user.avatar_image_url = nil if uploaded_avatar.present? + + user.avatar_image.purge_later if user.save && replace_attachment_with_url + user + end + + private + attr_reader :user, :attributes + end +end diff --git a/app/views/admin/dashboard/_stats.html.erb b/app/views/admin/dashboard/_stats.html.erb new file mode 100644 index 000000000..068965987 --- /dev/null +++ b/app/views/admin/dashboard/_stats.html.erb @@ -0,0 +1,10 @@ +
+ <% [ [ "Total users", stats.total, "from-indigo-500 to-violet-600" ], [ "Administrators", stats.admins, "from-amber-500 to-orange-600" ], [ "Standard users", stats.users, "from-emerald-500 to-teal-600" ] ].each do |label, value, gradient| %> +
+ +

<%= label %>

+

<%= value %>

+

Updated in real time

+
+ <% end %> +
diff --git a/app/views/admin/dashboard/show.html.erb b/app/views/admin/dashboard/show.html.erb new file mode 100644 index 000000000..864af5e13 --- /dev/null +++ b/app/views/admin/dashboard/show.html.erb @@ -0,0 +1,48 @@ +<% content_for :title, "Admin dashboard ¡ Umanni Users" %> +<%= turbo_stream_from "admin_dashboard" %> + +
+
+
+

Administration

+

User dashboard

+

Live account totals and the latest background imports.

+
+
+ <%= link_to "Import spreadsheet", new_admin_user_import_path, class: "rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm transition hover:bg-slate-50" %> + <%= link_to "Add user", new_admin_user_path, class: "rounded-xl bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700" %> +
+
+ +
<%= render "stats", stats: @stats %>
+ +
+
+
+

Recent imports

+

The five most recent spreadsheet jobs

+
+ <%= link_to "View all", admin_user_imports_path, class: "text-sm font-semibold text-indigo-600 hover:text-indigo-800" %> +
+ <% if @recent_imports.any? %> +
    + <% @recent_imports.each do |user_import| %> +
  • + <%= link_to admin_user_import_path(user_import), class: "flex flex-wrap items-center justify-between gap-3 px-5 py-4 transition hover:bg-slate-50" do %> + + <%= user_import.spreadsheet.filename %> + <%= time_ago_in_words(user_import.created_at) %> ago + + + <%= status_badge(user_import.status) %> + <%= user_import.progress_percentage %>% + + <% end %> +
  • + <% end %> +
+ <% else %> +
No spreadsheets have been imported yet.
+ <% end %> +
+
diff --git a/app/views/admin/user_imports/_progress.html.erb b/app/views/admin/user_imports/_progress.html.erb new file mode 100644 index 000000000..7b789dd1a --- /dev/null +++ b/app/views/admin/user_imports/_progress.html.erb @@ -0,0 +1,63 @@ +
+
+
+
+

<%= user_import.spreadsheet.filename %>

+

+ Uploaded <%= time_ago_in_words(user_import.created_at) %> ago by <%= import_creator_name(user_import) %> +

+
+ <%= status_badge(user_import.status) %> +
+ + + <%= user_import.progress_percentage %>% + + +
+ <%= user_import.progress_percentage %>% complete + <%= user_import.processed_rows %> of <%= user_import.total_rows %> rows processed +
+ +
+
+ <%= user_import.total_rows %> + Total +
+
+ <%= user_import.succeeded_rows %> + Created +
+
+ <%= user_import.failed_rows %> + Failed +
+
+ + <% if user_import.failure_message.present? %> + + <% end %> +
+ + <% if failed_rows.any? %> +
+
+

Rows requiring attention

+

Up to the first 100 failures are shown.

+
+
    + <% failed_rows.each do |row| %> +
  • + Row <%= row.row_number %> + + <%= row.payload["email"] %> + <%= row.error_message %> + +
  • + <% end %> +
+
+ <% end %> +
diff --git a/app/views/admin/user_imports/index.html.erb b/app/views/admin/user_imports/index.html.erb new file mode 100644 index 000000000..e8cb83011 --- /dev/null +++ b/app/views/admin/user_imports/index.html.erb @@ -0,0 +1,34 @@ +<% content_for :title, "Imports ¡ Umanni Users" %> + +
+
+

Background processing

Spreadsheet imports

Audit every CSV and XLSX import, including row-level failures.

+ <%= link_to "New import", new_admin_user_import_path, class: "rounded-xl bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700" %> +
+ +
+ <% if @user_imports.any? %> +
    + <% @user_imports.each do |user_import| %> +
  • + <%= link_to admin_user_import_path(user_import), class: "grid gap-3 px-5 py-4 transition hover:bg-slate-50 sm:grid-cols-[1fr_auto_auto] sm:items-center" do %> + + <%= user_import.spreadsheet.filename %> + + Uploaded by <%= import_creator_name(user_import) %> ¡ <%= user_import.created_at.to_fs(:short) %> + + + <%= user_import.processed_rows %>/<%= user_import.total_rows %> rows + <%= status_badge(user_import.status) %> + <% end %> +
  • + <% end %> +
+ <% else %> +
+

No imports yet

+

Upload a CSV or XLSX template to create users asynchronously.

+
+ <% end %> +
+
diff --git a/app/views/admin/user_imports/new.html.erb b/app/views/admin/user_imports/new.html.erb new file mode 100644 index 000000000..0d4512b34 --- /dev/null +++ b/app/views/admin/user_imports/new.html.erb @@ -0,0 +1,36 @@ +<% content_for :title, "New import ¡ Umanni Users" %> + +
+
+

Background processing

+

Import users

+

The upload is validated immediately, then processed by Solid Queue. This page will update through Solid Cable.

+ <%= form_with model: [ :admin, @user_import ], class: "mt-7 space-y-5" do |form| %> + <%= render "shared/errors", record: @user_import %> +
+ <%= form.label :spreadsheet, "CSV or XLSX spreadsheet", class: "text-sm font-semibold text-slate-800" %> + <%= form.file_field :spreadsheet, required: true, accept: ".csv,.xlsx,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", class: "mt-2 block w-full rounded-xl border border-slate-300 bg-slate-50 px-3 py-3 text-sm file:mr-3 file:rounded-lg file:border-0 file:bg-indigo-100 file:px-3 file:py-2 file:font-semibold file:text-indigo-700 hover:file:bg-indigo-200" %> +

Maximum 5 MB and 1,000 data rows.

+
+
+ <%= link_to "Cancel", admin_user_imports_path, class: "rounded-xl px-4 py-2.5 text-sm font-semibold text-slate-600 hover:bg-slate-100" %> + <%= form.submit "Queue import", class: "cursor-pointer rounded-xl bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700" %> +
+ <% end %> +
+ + +
diff --git a/app/views/admin/user_imports/show.html.erb b/app/views/admin/user_imports/show.html.erb new file mode 100644 index 000000000..60e214054 --- /dev/null +++ b/app/views/admin/user_imports/show.html.erb @@ -0,0 +1,7 @@ +<% content_for :title, "Import #{@user_import.id} ¡ Umanni Users" %> +<%= turbo_stream_from @user_import, :progress %> + +
+

Import #<%= @user_import.id %>

Processing details

<%= link_to "All imports", admin_user_imports_path, class: "rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50" %>
+ <%= render "progress", user_import: @user_import, failed_rows: @failed_rows %> +
diff --git a/app/views/admin/users/_actions.html.erb b/app/views/admin/users/_actions.html.erb new file mode 100644 index 000000000..f08aeb380 --- /dev/null +++ b/app/views/admin/users/_actions.html.erb @@ -0,0 +1,7 @@ +<% action_class = local_assigns.fetch(:mobile, false) ? "rounded-lg px-3 py-2 text-xs" : "rounded-lg px-2.5 py-1.5" %> + +
+ <%= link_to "Edit", edit_admin_user_path(user), class: "#{action_class} font-semibold text-indigo-600 hover:bg-indigo-50" %> + <%= button_to user.admin? ? "Make user" : "Make admin", toggle_role_admin_user_path(user), method: :patch, class: "#{action_class} font-semibold text-slate-600 hover:bg-slate-100", form: { data: { turbo_confirm: "Change #{user.full_name}'s role?" } } %> + <%= button_to "Delete", admin_user_path(user), method: :delete, class: "#{action_class} font-semibold text-rose-600 hover:bg-rose-50", form: { data: { turbo_confirm: "Delete #{user.full_name}? This cannot be undone." } } %> +
diff --git a/app/views/admin/users/_form.html.erb b/app/views/admin/users/_form.html.erb new file mode 100644 index 000000000..b71875cac --- /dev/null +++ b/app/views/admin/users/_form.html.erb @@ -0,0 +1,10 @@ +<%= form_with model: [ :admin, user ], class: "mt-7" do |form| %> + <%= render "shared/user_fields", form:, user: %> +
+

New users receive a secure password setup email. Roles are changed separately from the users list to make privilege changes explicit.

+
+ <%= link_to "Cancel", admin_users_path, class: "rounded-xl px-4 py-2.5 text-sm font-semibold text-slate-600 hover:bg-slate-100" %> + <%= form.submit user.persisted? ? "Save user" : "Create user", class: "cursor-pointer rounded-xl bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700" %> +
+
+<% end %> diff --git a/app/views/admin/users/_user_card.html.erb b/app/views/admin/users/_user_card.html.erb new file mode 100644 index 000000000..b4600603f --- /dev/null +++ b/app/views/admin/users/_user_card.html.erb @@ -0,0 +1,13 @@ +
+
+ <%= render "shared/avatar", user:, size: "size-12" %> +
+

<%= user.full_name %>

+

<%= user.email %>

+
+ <%= user.role %> +
+
+ <%= render "actions", user:, mobile: true %> +
+
diff --git a/app/views/admin/users/_user_row.html.erb b/app/views/admin/users/_user_row.html.erb new file mode 100644 index 000000000..e909636aa --- /dev/null +++ b/app/views/admin/users/_user_row.html.erb @@ -0,0 +1,16 @@ + + +
+ <%= render "shared/avatar", user:, size: "size-11" %> + + <%= user.full_name %> + <%= user.email %> + +
+ + + <%= user.role %> + + <%= user.created_at.to_date.to_fs(:medium) %> + <%= render "actions", user:, mobile: false %> + diff --git a/app/views/admin/users/edit.html.erb b/app/views/admin/users/edit.html.erb new file mode 100644 index 000000000..35c03d1af --- /dev/null +++ b/app/views/admin/users/edit.html.erb @@ -0,0 +1,6 @@ +<% content_for :title, "Edit #{@user.full_name} ¡ Umanni Users" %> +
+

Administration

+

Edit <%= @user.full_name %>

+ <%= render "form", user: @user %> +
diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb new file mode 100644 index 000000000..446f22007 --- /dev/null +++ b/app/views/admin/users/index.html.erb @@ -0,0 +1,54 @@ +<% content_for :title, "Users ¡ Umanni Users" %> + +
+
+
+

Directory

+

Manage users

+

<%= pluralize(@search.total_count, "account") %> in this result.

+
+ <%= link_to "Add user", new_admin_user_path, class: "rounded-xl bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700" %> +
+ + <%= form_with url: admin_users_path, method: :get, class: "mt-6 flex gap-2", role: "search" do |form| %> + <%= form.search_field :query, value: @search.query, class: field_classes, placeholder: "Search by name or email", aria: { label: "Search users" } %> + <%= form.submit "Search", class: "mt-2 cursor-pointer rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50" %> + <% end %> + + + +
+ <%= render partial: "user_card", collection: @search.records, as: :user %> +
+ + <% if @search.records.none? %> +
+ No users match that search. +
+ <% end %> + + <% if @search.total_pages > 1 %> + + <% end %> +
diff --git a/app/views/admin/users/new.html.erb b/app/views/admin/users/new.html.erb new file mode 100644 index 000000000..139d87240 --- /dev/null +++ b/app/views/admin/users/new.html.erb @@ -0,0 +1,7 @@ +<% content_for :title, "Add user ¡ Umanni Users" %> +
+

Administration

+

Add a user

+

Create the profile now; password setup is delivered separately.

+ <%= render "form", user: @user %> +
diff --git a/app/views/home/show.html.erb b/app/views/home/show.html.erb new file mode 100644 index 000000000..882ea63b1 --- /dev/null +++ b/app/views/home/show.html.erb @@ -0,0 +1,26 @@ +<% content_for :title, "Umanni Users ¡ People operations" %> + +
+
+ Modern people operations +

User management that stays clear as your team grows.

+

A secure Rails workspace for profiles, roles, real-time reporting, and resilient spreadsheet imports—without Redis or unnecessary services.

+
+ <%= link_to "Create your account", new_registration_path, class: "rounded-xl bg-indigo-600 px-5 py-3 font-semibold text-white shadow-lg shadow-indigo-200 transition hover:-translate-y-0.5 hover:bg-indigo-700" %> + <%= link_to "Sign in", new_session_path, class: "rounded-xl border border-slate-300 bg-white px-5 py-3 font-semibold text-slate-800 shadow-sm transition hover:border-slate-400 hover:bg-slate-50" %> +
+
+ +
+
+
+

Operational snapshot

+

Everything important, live.

+
+
100%role visibility
+
Liveimport progress
+
Native Rails stack

Hotwire ¡ Solid Queue ¡ Solid Cable ¡ PostgreSQL

+
+
+
+
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 000000000..834e4e9e9 --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,67 @@ + + + + <%= content_for(:title) || "Umanni Users" %> + + + + + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= yield :head %> + + <%= tag.link rel: "manifest", href: pwa_manifest_path(format: :json) %> + + + + + + <%# Includes all stylesheet files in app/assets/stylesheets %> + <%= stylesheet_link_tag :app, "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + +
+
+ <%= link_to root_path, class: "flex items-center gap-3 rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-100", aria: { label: "Umanni Users home" } do %> + U + + Umanni Users + People operations + + <% end %> + + +
+
+ + <%= render "shared/flash" %> + +
+ <%= yield %> +
+ +
+
+ Built with Rails 8, Hotwire, Solid Queue, and Solid Cable. + Secure by default ¡ Responsive by design +
+
+ + diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 000000000..3aac9002e --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 000000000..37f0bddbd --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/app/views/passwords/edit.html.erb b/app/views/passwords/edit.html.erb new file mode 100644 index 000000000..2090a921b --- /dev/null +++ b/app/views/passwords/edit.html.erb @@ -0,0 +1,24 @@ +<% content_for :title, "Choose password ¡ Umanni Users" %> + +
+
+

Secure access

+

Choose a new password

+

Use at least 12 characters. All existing sessions will be revoked after the change.

+ <%= form_with url: password_path(params[:token]), method: :put, scope: :user, class: "mt-7 space-y-5", data: { controller: "password-visibility" } do |form| %> + <%= render "shared/errors", record: @user %> +
+ <%= form.label :password, "New password", class: "text-sm font-semibold text-slate-800" %> + <%= form.password_field :password, required: true, autofocus: true, minlength: 12, autocomplete: "new-password", class: field_classes, data: { password_visibility_target: "input" } %> +
+
+ <%= form.label :password_confirmation, class: "text-sm font-semibold text-slate-800" %> + <%= form.password_field :password_confirmation, required: true, minlength: 12, autocomplete: "new-password", class: field_classes, data: { password_visibility_target: "input" } %> +
+ + <%= form.submit "Update password", class: "w-full cursor-pointer rounded-xl bg-indigo-600 px-4 py-3 font-semibold text-white transition hover:bg-indigo-700 focus:outline-none focus:ring-4 focus:ring-indigo-100" %> + <% end %> +
+
diff --git a/app/views/passwords/new.html.erb b/app/views/passwords/new.html.erb new file mode 100644 index 000000000..941894890 --- /dev/null +++ b/app/views/passwords/new.html.erb @@ -0,0 +1,17 @@ +<% content_for :title, "Reset password ¡ Umanni Users" %> + +
+
+

Account recovery

+

Reset your password

+

If the email exists, we will send a secure link. The response never reveals whether an account is registered.

+ <%= form_with url: passwords_path, class: "mt-7 space-y-5" do |form| %> +
+ <%= form.label :email, class: "text-sm font-semibold text-slate-800" %> + <%= form.email_field :email, required: true, autofocus: true, autocomplete: "username", maxlength: 254, class: field_classes %> +
+ <%= form.submit "Send reset instructions", class: "w-full cursor-pointer rounded-xl bg-indigo-600 px-4 py-3 font-semibold text-white transition hover:bg-indigo-700 focus:outline-none focus:ring-4 focus:ring-indigo-100" %> + <% end %> + <%= link_to "Back to sign in", new_session_path, class: "mt-5 block text-center text-sm font-semibold text-indigo-600 hover:text-indigo-800" %> +
+
diff --git a/app/views/passwords_mailer/invitation.html.erb b/app/views/passwords_mailer/invitation.html.erb new file mode 100644 index 000000000..9ba640fde --- /dev/null +++ b/app/views/passwords_mailer/invitation.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @user.full_name %>,

+ +

An administrator created an Umanni Users account for you.

+ +

<%= link_to "Set up your password", edit_password_url(@user.password_reset_token) %>.

+ +

This secure link expires in <%= distance_of_time_in_words(0, @user.password_reset_token_expires_in) %>.

diff --git a/app/views/passwords_mailer/invitation.text.erb b/app/views/passwords_mailer/invitation.text.erb new file mode 100644 index 000000000..b88176171 --- /dev/null +++ b/app/views/passwords_mailer/invitation.text.erb @@ -0,0 +1,8 @@ +Hello <%= @user.full_name %>, + +An administrator created an Umanni Users account for you. + +Set up your password: +<%= edit_password_url(@user.password_reset_token) %> + +This secure link expires in <%= distance_of_time_in_words(0, @user.password_reset_token_expires_in) %>. diff --git a/app/views/passwords_mailer/reset.html.erb b/app/views/passwords_mailer/reset.html.erb new file mode 100644 index 000000000..ab67e9df4 --- /dev/null +++ b/app/views/passwords_mailer/reset.html.erb @@ -0,0 +1,5 @@ +

Hello <%= @user.full_name %>,

+ +

<%= link_to "Reset your password", edit_password_url(@user.password_reset_token) %>.

+ +

This secure link expires in <%= distance_of_time_in_words(0, @user.password_reset_token_expires_in) %>.

diff --git a/app/views/passwords_mailer/reset.text.erb b/app/views/passwords_mailer/reset.text.erb new file mode 100644 index 000000000..eb1bd5345 --- /dev/null +++ b/app/views/passwords_mailer/reset.text.erb @@ -0,0 +1,6 @@ +Hello <%= @user.full_name %>, + +Reset your password: +<%= edit_password_url(@user.password_reset_token) %> + +This link will expire in <%= distance_of_time_in_words(0, @user.password_reset_token_expires_in) %>. diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb new file mode 100644 index 000000000..7fc7c7732 --- /dev/null +++ b/app/views/profiles/edit.html.erb @@ -0,0 +1,15 @@ +<% content_for :title, "Edit profile ¡ Umanni Users" %> + +
+
+

Personal settings

+

Edit your profile

+ <%= form_with model: @user, url: profile_path, class: "mt-7" do |form| %> + <%= render "shared/user_fields", form:, user: @user %> +
+ <%= link_to "Cancel", profile_path, class: "rounded-xl px-4 py-2.5 text-sm font-semibold text-slate-600 hover:bg-slate-100" %> + <%= form.submit "Save profile", class: "cursor-pointer rounded-xl bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700" %> +
+ <% end %> +
+
diff --git a/app/views/profiles/show.html.erb b/app/views/profiles/show.html.erb new file mode 100644 index 000000000..442110f89 --- /dev/null +++ b/app/views/profiles/show.html.erb @@ -0,0 +1,24 @@ +<% content_for :title, "My profile ¡ Umanni Users" %> + +
+
+
+
+
+
<%= render "shared/avatar", user: @user, size: "size-24" %>
+ <%= link_to "Edit profile", edit_profile_path, class: "rounded-xl bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-700" %> +
+

<%= @user.full_name %>

+

<%= @user.email %>

+
+ <%= @user.role %> + Member since <%= @user.created_at.to_date.to_fs(:long) %> +
+
+
+
+

Delete account

+

This permanently removes your profile and signs out every active session. The last administrator is protected from deletion.

+ <%= button_to "Delete my account", profile_path, method: :delete, class: "mt-4 rounded-xl border border-rose-300 bg-white px-4 py-2.5 text-sm font-semibold text-rose-700 transition hover:bg-rose-100", form: { data: { turbo_confirm: "Delete your account permanently? This cannot be undone." } } %> +
+
diff --git a/app/views/pwa/manifest.json.erb b/app/views/pwa/manifest.json.erb new file mode 100644 index 000000000..1d1a490bf --- /dev/null +++ b/app/views/pwa/manifest.json.erb @@ -0,0 +1,22 @@ +{ + "name": "Umanni Users", + "icons": [ + { + "src": "/icon.png", + "type": "image/png", + "sizes": "512x512" + }, + { + "src": "/icon.png", + "type": "image/png", + "sizes": "512x512", + "purpose": "maskable" + } + ], + "start_url": "/", + "display": "standalone", + "scope": "/", + "description": "Secure, real-time user management.", + "theme_color": "#4f46e5", + "background_color": "#f8fafc" +} diff --git a/app/views/pwa/service-worker.js b/app/views/pwa/service-worker.js new file mode 100644 index 000000000..b3a13fb7b --- /dev/null +++ b/app/views/pwa/service-worker.js @@ -0,0 +1,26 @@ +// Add a service worker for processing Web Push notifications: +// +// self.addEventListener("push", async (event) => { +// const { title, options } = await event.data.json() +// event.waitUntil(self.registration.showNotification(title, options)) +// }) +// +// self.addEventListener("notificationclick", function(event) { +// event.notification.close() +// event.waitUntil( +// clients.matchAll({ type: "window" }).then((clientList) => { +// for (let i = 0; i < clientList.length; i++) { +// let client = clientList[i] +// let clientPath = (new URL(client.url)).pathname +// +// if (clientPath == event.notification.data.path && "focus" in client) { +// return client.focus() +// } +// } +// +// if (clients.openWindow) { +// return clients.openWindow(event.notification.data.path) +// } +// }) +// ) +// }) diff --git a/app/views/registrations/new.html.erb b/app/views/registrations/new.html.erb new file mode 100644 index 000000000..69d636093 --- /dev/null +++ b/app/views/registrations/new.html.erb @@ -0,0 +1,16 @@ +<% content_for :title, "Create account ¡ Umanni Users" %> + +
+
+

Join the workspace

+

Create your user profile

+

Self-registered accounts always start with the standard user role.

+ <%= form_with model: @user, url: registration_path, class: "mt-7" do |form| %> + <%= render "shared/user_fields", form:, user: @user, include_password: true %> +
+ <%= link_to "Already registered? Sign in", new_session_path, class: "text-sm font-semibold text-indigo-600 hover:text-indigo-800" %> + <%= form.submit "Create account", class: "cursor-pointer rounded-xl bg-indigo-600 px-5 py-3 font-semibold text-white shadow-lg shadow-indigo-200 transition hover:bg-indigo-700 focus:outline-none focus:ring-4 focus:ring-indigo-100" %> +
+ <% end %> +
+
diff --git a/app/views/sessions/new.html.erb b/app/views/sessions/new.html.erb new file mode 100644 index 000000000..a18e53702 --- /dev/null +++ b/app/views/sessions/new.html.erb @@ -0,0 +1,27 @@ +<% content_for :title, "Sign in ¡ Umanni Users" %> + +
+
+

Welcome back

+

Sign in to your workspace

+

Use the email and password associated with your account.

+ <%= form_with url: session_path, class: "mt-7 space-y-5" do |form| %> +
+ <%= form.label :email, class: "text-sm font-semibold text-slate-800" %> + <%= form.email_field :email, required: true, autofocus: true, autocomplete: "username", maxlength: 254, class: field_classes, placeholder: "you@example.com" %> +
+
+
+ <%= form.label :password, class: "text-sm font-semibold text-slate-800" %> + <%= link_to "Forgot password?", new_password_path, class: "text-sm font-semibold text-indigo-600 hover:text-indigo-800" %> +
+ <%= form.password_field :password, required: true, autocomplete: "current-password", maxlength: 72, class: field_classes, data: { password_visibility_target: "input" } %> + +
+ <%= form.submit "Sign in", class: "w-full cursor-pointer rounded-xl bg-indigo-600 px-4 py-3 font-semibold text-white shadow-lg shadow-indigo-200 transition hover:bg-indigo-700 focus:outline-none focus:ring-4 focus:ring-indigo-100" %> + <% end %> +

New here? <%= link_to "Create an account", new_registration_path, class: "font-semibold text-indigo-600 hover:text-indigo-800" %>

+
+
diff --git a/app/views/shared/_avatar.html.erb b/app/views/shared/_avatar.html.erb new file mode 100644 index 000000000..9695dd36e --- /dev/null +++ b/app/views/shared/_avatar.html.erb @@ -0,0 +1,14 @@ +<% size_classes = local_assigns.fetch(:size, "size-12") %> +<% if user.avatar_image.attached? %> + + + <%= image_tag user.avatar_image, class: "absolute inset-0 size-full rounded-2xl object-cover ring-1 ring-slate-200", alt: "#{user.full_name}'s avatar", data: { controller: "image-fallback", action: "error->image-fallback#hide" } %> + +<% elsif user.avatar_image_url.present? %> + + + <%= image_tag user.avatar_image_url, class: "absolute inset-0 size-full rounded-2xl object-cover ring-1 ring-slate-200", alt: "#{user.full_name}'s avatar", loading: "lazy", referrerpolicy: "no-referrer", data: { controller: "image-fallback", action: "error->image-fallback#hide" } %> + +<% else %> + <%= user.initials %> +<% end %> diff --git a/app/views/shared/_errors.html.erb b/app/views/shared/_errors.html.erb new file mode 100644 index 000000000..70fcbd3b2 --- /dev/null +++ b/app/views/shared/_errors.html.erb @@ -0,0 +1,10 @@ +<% if record.errors.any? %> + +<% end %> diff --git a/app/views/shared/_flash.html.erb b/app/views/shared/_flash.html.erb new file mode 100644 index 000000000..0c7a3b2b7 --- /dev/null +++ b/app/views/shared/_flash.html.erb @@ -0,0 +1,9 @@ +
+ <% flash.each do |type, message| %> + <% colors = type.to_s == "alert" ? "border-rose-200 bg-rose-50 text-rose-900" : "border-emerald-200 bg-emerald-50 text-emerald-900" %> +
+

<%= message %>

+ +
+ <% end %> +
diff --git a/app/views/shared/_user_fields.html.erb b/app/views/shared/_user_fields.html.erb new file mode 100644 index 000000000..9864131f8 --- /dev/null +++ b/app/views/shared/_user_fields.html.erb @@ -0,0 +1,49 @@ +
+ <%= render "shared/errors", record: user %> + +
+ <%= form.label :full_name, class: "text-sm font-semibold text-slate-800" %> + <%= form.text_field :full_name, required: true, minlength: 2, maxlength: 100, autocomplete: "name", class: field_classes, placeholder: "Ada Lovelace" %> +
+ +
+ <%= form.label :email, class: "text-sm font-semibold text-slate-800" %> + <%= form.email_field :email, required: true, maxlength: 254, autocomplete: "email", class: field_classes, placeholder: "ada@example.com" %> +
+ + <% if local_assigns.fetch(:include_password, false) %> +
+
+ <%= form.label :password, class: "text-sm font-semibold text-slate-800" %> + <%= form.password_field :password, required: true, minlength: 12, autocomplete: "new-password", class: field_classes, data: { password_visibility_target: "input" } %> +
+
+ <%= form.label :password_confirmation, class: "text-sm font-semibold text-slate-800" %> + <%= form.password_field :password_confirmation, required: true, minlength: 12, autocomplete: "new-password", class: field_classes, data: { password_visibility_target: "input" } %> +
+ +
+ <% end %> + +
+ Avatar +

Upload a JPEG, PNG, or WebP up to 5 MB, or provide a public HTTPS image URL. A new upload takes precedence.

+ +
+
+ <%= form.label :avatar_image, "Upload image", class: "text-sm font-semibold text-slate-800" %> + <%= form.file_field :avatar_image, accept: User::AVATAR_CONTENT_TYPES.join(","), class: "mt-2 block w-full rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm file:mr-3 file:rounded-lg file:border-0 file:bg-indigo-50 file:px-3 file:py-2 file:font-semibold file:text-indigo-700 hover:file:bg-indigo-100", data: { action: "avatar-preview#fileChanged", avatar_preview_target: "file" } %> +
+
+ <%= form.label :avatar_image_url, "Remote image URL", class: "text-sm font-semibold text-slate-800" %> + <%= form.url_field :avatar_image_url, pattern: "https://.*", maxlength: User::MAX_AVATAR_URL_LENGTH, class: field_classes, placeholder: "https://example.com/avatar.jpg", data: { action: "input->avatar-preview#urlChanged", avatar_preview_target: "url" } %> +
+
+
+
diff --git a/bin/brakeman b/bin/brakeman new file mode 100755 index 000000000..ace1c9ba0 --- /dev/null +++ b/bin/brakeman @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +ARGV.unshift("--ensure-latest") + +load Gem.bin_path("brakeman", "brakeman") diff --git a/bin/bundler-audit b/bin/bundler-audit new file mode 100755 index 000000000..e2ef22690 --- /dev/null +++ b/bin/bundler-audit @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "bundler/audit/cli" + +ARGV.concat %w[ --config config/bundler-audit.yml ] if ARGV.empty? || ARGV.include?("check") +Bundler::Audit::CLI.start diff --git a/bin/ci b/bin/ci new file mode 100755 index 000000000..4137ad5bb --- /dev/null +++ b/bin/ci @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "active_support/continuous_integration" + +CI = ActiveSupport::ContinuousIntegration +require_relative "../config/ci.rb" diff --git a/bin/dev b/bin/dev new file mode 100755 index 000000000..ad72c7d53 --- /dev/null +++ b/bin/dev @@ -0,0 +1,16 @@ +#!/usr/bin/env sh + +if ! gem list foreman -i --silent; then + echo "Installing foreman..." + gem install foreman +fi + +# Default to port 3000 if not specified +export PORT="${PORT:-3000}" + +# Let the debug gem allow remote connections, +# but avoid loading until `debugger` is called +export RUBY_DEBUG_OPEN="true" +export RUBY_DEBUG_LAZY="true" + +exec foreman start -f Procfile.dev "$@" diff --git a/bin/docker-entrypoint b/bin/docker-entrypoint new file mode 100755 index 000000000..ed31659f4 --- /dev/null +++ b/bin/docker-entrypoint @@ -0,0 +1,8 @@ +#!/bin/bash -e + +# If running the rails server then create or migrate existing database +if [ "${@: -2:1}" == "./bin/rails" ] && [ "${@: -1:1}" == "server" ]; then + ./bin/rails db:prepare +fi + +exec "${@}" diff --git a/bin/importmap b/bin/importmap new file mode 100755 index 000000000..36502ab16 --- /dev/null +++ b/bin/importmap @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby + +require_relative "../config/application" +require "importmap/commands" diff --git a/bin/jobs b/bin/jobs new file mode 100755 index 000000000..dcf59f309 --- /dev/null +++ b/bin/jobs @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby + +require_relative "../config/environment" +require "solid_queue/cli" + +SolidQueue::Cli.start(ARGV) diff --git a/bin/kamal b/bin/kamal new file mode 100755 index 000000000..d9ba27670 --- /dev/null +++ b/bin/kamal @@ -0,0 +1,16 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'kamal' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("kamal", "kamal") diff --git a/bin/rails b/bin/rails new file mode 100755 index 000000000..efc037749 --- /dev/null +++ b/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/bin/rake b/bin/rake new file mode 100755 index 000000000..4fbf10b96 --- /dev/null +++ b/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/bin/rubocop b/bin/rubocop new file mode 100755 index 000000000..5a2050471 --- /dev/null +++ b/bin/rubocop @@ -0,0 +1,8 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +# Explicit RuboCop config increases performance slightly while avoiding config confusion. +ARGV.unshift("--config", File.expand_path("../.rubocop.yml", __dir__)) + +load Gem.bin_path("rubocop", "rubocop") diff --git a/bin/setup b/bin/setup new file mode 100755 index 000000000..81be011e8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,35 @@ +#!/usr/bin/env ruby +require "fileutils" + +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args, exception: true) +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system("bundle check") || system!("bundle install") + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + system! "bin/rails db:reset" if ARGV.include?("--reset") + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + unless ARGV.include?("--skip-server") + puts "\n== Starting development server ==" + STDOUT.flush # flush the output before exec(2) so that it displays + exec "bin/dev" + end +end diff --git a/bin/thrust b/bin/thrust new file mode 100755 index 000000000..36bde2d83 --- /dev/null +++ b/bin/thrust @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("thruster", "thrust") diff --git a/compose.yml b/compose.yml new file mode 100644 index 000000000..2beb3e91b --- /dev/null +++ b/compose.yml @@ -0,0 +1,87 @@ +name: umanni-users + +x-app: &app + build: + context: . + args: + RUBY_VERSION: 4.0.6 + environment: &app-environment + RAILS_ENV: production + DB_HOST: database + DB_PORT: 5432 + DB_USERNAME: ${DB_USERNAME:-postgres} + DB_PASSWORD: ${DB_PASSWORD:-postgres} + SECRET_KEY_BASE: ${SECRET_KEY_BASE:-local-compose-secret-key-base-that-must-never-be-used-in-production} + APP_HOST: ${APP_HOST:-localhost} + APP_PROTOCOL: ${APP_PROTOCOL:-http} + depends_on: + database: + condition: service_healthy + volumes: + - storage:/rails/storage + +services: + database: + image: postgres:17-alpine + environment: + POSTGRES_USER: ${DB_USERNAME:-postgres} + POSTGRES_PASSWORD: ${DB_PASSWORD:-postgres} + healthcheck: + test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\""] + interval: 5s + timeout: 5s + retries: 10 + volumes: + - postgres:/var/lib/postgresql/data + + setup: + <<: *app + command: ["./bin/rails", "db:prepare"] + + web: + <<: *app + depends_on: + setup: + condition: service_completed_successfully + ports: + - "3000:80" + + jobs: + <<: *app + command: ["./bin/jobs"] + depends_on: + setup: + condition: service_completed_successfully + healthcheck: + disable: true + + test: + profiles: ["tools"] + build: + context: . + target: development + args: + RUBY_VERSION: 4.0.6 + environment: + RAILS_ENV: test + DB_HOST: database + DB_PORT: 5432 + DB_USERNAME: ${DB_USERNAME:-postgres} + DB_PASSWORD: ${DB_PASSWORD:-postgres} + CHROME_BIN: /usr/bin/chromium + depends_on: + database: + condition: service_healthy + volumes: + - .:/rails + command: ["./bin/ci"] + +volumes: + postgres: + storage: + +networks: + default: + ipam: + config: + - subnet: ${DOCKER_SUBNET:-198.18.113.0/24} diff --git a/config.ru b/config.ru new file mode 100644 index 000000000..4a3c09a68 --- /dev/null +++ b/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative "config/environment" + +run Rails.application +Rails.application.load_server diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 000000000..2e12b06e7 --- /dev/null +++ b/config/application.rb @@ -0,0 +1,31 @@ +require_relative "boot" + +require "rails/all" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module UmanniUsers + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 8.1 + + # Please, add to the `ignore` list any other `lib` subdirectories that do + # not contain `.rb` files, or that should not be reloaded or eager loaded. + # Common ones are `templates`, `generators`, or `middleware`, for example. + config.autoload_lib(ignore: %w[assets tasks]) + + config.time_zone = "UTC" + config.active_record.default_timezone = :utc + config.generators.system_tests = :test_unit + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 000000000..988a5ddc4 --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,4 @@ +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "bundler/setup" # Set up gems listed in the Gemfile. +require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/config/bundler-audit.yml b/config/bundler-audit.yml new file mode 100644 index 000000000..e74b3af94 --- /dev/null +++ b/config/bundler-audit.yml @@ -0,0 +1,5 @@ +# Audit all gems listed in the Gemfile for known security problems by running bin/bundler-audit. +# CVEs that are not relevant to the application can be enumerated on the ignore list below. + +ignore: + - CVE-THAT-DOES-NOT-APPLY diff --git a/config/cable.yml b/config/cable.yml new file mode 100644 index 000000000..7866c8d15 --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,22 @@ +# Async adapter only works within the same process, so for manually triggering cable updates from a console, +# and seeing results in the browser, you must do so from the web console (running inside the dev process), +# not a terminal started via bin/rails console! Add "console" to any action or any ERB template view +# to make the web console appear. +development: + adapter: solid_cable + connects_to: + database: + writing: cable + polling_interval: 0.1.seconds + message_retention: 1.day + +test: + adapter: test + +production: + adapter: solid_cable + connects_to: + database: + writing: cable + polling_interval: 0.1.seconds + message_retention: 1.day diff --git a/config/cache.yml b/config/cache.yml new file mode 100644 index 000000000..19d490843 --- /dev/null +++ b/config/cache.yml @@ -0,0 +1,16 @@ +default: &default + store_options: + # Cap age of oldest cache entry to fulfill retention policies + # max_age: <%= 60.days.to_i %> + max_size: <%= 256.megabytes %> + namespace: <%= Rails.env %> + +development: + <<: *default + +test: + <<: *default + +production: + database: cache + <<: *default diff --git a/config/ci.rb b/config/ci.rb new file mode 100644 index 000000000..c8e9ebc12 --- /dev/null +++ b/config/ci.rb @@ -0,0 +1,23 @@ +# Run using bin/ci + +CI.run do + step "Setup", "bin/setup --skip-server" + + step "Style: Ruby", "bin/rubocop" + + step "Security: Gem audit", "bin/bundler-audit" + step "Security: Importmap vulnerability audit", "bin/importmap audit" + step "Security: Brakeman code analysis", "bin/brakeman --quiet --no-pager --exit-on-warn --exit-on-error" + step "Code loading: Zeitwerk", "bin/rails zeitwerk:check" + step "Tests: Rails", "bin/rails test" + step "Tests: System", "bin/rails test:system" + step "Tests: Seeds", "env RAILS_ENV=test bin/rails db:seed:replant" + + # Optional: set a green GitHub commit status to unblock PR merge. + # Requires the `gh` CLI and `gh extension install basecamp/gh-signoff`. + # if success? + # step "Signoff: All systems go. Ready for merge and deploy.", "gh signoff" + # else + # failure "Signoff: CI failed. Do not merge or deploy.", "Fix the issues and try again." + # end +end diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 000000000..e9dc81e2d --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +D4sTAFpVeRpn9pSrj+OEuQU/pOkH/OKLhDlvLUOdLvO0akfia3nfcmAk6CBFWIyS85mMfoXvGTl6Uw5/9zoG/Wca/n/k3Cn/mo2MAkOiVo0rol9UjQv4UwcJLAvgnTZOPBkaUFco2oQa3yX/qptpQAHRJvuisqzf0J1IwM9nC7AiCxB1TX7+bzwTwf84vyK3iFbHJ/FCoiRkDzvZOXuUnz/i86Z82Iihr6NCBnO6g/kpfGngNlMpnjxqlQt99DpVsaqyRQlEZomhhGhoDs9OGUilDMNoVRRRAETFWQIJsuv3lYduD2pa2Cz1rloIGpQM7vSkuV2w03bIW/+BCl9jclEm3fxGilnhCXGQNX2Epykj9lMPM519N01T6XIB8JXSviYYcsJJBpP1dliGhW09ILlelzwDuBhai8MfB8E5wTkq0sJIknaBRapdFeIwbRBxlgiVTPNrlyaMW09UzekdAnlng7p+fURWAjuSqe88TbpYLV99F7+QDHk+--d455Fjw/khxDzfcP--htMbdkpFesew9zigHwriWQ== \ No newline at end of file diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 000000000..9d36caac6 --- /dev/null +++ b/config/database.yml @@ -0,0 +1,119 @@ +# PostgreSQL. Versions 9.5 and up are supported. +# +# Install the pg driver: +# gem install pg +# On macOS with Homebrew: +# gem install pg -- --with-pg-config=/opt/homebrew/bin/pg_config +# On Windows: +# gem install pg +# Choose the win32 build. +# Install PostgreSQL and put its /bin directory on your path. +# +# Configure Using Gemfile +# gem "pg" +# +default: &default + adapter: postgresql + encoding: unicode + # For details on connection pooling, see Rails configuration guide + # https://guides.rubyonrails.org/configuring.html#database-pooling + max_connections: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + host: <%= ENV["DB_HOST"] %> + port: <%= ENV.fetch("DB_PORT", 5432) %> + username: <%= ENV["DB_USERNAME"] %> + password: <%= ENV["DB_PASSWORD"] %> + + +development: + primary: &primary_development + <<: *default + database: umanni_users_development + cache: + <<: *primary_development + database: umanni_users_development_cache + migrations_paths: db/cache_migrate + queue: + <<: *primary_development + database: umanni_users_development_queue + migrations_paths: db/queue_migrate + cable: + <<: *primary_development + database: umanni_users_development_cable + migrations_paths: db/cable_migrate + + # The specified database role being used to connect to PostgreSQL. + # To create additional roles in PostgreSQL see `$ createuser --help`. + # When left blank, PostgreSQL will use the default role. This is + # the same name as the operating system user running Rails. + #username: app + + # The password associated with the PostgreSQL role (username). + #password: + + # Connect on a TCP socket. Omitted by default since the client uses a + # domain socket that doesn't need configuration. Windows does not have + # domain sockets, so uncomment these lines. + #host: localhost + + # The TCP port the server listens on. Defaults to 5432. + # If your server runs on a different port number, change accordingly. + #port: 5432 + + # Schema search path. The server defaults to $user,public + #schema_search_path: myapp,sharedapp,public + + # Minimum log levels, in increasing order: + # debug5, debug4, debug3, debug2, debug1, + # log, notice, warning, error, fatal, and panic + # Defaults to warning. + #min_messages: notice + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: umanni_users_test<%= ENV["TEST_ENV_NUMBER"] %> + +# As with config/credentials.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password or a full connection URL as an environment +# variable when you boot the app. For example: +# +# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" +# +# If the connection URL is provided in the special DATABASE_URL environment +# variable, Rails will automatically merge its configuration values on top of +# the values provided in this file. Alternatively, you can specify a connection +# URL environment variable explicitly: +# +# production: +# url: <%= ENV["MY_APP_DATABASE_URL"] %> +# +# Connection URLs for non-primary databases can also be configured using +# environment variables. The variable name is formed by concatenating the +# connection name with `_DATABASE_URL`. For example: +# +# CACHE_DATABASE_URL="postgres://cacheuser:cachepass@localhost/cachedatabase" +# +# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full overview on how database connection configuration can be specified. +# +production: + primary: &primary_production + <<: *default + database: umanni_users_production + cache: + <<: *primary_production + database: umanni_users_production_cache + migrations_paths: db/cache_migrate + queue: + <<: *primary_production + database: umanni_users_production_queue + migrations_paths: db/queue_migrate + cable: + <<: *primary_production + database: umanni_users_production_cable + migrations_paths: db/cable_migrate diff --git a/config/deploy.yml b/config/deploy.yml new file mode 100644 index 000000000..9e4cb3fda --- /dev/null +++ b/config/deploy.yml @@ -0,0 +1,73 @@ +service: umanni-users +image: <%= ENV.fetch("KAMAL_IMAGE", "your-org/umanni-users") %> + +servers: + web: + - <%= ENV.fetch("KAMAL_WEB_HOST", "your-server.example.com") %> + job: + hosts: + - <%= ENV.fetch("KAMAL_JOB_HOST", ENV.fetch("KAMAL_WEB_HOST", "your-server.example.com")) %> + cmd: bin/jobs + +proxy: + ssl: true + host: <%= ENV.fetch("APP_HOST", "users.example.com") %> + healthcheck: + path: /up + interval: 3 + timeout: 3 + +registry: + server: ghcr.io + username: <%= ENV.fetch("KAMAL_REGISTRY_USERNAME", "your-github-user") %> + password: + - KAMAL_REGISTRY_PASSWORD + +env: + secret: + - SECRET_KEY_BASE + - DB_PASSWORD + - SMTP_PASSWORD + clear: + APP_HOST: <%= ENV.fetch("APP_HOST", "users.example.com") %> + APP_PROTOCOL: https + DB_HOST: umanni-users-db + DB_PORT: 5432 + DB_USERNAME: umanni_users + RAILS_LOG_LEVEL: info + RAILS_MAX_THREADS: 5 + JOB_CONCURRENCY: 2 + SMTP_ADDRESS: <%= ENV.fetch("SMTP_ADDRESS", "smtp.example.com") %> + SMTP_PORT: 587 + SMTP_USERNAME: "<%= ENV.fetch("SMTP_USERNAME", "") %>" + +aliases: + console: app exec --interactive --reuse "bin/rails console" + shell: app exec --interactive --reuse "bash" + logs: app logs -f + jobs: app logs -f -r job + dbc: app exec --interactive --reuse "bin/rails dbconsole --include-password" + +volumes: + - "umanni_users_storage:/rails/storage" + +asset_path: /rails/public/assets + +builder: + arch: amd64 + +ssh: + user: deploy + +accessories: + db: + image: postgres:17-alpine + host: <%= ENV.fetch("KAMAL_WEB_HOST", "your-server.example.com") %> + port: "127.0.0.1:5432:5432" + env: + clear: + POSTGRES_USER: umanni_users + secret: + - POSTGRES_PASSWORD:DB_PASSWORD + directories: + - data:/var/lib/postgresql/data diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 000000000..cac531577 --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 index 000000000..f56a0e67f --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,82 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Make code changes take effect immediately without server restart. + config.enable_reloading = true + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing. + config.server_timing = true + + # Enable/disable Action Controller caching. By default Action Controller caching is disabled. + # Run rails dev:cache to toggle Action Controller caching. + if Rails.root.join("tmp/caching-dev.txt").exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + config.public_file_server.headers = { "cache-control" => "public, max-age=#{2.days.to_i}" } + else + config.action_controller.perform_caching = false + end + + # Change to :null_store to avoid any caching. + config.cache_store = :memory_store + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + config.action_mailer.delivery_method = :file + config.action_mailer.file_settings = { location: Rails.root.join("tmp/mails") } + + # Make template changes take effect immediately. + config.action_mailer.perform_caching = false + + # Set localhost to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "localhost", port: 3000 } + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Append comments with runtime information tags to SQL queries in logs. + config.active_record.query_log_tags_enabled = true + + # Highlight code that enqueued background job in logs. + config.active_job.verbose_enqueue_logs = true + config.active_job.queue_adapter = :solid_queue + config.solid_queue.connects_to = { database: { writing: :queue } } + + # Highlight code that triggered redirect in logs. + config.action_dispatch.verbose_redirect_logs = true + + # Suppress logger output for asset requests. + config.assets.quiet = true + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true + + # Apply autocorrection by RuboCop to files generated by `bin/rails generate`. + # config.generators.apply_rubocop_autocorrect_after_generate! +end diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 000000000..2c65407f7 --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,100 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + app_host = ENV.fetch("APP_HOST", "example.com") + app_protocol = ENV.fetch("APP_PROTOCOL", "https") + credentials_available = ENV["RAILS_MASTER_KEY"].present? || Rails.root.join("config/master.key").exist? + smtp_credentials = credentials_available ? Rails.application.credentials.fetch(:smtp, {}) : {} + config.yjit = false if ENV["RUBYOPT"].to_s.split.include?("--zjit") + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.enable_reloading = false + + # Eager load code on boot for better performance and memory savings (ignored by Rake tasks). + config.eager_load = true + + # Full error reports are disabled. + config.consider_all_requests_local = false + + # Turn on fragment caching in view templates. + config.action_controller.perform_caching = true + + # Cache assets for far-future expiry since they are all digest stamped. + config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + if app_protocol == "https" + config.assume_ssl = true + config.force_ssl = true + config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } + end + + # Log to STDOUT with the current request id as a default log tag. + config.log_tags = [ :request_id ] + config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) + + # Change to "debug" to log everything (including potentially personally-identifiable information!). + config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") + + # Prevent health checks from clogging up the logs. + config.silence_healthcheck_path = "/up" + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Replace the default in-process memory cache store with a durable alternative. + config.cache_store = :solid_cache_store + + # Replace the default in-process and non-durable queuing backend for Active Job. + config.active_job.queue_adapter = :solid_queue + config.solid_queue.connects_to = { database: { writing: :queue } } + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { + host: app_host, + protocol: app_protocol + } + + smtp_address = ENV["SMTP_ADDRESS"].presence || smtp_credentials[:address] + if smtp_address.present? + config.action_mailer.delivery_method = :smtp + config.action_mailer.raise_delivery_errors = true + config.action_mailer.smtp_settings = { + address: smtp_address, + port: ENV.fetch("SMTP_PORT", smtp_credentials[:port] || 587), + user_name: ENV["SMTP_USERNAME"].presence || smtp_credentials[:user_name], + password: ENV["SMTP_PASSWORD"].presence || smtp_credentials[:password], + authentication: :plain, + enable_starttls_auto: true + }.compact + else + # Keeps the production-like Docker demo self-contained. Real deployments + # should supply SMTP credentials and will automatically switch to SMTP. + config.action_mailer.delivery_method = :file + config.action_mailer.file_settings = { location: Rails.root.join("storage/mails") } + end + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # Only use :id for inspections in production. + config.active_record.attributes_for_inspect = [ :id ] + + config.hosts = [ app_host ] + config.hosts << "localhost" if app_host == "localhost" + config.host_authorization = { exclude: ->(request) { request.path == "/up" } } +end diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 000000000..c2095b117 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,53 @@ +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # While tests run files are not watched, reloading is not necessary. + config.enable_reloading = false + + # Eager loading loads your entire application. When running a single test locally, + # this is usually not necessary, and can slow down your test suite. However, it's + # recommended that you enable it in continuous integration systems to ensure eager + # loading is working properly before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with cache-control for performance. + config.public_file_server.headers = { "cache-control" => "public, max-age=3600" } + + # Show full error reports. + config.consider_all_requests_local = true + config.cache_store = :null_store + + # Render exception templates for rescuable exceptions and raise for other exceptions. + config.action_dispatch.show_exceptions = :rescuable + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "example.com" } + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true +end diff --git a/config/importmap.rb b/config/importmap.rb new file mode 100644 index 000000000..909dfc542 --- /dev/null +++ b/config/importmap.rb @@ -0,0 +1,7 @@ +# Pin npm packages by running ./bin/importmap + +pin "application" +pin "@hotwired/turbo-rails", to: "turbo.min.js" +pin "@hotwired/stimulus", to: "stimulus.min.js" +pin "@hotwired/stimulus-loading", to: "stimulus-loading.js" +pin_all_from "app/javascript/controllers", under: "controllers" diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb new file mode 100644 index 000000000..487324424 --- /dev/null +++ b/config/initializers/assets.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = "1.0" + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path diff --git a/config/initializers/content_security_policy.rb b/config/initializers/content_security_policy.rb new file mode 100644 index 000000000..e5e344c06 --- /dev/null +++ b/config/initializers/content_security_policy.rb @@ -0,0 +1,24 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy. +# See the Securing Rails Applications Guide for more information: +# https://guides.rubyonrails.org/security.html#content-security-policy-header + +Rails.application.configure do + config.content_security_policy do |policy| + policy.default_src :self + policy.base_uri :self + policy.connect_src :self, "ws:", "wss:" + policy.font_src :self, :data + policy.form_action :self + policy.frame_ancestors :none + policy.img_src :self, :https, :data, :blob + policy.object_src :none + policy.script_src :self + policy.style_src :self + end + + config.content_security_policy_nonce_generator = ->(_request) { SecureRandom.base64(16) } + config.content_security_policy_nonce_directives = %w[script-src] + config.content_security_policy_nonce_auto = true +end diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 000000000..23c0588e7 --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. +# Use this to limit dissemination of sensitive information. +# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc, :payload +] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 000000000..3860f659e --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 000000000..6c349ae5e --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,31 @@ +# Files in the config/locales directory are used for internationalization and +# are automatically loaded by Rails. If you want to use locales other than +# English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more about the API, please read the Rails Internationalization guide +# at https://guides.rubyonrails.org/i18n.html. +# +# Be aware that YAML interprets the following case-insensitive strings as +# booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings +# must be quoted to be interpreted as strings. For example: +# +# en: +# "yes": yup +# enabled: "ON" + +en: + hello: "Hello world" diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 000000000..38c4b8659 --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,42 @@ +# This configuration file will be evaluated by Puma. The top-level methods that +# are invoked here are part of Puma's configuration DSL. For more information +# about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. +# +# Puma starts a configurable number of processes (workers) and each process +# serves each request in a thread from an internal thread pool. +# +# You can control the number of workers using ENV["WEB_CONCURRENCY"]. You +# should only set this value when you want to run 2 or more workers. The +# default is already 1. You can set it to `auto` to automatically start a worker +# for each available processor. +# +# The ideal number of threads per worker depends both on how much time the +# application spends waiting for IO operations and on how much you wish to +# prioritize throughput over latency. +# +# As a rule of thumb, increasing the number of threads will increase how much +# traffic a given process can handle (throughput), but due to CRuby's +# Global VM Lock (GVL) it has diminishing returns and will degrade the +# response time (latency) of the application. +# +# The default is set to 3 threads as it's deemed a decent compromise between +# throughput and latency for the average Rails application. +# +# Any libraries that use a connection pool or another resource pool should +# be configured to provide at least as many connections as the number of +# threads. This includes Active Record's `pool` parameter in `database.yml`. +threads_count = ENV.fetch("RAILS_MAX_THREADS", 3) +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +port ENV.fetch("PORT", 3000) + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart + +# Run the Solid Queue supervisor inside of Puma for single-server deployments. +plugin :solid_queue if ENV["SOLID_QUEUE_IN_PUMA"] + +# Specify the PID file. Defaults to tmp/pids/server.pid in development. +# In other environments, only set the PID file if requested. +pidfile ENV["PIDFILE"] if ENV["PIDFILE"] diff --git a/config/queue.yml b/config/queue.yml new file mode 100644 index 000000000..6b1436086 --- /dev/null +++ b/config/queue.yml @@ -0,0 +1,18 @@ +default: &default + dispatchers: + - polling_interval: 1 + batch_size: 500 + workers: + - queues: "*" + threads: 3 + processes: <%= ENV.fetch("JOB_CONCURRENCY", 1) %> + polling_interval: 1 + +development: + <<: *default + +test: + <<: *default + +production: + <<: *default diff --git a/config/recurring.yml b/config/recurring.yml new file mode 100644 index 000000000..b4207f9b0 --- /dev/null +++ b/config/recurring.yml @@ -0,0 +1,15 @@ +# examples: +# periodic_cleanup: +# class: CleanSoftDeletedRecordsJob +# queue: background +# args: [ 1000, { batch_size: 500 } ] +# schedule: every hour +# periodic_cleanup_with_command: +# command: "SoftDeletedRecord.due.delete_all" +# priority: 2 +# schedule: at 5am every day + +production: + clear_solid_queue_finished_jobs: + command: "SolidQueue::Job.clear_finished_in_batches(sleep_between_batches: 0.3)" + schedule: every hour at minute 12 diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 000000000..57fc84bd3 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,23 @@ +Rails.application.routes.draw do + root "home#show" + + resource :session, only: %i[ new create destroy ] + resources :passwords, param: :token, only: %i[ new create edit update ] + resource :registration, only: %i[ new create ] + resource :profile, only: %i[ show edit update destroy ] + + namespace :admin do + root "dashboard#show" + resources :users, except: :show do + patch :toggle_role, on: :member + end + resources :user_imports, only: %i[ index new create show ] + end + + # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. + # Can be used by load balancers and uptime monitors to verify that the app is live. + get "up" => "rails/health#show", as: :rails_health_check + + get "manifest" => "rails/pwa#manifest", defaults: { format: :json }, as: :pwa_manifest + get "service-worker" => "rails/pwa#service_worker", defaults: { format: :js }, as: :pwa_service_worker +end diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 000000000..927dc537c --- /dev/null +++ b/config/storage.yml @@ -0,0 +1,27 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/db/cable_schema.rb b/db/cable_schema.rb new file mode 100644 index 000000000..23666604a --- /dev/null +++ b/db/cable_schema.rb @@ -0,0 +1,11 @@ +ActiveRecord::Schema[7.1].define(version: 1) do + create_table "solid_cable_messages", force: :cascade do |t| + t.binary "channel", limit: 1024, null: false + t.binary "payload", limit: 536870912, null: false + t.datetime "created_at", null: false + t.integer "channel_hash", limit: 8, null: false + t.index ["channel"], name: "index_solid_cable_messages_on_channel" + t.index ["channel_hash"], name: "index_solid_cable_messages_on_channel_hash" + t.index ["created_at"], name: "index_solid_cable_messages_on_created_at" + end +end diff --git a/db/cache_schema.rb b/db/cache_schema.rb new file mode 100644 index 000000000..81a410d18 --- /dev/null +++ b/db/cache_schema.rb @@ -0,0 +1,12 @@ +ActiveRecord::Schema[7.2].define(version: 1) do + create_table "solid_cache_entries", force: :cascade do |t| + t.binary "key", limit: 1024, null: false + t.binary "value", limit: 536870912, null: false + t.datetime "created_at", null: false + t.integer "key_hash", limit: 8, null: false + t.integer "byte_size", limit: 4, null: false + t.index ["byte_size"], name: "index_solid_cache_entries_on_byte_size" + t.index ["key_hash", "byte_size"], name: "index_solid_cache_entries_on_key_hash_and_byte_size" + t.index ["key_hash"], name: "index_solid_cache_entries_on_key_hash", unique: true + end +end diff --git a/db/migrate/20260902214512_create_users.rb b/db/migrate/20260902214512_create_users.rb new file mode 100644 index 000000000..da51f954b --- /dev/null +++ b/db/migrate/20260902214512_create_users.rb @@ -0,0 +1,17 @@ +class CreateUsers < ActiveRecord::Migration[8.1] + def change + create_table :users do |t| + t.string :full_name, null: false + t.string :email, null: false + t.string :password_digest, null: false + t.integer :role, null: false, default: 0 + t.string :avatar_image_url + + t.timestamps + end + add_index :users, "lower(email)", unique: true, name: "index_users_on_lower_email" + add_check_constraint :users, "role IN (0, 1)", name: "users_role_check" + add_check_constraint :users, "char_length(email) <= 254", name: "users_email_length_check" + add_check_constraint :users, "char_length(full_name) BETWEEN 2 AND 100", name: "users_full_name_length_check" + end +end diff --git a/db/migrate/20260902214513_create_sessions.rb b/db/migrate/20260902214513_create_sessions.rb new file mode 100644 index 000000000..ec9efdbaa --- /dev/null +++ b/db/migrate/20260902214513_create_sessions.rb @@ -0,0 +1,11 @@ +class CreateSessions < ActiveRecord::Migration[8.1] + def change + create_table :sessions do |t| + t.references :user, null: false, foreign_key: true + t.string :ip_address + t.string :user_agent + + t.timestamps + end + end +end diff --git a/db/migrate/20260902214516_create_active_storage_tables.active_storage.rb b/db/migrate/20260902214516_create_active_storage_tables.active_storage.rb new file mode 100644 index 000000000..6bd8bd082 --- /dev/null +++ b/db/migrate/20260902214516_create_active_storage_tables.active_storage.rb @@ -0,0 +1,57 @@ +# This migration comes from active_storage (originally 20170806125915) +class CreateActiveStorageTables < ActiveRecord::Migration[7.0] + def change + # Use Active Record's configured type for primary and foreign keys + primary_key_type, foreign_key_type = primary_and_foreign_key_types + + create_table :active_storage_blobs, id: primary_key_type do |t| + t.string :key, null: false + t.string :filename, null: false + t.string :content_type + t.text :metadata + t.string :service_name, null: false + t.bigint :byte_size, null: false + t.string :checksum + + if connection.supports_datetime_with_precision? + t.datetime :created_at, precision: 6, null: false + else + t.datetime :created_at, null: false + end + + t.index [ :key ], unique: true + end + + create_table :active_storage_attachments, id: primary_key_type do |t| + t.string :name, null: false + t.references :record, null: false, polymorphic: true, index: false, type: foreign_key_type + t.references :blob, null: false, type: foreign_key_type + + if connection.supports_datetime_with_precision? + t.datetime :created_at, precision: 6, null: false + else + t.datetime :created_at, null: false + end + + t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + + create_table :active_storage_variant_records, id: primary_key_type do |t| + t.belongs_to :blob, null: false, index: false, type: foreign_key_type + t.string :variation_digest, null: false + + t.index [ :blob_id, :variation_digest ], name: :index_active_storage_variant_records_uniqueness, unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + end + + private + def primary_and_foreign_key_types + config = Rails.configuration.generators + setting = config.options[config.orm][:primary_key_type] + primary_key_type = setting || :primary_key + foreign_key_type = setting || :bigint + [ primary_key_type, foreign_key_type ] + end +end diff --git a/db/migrate/20260902214709_create_user_imports.rb b/db/migrate/20260902214709_create_user_imports.rb new file mode 100644 index 000000000..5b95460ca --- /dev/null +++ b/db/migrate/20260902214709_create_user_imports.rb @@ -0,0 +1,22 @@ +class CreateUserImports < ActiveRecord::Migration[8.1] + def change + create_table :user_imports do |t| + t.references :created_by, null: false, foreign_key: { to_table: :users } + t.integer :status, null: false, default: 0 + t.integer :total_rows, null: false, default: 0 + t.integer :processed_rows, null: false, default: 0 + t.integer :succeeded_rows, null: false, default: 0 + t.integer :failed_rows, null: false, default: 0 + t.datetime :started_at + t.datetime :finished_at + t.text :failure_message + + t.timestamps + end + + add_check_constraint :user_imports, "status IN (0, 1, 2, 3, 4)", name: "user_imports_status_check" + add_check_constraint :user_imports, + "total_rows >= 0 AND processed_rows >= 0 AND succeeded_rows >= 0 AND failed_rows >= 0", + name: "user_imports_counters_non_negative_check" + end +end diff --git a/db/migrate/20260902214713_create_user_import_rows.rb b/db/migrate/20260902214713_create_user_import_rows.rb new file mode 100644 index 000000000..03440c2f2 --- /dev/null +++ b/db/migrate/20260902214713_create_user_import_rows.rb @@ -0,0 +1,18 @@ +class CreateUserImportRows < ActiveRecord::Migration[8.1] + def change + create_table :user_import_rows do |t| + t.references :user_import, null: false, foreign_key: true + t.integer :row_number, null: false + t.integer :status, null: false, default: 0 + t.jsonb :payload, null: false, default: {} + t.text :error_message + t.references :user, null: true, foreign_key: true + + t.timestamps + end + + add_index :user_import_rows, [ :user_import_id, :row_number ], unique: true + add_check_constraint :user_import_rows, "status IN (0, 1, 2)", name: "user_import_rows_status_check" + add_check_constraint :user_import_rows, "row_number >= 2", name: "user_import_rows_row_number_check" + end +end diff --git a/db/migrate/20260902224000_add_consistency_constraints_to_user_imports.rb b/db/migrate/20260902224000_add_consistency_constraints_to_user_imports.rb new file mode 100644 index 000000000..5d548b1d6 --- /dev/null +++ b/db/migrate/20260902224000_add_consistency_constraints_to_user_imports.rb @@ -0,0 +1,10 @@ +class AddConsistencyConstraintsToUserImports < ActiveRecord::Migration[8.1] + def change + add_check_constraint :user_imports, + "processed_rows <= total_rows", + name: "user_imports_processed_within_total_check" + add_check_constraint :user_imports, + "succeeded_rows + failed_rows = processed_rows", + name: "user_imports_processed_breakdown_check" + end +end diff --git a/db/migrate/20260902231500_preserve_import_history_when_users_are_deleted.rb b/db/migrate/20260902231500_preserve_import_history_when_users_are_deleted.rb new file mode 100644 index 000000000..abcca0297 --- /dev/null +++ b/db/migrate/20260902231500_preserve_import_history_when_users_are_deleted.rb @@ -0,0 +1,31 @@ +class PreserveImportHistoryWhenUsersAreDeleted < ActiveRecord::Migration[8.1] + def up + change_column_null :user_imports, :created_by_id, true + + replace_user_foreign_key(:user_imports, :created_by_id, on_delete: :nullify) + replace_user_foreign_key(:user_import_rows, :user_id, on_delete: :nullify) + end + + def down + null_references = select_value(<<~SQL.squish) + SELECT EXISTS ( + SELECT 1 FROM user_imports WHERE created_by_id IS NULL + UNION ALL + SELECT 1 FROM user_import_rows WHERE user_id IS NULL AND status = 1 + ) + SQL + if null_references + raise ActiveRecord::IrreversibleMigration, "anonymized import references cannot recover their original users" + end + + replace_user_foreign_key(:user_imports, :created_by_id) + replace_user_foreign_key(:user_import_rows, :user_id) + change_column_null :user_imports, :created_by_id, false + end + + private + def replace_user_foreign_key(table, column, **options) + remove_foreign_key(table, :users, column: column) + add_foreign_key(table, :users, column: column, **options) + end +end diff --git a/db/queue_schema.rb b/db/queue_schema.rb new file mode 100644 index 000000000..f9a71dabb --- /dev/null +++ b/db/queue_schema.rb @@ -0,0 +1,160 @@ +ActiveRecord::Schema[7.1].define(version: 1) do + create_table "solid_queue_blocked_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.string "concurrency_key", null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.index [ "concurrency_key", "priority", "job_id" ], name: "index_solid_queue_blocked_executions_for_release" + t.index [ "expires_at", "concurrency_key" ], name: "index_solid_queue_blocked_executions_for_maintenance" + t.index [ "job_id" ], name: "index_solid_queue_blocked_executions_on_job_id", unique: true + end + + create_table "solid_queue_claimed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.bigint "process_id" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_claimed_executions_on_job_id", unique: true + t.index [ "process_id", "job_id" ], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id" + end + + create_table "solid_queue_failed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.text "error" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_failed_executions_on_job_id", unique: true + end + + create_table "solid_queue_jobs", force: :cascade do |t| + t.string "queue_name", null: false + t.string "class_name", null: false + t.text "arguments" + t.integer "priority", default: 0, null: false + t.string "active_job_id" + t.datetime "scheduled_at" + t.datetime "finished_at" + t.string "concurrency_key" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.bigint "batch_id" + t.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_id" + t.index [ "batch_id" ], name: "index_solid_queue_jobs_on_batch_id" + t.index [ "class_name" ], name: "index_solid_queue_jobs_on_class_name" + t.index [ "finished_at" ], name: "index_solid_queue_jobs_on_finished_at" + t.index [ "queue_name", "finished_at" ], name: "index_solid_queue_jobs_for_filtering" + t.index [ "scheduled_at", "finished_at" ], name: "index_solid_queue_jobs_for_alerting" + end + + create_table "solid_queue_pauses", force: :cascade do |t| + t.string "queue_name", null: false + t.datetime "created_at", null: false + t.index [ "queue_name" ], name: "index_solid_queue_pauses_on_queue_name", unique: true + end + + create_table "solid_queue_processes", force: :cascade do |t| + t.string "kind", null: false + t.datetime "last_heartbeat_at", null: false + t.bigint "supervisor_id" + t.integer "pid", null: false + t.string "hostname" + t.text "metadata" + t.datetime "created_at", null: false + t.string "name", null: false + t.index [ "last_heartbeat_at" ], name: "index_solid_queue_processes_on_last_heartbeat_at" + t.index [ "name", "supervisor_id" ], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true + t.index [ "supervisor_id" ], name: "index_solid_queue_processes_on_supervisor_id" + end + + create_table "solid_queue_ready_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_ready_executions_on_job_id", unique: true + t.index [ "priority", "job_id" ], name: "index_solid_queue_poll_all" + t.index [ "queue_name", "priority", "job_id" ], name: "index_solid_queue_poll_by_queue" + end + + create_table "solid_queue_recurring_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "task_key", null: false + t.datetime "run_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_recurring_executions_on_job_id", unique: true + t.index [ "task_key", "run_at" ], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true + end + + create_table "solid_queue_recurring_tasks", force: :cascade do |t| + t.string "key", null: false + t.string "schedule", null: false + t.string "command", limit: 2048 + t.string "class_name" + t.text "arguments" + t.string "queue_name" + t.integer "priority", default: 0 + t.boolean "static", default: true, null: false + t.text "description" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "key" ], name: "index_solid_queue_recurring_tasks_on_key", unique: true + t.index [ "static" ], name: "index_solid_queue_recurring_tasks_on_static" + end + + create_table "solid_queue_scheduled_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "scheduled_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true + t.index [ "scheduled_at", "priority", "job_id" ], name: "index_solid_queue_dispatch_all" + end + + create_table "solid_queue_semaphores", force: :cascade do |t| + t.string "key", null: false + t.integer "value", default: 1, null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "expires_at" ], name: "index_solid_queue_semaphores_on_expires_at" + t.index [ "key", "value" ], name: "index_solid_queue_semaphores_on_key_and_value" + t.index [ "key" ], name: "index_solid_queue_semaphores_on_key", unique: true + end + + create_table "solid_queue_batches", force: :cascade do |t| + t.string "active_job_batch_id" + t.string "description" + t.text "on_finish" + t.text "on_success" + t.text "on_failure" + t.text "metadata" + t.integer "total_jobs", default: 0, null: false + t.integer "completed_jobs", default: 0, null: false + t.integer "failed_jobs", default: 0, null: false + t.datetime "enqueued_at" + t.datetime "finished_at" + t.datetime "failed_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "active_job_batch_id" ], name: "index_solid_queue_batches_on_active_job_batch_id", unique: true + t.index [ "finished_at" ], name: "index_solid_queue_batches_on_finished_at" + end + + create_table "solid_queue_batch_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.bigint "batch_id", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_batch_executions_on_job_id", unique: true + t.index [ "batch_id" ], name: "index_solid_queue_batch_executions_on_batch_id" + end + + add_foreign_key "solid_queue_batch_executions", "solid_queue_batches", column: "batch_id", on_delete: :cascade + add_foreign_key "solid_queue_batch_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 000000000..6f61f032f --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,109 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema[8.1].define(version: 2026_09_02_231500) do + # These are extensions that must be enabled in order to support this database + enable_extension "pg_catalog.plpgsql" + + create_table "active_storage_attachments", force: :cascade do |t| + t.bigint "blob_id", null: false + t.datetime "created_at", null: false + t.string "name", null: false + t.bigint "record_id", null: false + t.string "record_type", null: false + t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id" + t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true + end + + create_table "active_storage_blobs", force: :cascade do |t| + t.bigint "byte_size", null: false + t.string "checksum" + t.string "content_type" + t.datetime "created_at", null: false + t.string "filename", null: false + t.string "key", null: false + t.text "metadata" + t.string "service_name", null: false + t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true + end + + create_table "active_storage_variant_records", force: :cascade do |t| + t.bigint "blob_id", null: false + t.string "variation_digest", null: false + t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true + end + + create_table "sessions", force: :cascade do |t| + t.datetime "created_at", null: false + t.string "ip_address" + t.datetime "updated_at", null: false + t.string "user_agent" + t.bigint "user_id", null: false + t.index ["user_id"], name: "index_sessions_on_user_id" + end + + create_table "user_import_rows", force: :cascade do |t| + t.datetime "created_at", null: false + t.text "error_message" + t.jsonb "payload", default: {}, null: false + t.integer "row_number", null: false + t.integer "status", default: 0, null: false + t.datetime "updated_at", null: false + t.bigint "user_id" + t.bigint "user_import_id", null: false + t.index ["user_id"], name: "index_user_import_rows_on_user_id" + t.index ["user_import_id", "row_number"], name: "index_user_import_rows_on_user_import_id_and_row_number", unique: true + t.index ["user_import_id"], name: "index_user_import_rows_on_user_import_id" + t.check_constraint "row_number >= 2", name: "user_import_rows_row_number_check" + t.check_constraint "status = ANY (ARRAY[0, 1, 2])", name: "user_import_rows_status_check" + end + + create_table "user_imports", force: :cascade do |t| + t.datetime "created_at", null: false + t.bigint "created_by_id" + t.integer "failed_rows", default: 0, null: false + t.text "failure_message" + t.datetime "finished_at" + t.integer "processed_rows", default: 0, null: false + t.datetime "started_at" + t.integer "status", default: 0, null: false + t.integer "succeeded_rows", default: 0, null: false + t.integer "total_rows", default: 0, null: false + t.datetime "updated_at", null: false + t.index ["created_by_id"], name: "index_user_imports_on_created_by_id" + t.check_constraint "(succeeded_rows + failed_rows) = processed_rows", name: "user_imports_processed_breakdown_check" + t.check_constraint "processed_rows <= total_rows", name: "user_imports_processed_within_total_check" + t.check_constraint "status = ANY (ARRAY[0, 1, 2, 3, 4])", name: "user_imports_status_check" + t.check_constraint "total_rows >= 0 AND processed_rows >= 0 AND succeeded_rows >= 0 AND failed_rows >= 0", name: "user_imports_counters_non_negative_check" + end + + create_table "users", force: :cascade do |t| + t.string "avatar_image_url" + t.datetime "created_at", null: false + t.string "email", null: false + t.string "full_name", null: false + t.string "password_digest", null: false + t.integer "role", default: 0, null: false + t.datetime "updated_at", null: false + t.index "lower((email)::text)", name: "index_users_on_lower_email", unique: true + t.check_constraint "char_length(email::text) <= 254", name: "users_email_length_check" + t.check_constraint "char_length(full_name::text) >= 2 AND char_length(full_name::text) <= 100", name: "users_full_name_length_check" + t.check_constraint "role = ANY (ARRAY[0, 1])", name: "users_role_check" + end + + add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" + add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" + add_foreign_key "sessions", "users" + add_foreign_key "user_import_rows", "user_imports" + add_foreign_key "user_import_rows", "users", on_delete: :nullify + add_foreign_key "user_imports", "users", column: "created_by_id", on_delete: :nullify +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 000000000..c8b7e7b76 --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,17 @@ +seed_users = [ + { full_name: "Ada Admin", email: "admin@example.com", role: :admin, password: "SecurePass123!" }, + { full_name: "Grace Member", email: "member@example.com", role: :user, password: "SecurePass123!" } +] + +seed_users.each do |attributes| + user = User.find_or_initialize_by(email: attributes[:email]) + user.assign_attributes(attributes) + unless user.avatar_image.attached? + user.avatar_image.attach( + io: File.open(Rails.root.join("public/icon.png")), + filename: "umanni-avatar.png", + content_type: "image/png" + ) + end + user.save! +end diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 000000000..933db6c58 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,83 @@ +# Architecture + +## Design goals + +The system optimizes for explicit business boundaries, safe asynchronous work, and a small operational surface. It is a modular Rails monolith: deployment remains one application image, while namespaces and object responsibilities keep independent concerns replaceable and testable. + +The design avoids ceremonial repositories and layers where Active Record already provides the right abstraction. It also avoids microservices because user management, authorization, statistics, and imports share transactional data and have no independent scaling or ownership boundary in this scope. + +## Responsibilities + +### HTTP layer + +Controllers authenticate, authorize, coerce structural parameters with `params.expect`, invoke one use-case/query boundary, and choose a response. They contain no import parsing, role invariant, password generation, or statistics logic. + +- `RegistrationsController` creates forced-standard-role visitor accounts. +- `ProfilesController` scopes every operation to `Current.user`. +- `Admin::BaseController` centralizes administrator authorization. +- Admin controllers orchestrate users, imports, and dashboard reads. + +### Domain and persistence layer + +- `User` owns identity normalization, credential policy, role semantics, and avatar invariants. +- `Session` is a revocable server-side authentication record. +- `UserImport` is the durable import aggregate with counters and lifecycle state. Its creator reference is required at creation but can be anonymized later, so deleting an account does not erase operational history. +- `UserImportRow` is an auditable per-row result and idempotency marker. Its optional user reference is anonymized if that account is deleted. +- PostgreSQL constraints mirror the critical role, length, counter, status, uniqueness, and relationship invariants. + +### Use-case services + +- `Users::Create`, `Users::Update`, `Users::Destroy`, and `Users::ToggleRole` own account mutations and side effects. +- `Imports::SpreadsheetParser` bounds XLSX archive expansion and sparse sheet dimensions before turning CSV/XLSX content into a normalized immutable row representation. +- `Imports::RowProcessor` maps external role values, creates an invited user, and isolates validation/uniqueness errors. +- `Imports::ProgressUpdater` derives counters from persisted row states rather than trusting in-memory increments. +- `Imports::ProgressBroadcaster` publishes the server-rendered progress component. + +Service results are domain records with their validation errors, so controllers do not translate a parallel error model. + +### Read models + +- `Dashboard::Stats` returns the role totals required by the live dashboard. +- `Users::Search` owns case-insensitive filtering, wildcard escaping, ordering, pagination, and avatar preloading. + +### Asynchronous boundaries + +`Imports::ProcessJob` runs on the `imports` queue. It persists processing metadata, creates/updates each row, refreshes durable counters, and broadcasts progress. Successful rows are skipped on retry and terminal imports return immediately. Structural parse failures finish as `failed`; row validation failures finish as `completed_with_errors` while successful rows remain committed. + +`Dashboard::BroadcastStatsJob` renders one Turbo Stream replacement after account and role changes. During imports it is additionally queued every 25 rows and once at completion to avoid a counter broadcast for every large-import row. + +Solid Queue, Solid Cable, and Solid Cache use separate logical PostgreSQL databases. This isolates their schemas and connection roles without adding Redis or separate application services. + +## Last-administrator invariant + +Demotion and deletion must never remove the final administrator. A validation alone cannot provide this guarantee because two requests can both observe another administrator. + +The mutation service opens a transaction and locks all current administrator rows in deterministic primary-key order. A concurrent mutation waits, re-reads the committed set under PostgreSQL's `READ COMMITTED` isolation, and rejects the operation if one administrator remains. Standard-user rows are locked individually. The stable order also avoids two concurrent operations deadlocking while each holds a different administrator row. + +## Authentication and authorization flow + +The Rails authentication generator was customized to use `email`, server-side `Session` records, and role-aware destinations. A successful login retains only a validated same-host return URL, resets the cookie session to prevent fixation, and creates a new persisted session. Action Cable resolves the same signed session cookie before accepting a connection. + +Authorization is intentionally server-side. Navigation visibility improves usability but is never treated as a permission boundary. + +## Frontend + +Turbo provides navigation, form submissions, confirmations, and stream replacements. Small Stimulus controllers handle password visibility, dismissible notices, avatar preview lifecycle, and broken-image fallback. Server-rendered HTML remains the source of truth, so there is no duplicate JSON state model or client-side authorization logic. + +Tailwind switches the directory from a semantic desktop table to mobile cards. Native labels, constraints, progress elements, live regions, focus styles, and confirmation dialogs provide the accessible baseline. + +## Deployment topology + +The same final Docker image runs two roles: + +- `web`: Puma behind Thruster for HTTP compression, caching, and health checks; +- `job`: Solid Queue supervisor and workers. + +Compose adds a one-shot setup service so the queue worker cannot start before all four schemas are prepared. Kamal provides equivalent web/job roles, TLS proxying, a PostgreSQL accessory, and a shared volume for a single-host deployment. Ruby 4 ZJIT is enabled only in the lean runtime stage; build/test stages remain deterministic. + +## Future evolution + +- Move Active Storage to S3-compatible storage before deploying web/job roles to different hosts. +- Add direct-to-cloud uploads if avatar volume or request duration justifies it. +- Add an outbox only if mail/stream delivery must become atomic across infrastructure failures. +- Partition import rows or stream/chunk parser input if limits grow substantially beyond the current 5 MB/1,000-row product boundary. diff --git a/docs/qa-inventory.md b/docs/qa-inventory.md new file mode 100644 index 000000000..8aea2623d --- /dev/null +++ b/docs/qa-inventory.md @@ -0,0 +1,53 @@ +# End-to-end QA inventory + +This inventory defines the user-visible claims and controls that must be checked before delivery. Automated system coverage is complemented by an interactive browser pass against the production Docker image. + +## Visitor journeys + +- Landing page: responsive header, product message, sign-in link, and registration call to action. +- Registration: name, email, password confirmation, upload/remote avatar choice, client constraints, server validation errors, and forced standard-user role. +- Authentication: valid/invalid credentials, password visibility, same-host return path, sign-out, and password recovery without account enumeration. + +## Standard-user journeys + +- Role-aware login redirect to the personal profile. +- Profile only exposes the signed-in user's information. +- Profile edit supports name, email, uploaded avatar, and HTTPS remote avatar with preview/fallback behavior. +- Account deletion requires confirmation, revokes the current session, and cannot mutate another account. +- Admin navigation and endpoints remain inaccessible. + +## Administrator journeys + +- Role-aware login redirect to the admin dashboard. +- Dashboard shows total, administrator, and standard-user counts and subscribes to a Turbo stream. +- User directory supports responsive list/card layouts, safe name/email search, empty state, pagination, creation, editing, role toggling, and deletion confirmations. +- The final administrator cannot be demoted or deleted. +- CSV and XLSX upload controls enforce extension/content-type pairing and size limits, and provide downloadable templates. +- Imports move through queued/processing/terminal states in Solid Queue, update through Solid Cable, retain durable counters, isolate row failures, and remain idempotent after completion. + +## States and presentation + +- Success/error flash messages can be dismissed and are exposed as live regions. +- Forms have labels, required/min/max/pattern constraints, visible focus states, and useful backend feedback. +- Remote-image failures reveal initials instead of a broken image. +- Pages have no unintended horizontal overflow at 375 px mobile and 1,400 px desktop widths. +- Primary content, navigation, actions, tables/cards, progress bars, and footer remain visually legible at both widths. + +## Exploratory and edge-case scenarios + +- Authentication and password recovery normalize surrounding whitespace and email casing without weakening the generic anti-enumeration response. +- Avatar validation rejects credential-bearing, non-HTTPS, and excessively long remote URLs on both the form and server boundaries. +- Spreadsheet parsing rejects sparse or oversized workbooks before iterating an unbounded row range, and a retried job does not duplicate successful users. +- Deleting a non-final administrator preserves completed import history without leaving a broken creator reference in the import list or detail view. +- Authenticated users who revisit guest-only login or registration routes are returned to their role-appropriate destination. + +## Verification matrix + +| Layer | Coverage | +| --- | --- | +| Models/services/queries/jobs | Minitest, parallel execution, line and branch thresholds | +| HTTP/auth/security boundaries | Rails integration tests | +| Browser journeys | Capybara + Selenium + headless Chromium | +| Interactive presentation | Production Docker image in desktop and mobile browser viewports | +| Static quality | RuboCop, Brakeman, bundler-audit, importmap audit, CodeQL | +| Delivery | Multi-stage Docker build, Compose health checks, PostgreSQL, Solid Queue, Solid Cable, Kamal configuration | diff --git a/docs/qa-report.md b/docs/qa-report.md new file mode 100644 index 000000000..29171475e --- /dev/null +++ b/docs/qa-report.md @@ -0,0 +1,88 @@ +# QA report + +Validation date: 2026-09-02 + +## Complete CI gate + +Command: + +```bash +docker compose --profile tools run --rm test bin/ci +``` + +Result: passed in 30.84 seconds. + +| Check | Result | +| --- | --- | +| RuboCop | 89 files, 0 offenses | +| bundler-audit | 0 known vulnerable gems | +| importmap audit | 0 vulnerable packages | +| Brakeman 8.0.6 | 0 errors, 0 security warnings | +| Zeitwerk eager loading | passed, no warnings | +| Rails model/service/query/job/controller tests | 120 tests, 497 assertions, 0 failures/errors/skips | +| Parallel coverage | 97.83% lines, 88.88% branches | +| Capybara/Selenium system tests | 4 tests, 26 assertions, 0 failures/errors/skips | +| Merged coverage after system tests | 99.63% lines, 89.58% branches | +| Seed replant | passed | + +The enforced thresholds are 90% line and 80% branch coverage. The Rails suite used 14 parallel processes; browser tests remained serialized to avoid shared-driver state. + +## Production container validation + +- Multi-stage `web`, `job`, and one-shot `setup` images built successfully from Ruby 4.0.6. +- Production assets were compiled through Propshaft/Tailwind without a runtime secret. +- The final image runs as UID/GID 1000 and excludes development/test gem groups. +- PostgreSQL prepared independent application, cache, queue, and cable databases. +- The latest primary-database migration completed an explicit down/up round trip in both test and production containers. +- PostgreSQL inspection confirmed `ON DELETE SET NULL` for import creators and imported-user audit references; deleting a real imported QA user preserved and anonymized its row history. +- `/up` returned HTTP 200 and the web container reached healthy state. +- `/`, `/manifest`, and `/service-worker` each returned HTTP 200 from the rebuilt final image. +- The dedicated Solid Queue supervisor started dispatcher, worker, and scheduler processes. +- Runtime inspection confirmed `RubyVM::ZJIT.enabled? == true`. +- Production response headers included CSP, a non-empty random script nonce, `nosniff`, frame protection, and strict referrer policy. +- A direct login POST without an authenticity token returned HTTP 422, and the request log filtered both email and password values. +- Worker/web logs contained no unexpected job or application failures; the deliberate CSRF probe logged the expected `ActionController::InvalidAuthenticityToken` event. +- `bin/kamal config` rendered successfully with non-secret placeholder environment values. + +## Interactive browser validation + +The production Docker application was reviewed interactively in the in-app Chromium browser in addition to the repeatable Selenium suite. + +### Desktop (1,400 × 1,000) + +- Landing page hierarchy, navigation, CTA, cards, and footer rendered correctly. +- Admin login persisted through the Turbo redirect and landed on `/admin`. +- Login and password recovery accepted deliberately uppercased, whitespace-padded email input after canonicalization. +- A mismatched password confirmation rendered inline validation with HTTP 422; a valid token reset the password, revoked prior sessions, and allowed login with the new password. +- An unreachable remote avatar produced the intentional “Preview unavailable” state and hid the broken image before submission. +- Dashboard rendered accurate role totals and no browser console warnings/errors. +- Creating and then removing a scoped QA record through the application service changed the open dashboard from 4 → 5 → 4 without a reload, proving the Solid Queue → Solid Cable → Turbo Stream path. +- User search reduced the desktop table to the expected record. +- Admin creation form exposed the intended attributes and kept role mutation separate. +- An import whose administrator had been deleted remained readable and displayed anonymized authorship as `Deleted user`. + +### Mobile (375 × 812) + +- No horizontal overflow was present on the user form, directory, dashboard, import list, import form, progress view, or profile. +- The desktop user table was hidden and two mobile user cards were visible. +- Dashboard statistics stacked cleanly and primary actions remained reachable. +- CSV/XLSX upload and both template links remained usable. +- Standard-user login landed on `/profile`; admin navigation was absent. +- Direct navigation to `/admin` as a standard user returned to the profile with a visible authorization alert. + +### Real background imports + +- A queued two-row CSV transitioned to completed with 100%, 2/2 processed, 2 created, and 0 failed on the already-open page. +- A duplicate-email CSV transitioned to completed-with-errors with 100%, 1/1 processed, and an escaped row-level `Email has already been taken` message. +- A fresh one-row CSV uploaded through the native browser file chooser completed asynchronously and created its user. +- The browser observed both state changes without reload while the separate production Solid Queue worker processed them. +- Browser console inspection after the journeys returned no warnings or errors. + +## Automated browser journeys + +- Visitor registers with a real PNG upload, sees the Stimulus preview, edits the profile, and signs out. +- Administrator creates, searches, promotes, and deletes a user with Turbo confirmation dialogs. +- Administrator imports CSV and sees final progress. +- Administrator imports XLSX and sees final progress. + +See [qa-inventory.md](qa-inventory.md) for the complete acceptance surface. diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 000000000..fe7c07b25 --- /dev/null +++ b/docs/security.md @@ -0,0 +1,79 @@ +# Security design and production checklist + +## Trust boundaries + +The application treats browser parameters, uploaded files, spreadsheet cells, remote image URLs, cookies, and job arguments as untrusted input. The server never fetches a remote avatar: it stores a validated HTTPS URL and lets the browser request it without a referrer, avoiding a server-side request-forgery boundary. + +## Implemented controls + +### Authentication and sessions + +- Rails 8 generated authentication customized around `User#email` and bcrypt. +- Passwords require at least 12 characters and are never logged. +- Login and password-reset requests are rate limited. +- Responses do not reveal whether an email exists during password recovery. +- Login resets the cookie session before issuing a new signed, HTTP-only, same-site cookie. +- The cookie is marked secure whenever the request is HTTPS, including TLS terminated by the configured production proxy. +- Password changes revoke all persisted sessions. +- Authentication return URLs must parse and match the current host. +- Action Cable rejects connections without a valid persisted session. + +### Authorization + +- `Admin::BaseController` protects every administrative route. +- Profile routes do not accept a user identifier and always use `Current.user`. +- Visitor registration forces `role: :user` after structural parameter filtering. +- Role changes use a dedicated admin-only endpoint; normal create/update parameters do not accept `role`. +- Deterministic PostgreSQL row locks protect the final-administrator invariant under concurrency. + +### Request and output handling + +- Rails CSRF protection remains enabled for all state-changing browser requests. +- `params.expect` defines the accepted shape at every mutation boundary. +- Rails output escaping neutralizes stored HTML/script content. +- User search uses bound parameters and `sanitize_sql_like`, so quote and wildcard input cannot alter SQL meaning. +- Content Security Policy defaults to same-origin, blocks objects and framing, limits form targets, and uses a cryptographically random nonce for scripts. +- Production host authorization rejects unexpected host headers; HTTPS deployments enable HSTS/redirect behavior while excluding only the health endpoint. +- Sensitive keys, tokens, passwords, emails, and import payloads are filtered from logs. + +### Files and imports + +- Avatar uploads accept only JPEG, PNG, or WebP and are limited to 5 MB. +- Remote avatars require HTTPS, a host, no embedded username/password, and at most 2,048 characters. +- Spreadsheet uploads require a matching CSV/XLSX extension and content type and are limited to 5 MB. +- XLSX archives are bounded by entry count, expanded size, and physical sheet rows before cell iteration to limit archive-expansion and sparse-sheet denial of service. +- Parsed imports require explicit columns and at least one but no more than 1,000 data rows. +- Imported attributes are sliced to an allowlist; role values use an explicit mapping. +- Uniqueness races are handled at both model and database-index layers. +- Row errors are truncated before persistence and rendered through normal HTML escaping. +- Successful rows are durable and terminal jobs are idempotent. + +### Persistence and secrets + +- PostgreSQL foreign keys and check constraints defend critical invariants below the model layer. +- Import history survives creator or imported-user deletion through nullable audit references and database-level `ON DELETE SET NULL` foreign keys. +- Passwords are stored only as one-way bcrypt digests, and no recoverable application secret is persisted in domain tables. Email remains queryable for authentication, search, and a case-insensitive unique index, so it is protected through access control and log filtering rather than ineffective reversible application encryption. +- No production credential or key is committed. `.env`, Rails master keys, and Kamal secrets are ignored. +- SMTP may be read from encrypted Rails credentials or environment variables. Environment variables take precedence. +- The final container runs as an unprivileged user and contains no development/test gem group. + +## Verified attack-oriented checks + +- SQL-like search input is treated as literal text. +- Stored script-shaped names render escaped and never create executable elements. +- Non-admin requests to admin routes redirect without disclosing admin content. +- Visitor and profile/admin update parameters cannot assign a role. +- Insecure/credential-bearing avatar URLs, unsafe upload types, oversized files, duplicate emails, malformed spreadsheets, and missing columns are rejected. +- Brakeman runs with warning/error exit status; bundler-audit, importmap audit, and CodeQL are delivery gates. + +## Production checklist + +- Replace all example hosts and registry values in `config/deploy.yml`. +- Generate a strong `SECRET_KEY_BASE`; load registry, database, and SMTP secrets from a password manager. +- Use a dedicated PostgreSQL role and encrypted backups; restrict port 5432 to localhost/private networking. +- Keep `APP_PROTOCOL=https`, confirm proxy TLS/HSTS behavior, and test secure cookies through the real hostname. +- Configure SMTP or intentionally accept file delivery; monitor failed Solid Queue jobs. +- Use S3-compatible Active Storage for multi-host deployments and enforce bucket encryption/lifecycle policy. +- Add centralized error reporting without attaching filtered parameters or spreadsheet payloads. +- Patch base images and gems continuously; keep CI security gates required for merge. +- Define retention/deletion policy for import files, row errors, sessions, finished jobs, and generated mail files. diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/log/.keep b/log/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/public/400.html b/public/400.html new file mode 100644 index 000000000..640de0339 --- /dev/null +++ b/public/400.html @@ -0,0 +1,135 @@ + + + + + + + The server cannot process the request due to a client error (400 Bad Request) + + + + + + + + + + + + + +
+
+ +
+
+

The server cannot process the request due to a client error. Please check the request and try again. If you're the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/404.html b/public/404.html new file mode 100644 index 000000000..d7f0f1422 --- /dev/null +++ b/public/404.html @@ -0,0 +1,135 @@ + + + + + + + The page you were looking for doesn't exist (404 Not found) + + + + + + + + + + + + + +
+
+ +
+
+

The page you were looking for doesn't exist. You may have mistyped the address or the page may have moved. If you're the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/406-unsupported-browser.html b/public/406-unsupported-browser.html new file mode 100644 index 000000000..43d2811e8 --- /dev/null +++ b/public/406-unsupported-browser.html @@ -0,0 +1,135 @@ + + + + + + + Your browser is not supported (406 Not Acceptable) + + + + + + + + + + + + + +
+
+ +
+
+

Your browser is not supported.
Please upgrade your browser to continue.

+
+
+ + + + diff --git a/public/422.html b/public/422.html new file mode 100644 index 000000000..f12fb4aa1 --- /dev/null +++ b/public/422.html @@ -0,0 +1,135 @@ + + + + + + + The change you wanted was rejected (422 Unprocessable Entity) + + + + + + + + + + + + + +
+
+ +
+
+

The change you wanted was rejected. Maybe you tried to change something you didn't have access to. If you're the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/500.html b/public/500.html new file mode 100644 index 000000000..e4eb18a75 --- /dev/null +++ b/public/500.html @@ -0,0 +1,135 @@ + + + + + + + We're sorry, but something went wrong (500 Internal Server Error) + + + + + + + + + + + + + +
+
+ +
+
+

We're sorry, but something went wrong.
If you're the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/icon.png b/public/icon.png new file mode 100644 index 000000000..c4c9dbfbb Binary files /dev/null and b/public/icon.png differ diff --git a/public/icon.svg b/public/icon.svg new file mode 100644 index 000000000..04b34bf83 --- /dev/null +++ b/public/icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 000000000..c19f78ab6 --- /dev/null +++ b/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/public/user_import_template.csv b/public/user_import_template.csv new file mode 100644 index 000000000..a9f8880e0 --- /dev/null +++ b/public/user_import_template.csv @@ -0,0 +1,3 @@ +full_name,email,avatar_image_url,role +Grace Hopper,grace.hopper@example.com,https://example.com/grace.jpg,user +Katherine Johnson,katherine.johnson@example.com,https://example.com/katherine.jpg,admin diff --git a/public/user_import_template.xlsx b/public/user_import_template.xlsx new file mode 100644 index 000000000..aba079d3b Binary files /dev/null and b/public/user_import_template.xlsx differ diff --git a/script/.keep b/script/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/script/generate_import_templates.rb b/script/generate_import_templates.rb new file mode 100644 index 000000000..015002e26 --- /dev/null +++ b/script/generate_import_templates.rb @@ -0,0 +1,94 @@ +#!/usr/bin/env ruby + +require "cgi" +require "csv" +require "fileutils" +require "zip" + +ROOT = File.expand_path("..", __dir__) +HEADERS = %w[full_name email avatar_image_url role].freeze +ROWS = [ + [ "Grace Hopper", "grace.hopper@example.com", "https://example.com/grace.jpg", "user" ], + [ "Katherine Johnson", "katherine.johnson@example.com", "https://example.com/katherine.jpg", "admin" ] +].freeze + +def write_csv(path) + FileUtils.mkdir_p(File.dirname(path)) + CSV.open(path, "wb") do |csv| + csv << HEADERS + ROWS.each { |row| csv << row } + end +end + +def cell(reference, value) + escaped_value = CGI.escapeHTML(value) + %(#{escaped_value}) +end + +def sheet_xml + rows = [ HEADERS, *ROWS ].each_with_index.map do |values, row_index| + cells = values.each_with_index.map do |value, column_index| + reference = "#{('A'.ord + column_index).chr}#{row_index + 1}" + cell(reference, value) + end.join + %(#{cells}) + end.join + + <<~XML + + + #{rows} + + XML +end + +def write_xlsx(path) + FileUtils.mkdir_p(File.dirname(path)) + FileUtils.rm_f(path) + + Zip::File.open(path, create: true) do |zip| + zip.get_output_stream("[Content_Types].xml") do |file| + file.write <<~XML + + + + + + + + XML + end + zip.get_output_stream("_rels/.rels") do |file| + file.write <<~XML + + + + + XML + end + zip.get_output_stream("xl/workbook.xml") do |file| + file.write <<~XML + + + + + XML + end + zip.get_output_stream("xl/_rels/workbook.xml.rels") do |file| + file.write <<~XML + + + + + XML + end + zip.get_output_stream("xl/worksheets/sheet1.xml") { |file| file.write(sheet_xml) } + end +end + +write_csv(File.join(ROOT, "public/user_import_template.csv")) +write_csv(File.join(ROOT, "test/fixtures/files/valid_users.csv")) +write_xlsx(File.join(ROOT, "public/user_import_template.xlsx")) +write_xlsx(File.join(ROOT, "test/fixtures/files/valid_users.xlsx")) + +puts "Generated CSV and XLSX import templates." diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb new file mode 100644 index 000000000..35aec9361 --- /dev/null +++ b/test/application_system_test_case.rb @@ -0,0 +1,16 @@ +require "test_helper" + +Capybara.register_driver :selenium_chromium_headless do |app| + options = Selenium::WebDriver::Chrome::Options.new + options.binary = ENV["CHROME_BIN"] if ENV["CHROME_BIN"].present? + options.add_argument("--headless=new") + options.add_argument("--no-sandbox") + options.add_argument("--disable-dev-shm-usage") + options.add_argument("--window-size=1400,1000") + + Capybara::Selenium::Driver.new(app, browser: :chrome, options:) +end + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium_chromium_headless +end diff --git a/test/controllers/.keep b/test/controllers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/controllers/admin/dashboard_controller_test.rb b/test/controllers/admin/dashboard_controller_test.rb new file mode 100644 index 000000000..360361e4c --- /dev/null +++ b/test/controllers/admin/dashboard_controller_test.rb @@ -0,0 +1,29 @@ +require "test_helper" + +class Admin::DashboardControllerTest < ActionDispatch::IntegrationTest + test "renders live statistics for an administrator" do + sign_in_as(users(:admin)) + + get admin_root_path + + assert_response :success + assert_select "#dashboard_stats" + assert_select "turbo-cable-stream-source[channel='Turbo::StreamsChannel']" + assert_match User.count.to_s, response.body + end + + test "redirects a standard user to their profile" do + sign_in_as(users(:member)) + + get admin_root_path + + assert_redirected_to profile_path + assert_equal "You are not authorized to access that page.", flash[:alert] + end + + test "requires authentication" do + get admin_root_path + + assert_redirected_to new_session_path + end +end diff --git a/test/controllers/admin/user_imports_controller_test.rb b/test/controllers/admin/user_imports_controller_test.rb new file mode 100644 index 000000000..6bcf4e1ba --- /dev/null +++ b/test/controllers/admin/user_imports_controller_test.rb @@ -0,0 +1,94 @@ +require "test_helper" + +class Admin::UserImportsControllerTest < ActionDispatch::IntegrationTest + include ActiveJob::TestHelper + + setup { sign_in_as(users(:admin)) } + + test "lists imports and renders the upload form" do + get admin_user_imports_path + assert_response :success + + get new_admin_user_import_path + assert_response :success + assert_select "input[type=file][accept]" + end + + test "queues a valid CSV import" do + spreadsheet = fixture_file_upload("valid_users.csv", "text/csv") + + assert_enqueued_with(job: Imports::ProcessJob) do + assert_difference "UserImport.count", 1 do + post admin_user_imports_path, params: { user_import: { spreadsheet: } } + end + end + + assert_redirected_to admin_user_import_path(UserImport.last) + end + + test "accepts a valid XLSX import" do + spreadsheet = fixture_file_upload( + "valid_users.xlsx", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + ) + + assert_difference "UserImport.count", 1 do + post admin_user_imports_path, params: { user_import: { spreadsheet: } } + end + + assert_redirected_to admin_user_import_path(UserImport.last) + end + + test "rejects an unsupported upload" do + spreadsheet = fixture_file_upload("unsupported.txt", "text/plain") + + assert_no_difference "UserImport.count" do + post admin_user_imports_path, params: { user_import: { spreadsheet: } } + end + + assert_response :unprocessable_entity + assert_select "[role=alert]" + end + + test "shows durable progress and row failures" do + user_import = create_import + user_import.update!(status: :completed_with_errors, total_rows: 1, processed_rows: 1, failed_rows: 1) + user_import.rows.create!(row_number: 2, payload: { "email" => "bad@example.com" }, status: :failed, + error_message: "Email is invalid") + + get admin_user_import_path(user_import) + + assert_response :success + assert_select "progress[value='100']" + assert_match "Email is invalid", response.body + end + + test "does not expose imports to a standard user" do + sign_out + sign_in_as(users(:member)) + + get admin_user_imports_path + + assert_redirected_to profile_path + end + + test "renders preserved imports after their creator is deleted" do + creator = User.create!(valid_user_attributes(email: "former-admin@example.com", role: :admin)) + user_import = UserImport.create!(created_by: creator, spreadsheet: { + io: StringIO.new("placeholder"), filename: "users.csv", content_type: "text/csv" + }) + creator.destroy! + + get admin_user_import_path(user_import) + + assert_response :success + assert_select "p", /Deleted user/ + end + + private + def create_import + UserImport.create!(created_by: users(:admin), spreadsheet: { + io: StringIO.new("placeholder"), filename: "users.csv", content_type: "text/csv" + }) + end +end diff --git a/test/controllers/admin/users_controller_test.rb b/test/controllers/admin/users_controller_test.rb new file mode 100644 index 000000000..62ca0dccb --- /dev/null +++ b/test/controllers/admin/users_controller_test.rb @@ -0,0 +1,136 @@ +require "test_helper" + +class Admin::UsersControllerTest < ActionDispatch::IntegrationTest + include ActiveJob::TestHelper + + setup { sign_in_as(users(:admin)) } + + test "renders new and edit forms" do + get new_admin_user_path + assert_response :success + assert_select "form[action='#{admin_users_path}']" + + get edit_admin_user_path(users(:member)) + assert_response :success + assert_select "form[action='#{admin_user_path(users(:member))}']" + end + + test "lists users and escapes names in rendered HTML" do + user = User.create!(valid_user_attributes(full_name: "")) + + get admin_users_path + + assert_response :success + assert_no_match "", response.body + assert_includes response.body, ERB::Util.html_escape(user.full_name) + end + + test "searches without interpreting SQL injection syntax" do + get admin_users_path, params: { query: "' OR 1=1 --" } + + assert_response :success + assert_select "[data-testid=user-row]", count: 0 + end + + test "creates an invited user" do + assert_enqueued_emails 1 do + assert_difference "User.count", 1 do + post admin_users_path, params: { + user: valid_user_attributes(email: "managed@example.com").except(:password, :password_confirmation) + } + end + end + + assert_redirected_to admin_users_path + end + + test "renders validation errors when creation fails" do + assert_no_difference "User.count" do + post admin_users_path, params: { user: { full_name: "", email: "invalid", avatar_image_url: "" } } + end + + assert_response :unprocessable_entity + assert_select "[role=alert]" + end + + test "updates a user without allowing role assignment" do + user = users(:member) + + patch admin_user_path(user), params: { + user: { full_name: "Managed Member", email: user.email, avatar_image_url: user.avatar_image_url, role: :admin } + } + + assert_redirected_to admin_users_path + assert_equal "Managed Member", user.reload.full_name + assert_predicate user, :user? + end + + test "renders validation errors when an update fails" do + user = users(:member) + + patch admin_user_path(user), params: { user: { full_name: "", email: "invalid", avatar_image_url: "" } } + + assert_response :unprocessable_entity + assert_select "[role=alert]" + assert_equal users(:member).email, user.reload.email + end + + test "toggles a role through the explicit endpoint" do + user = users(:member) + + patch toggle_role_admin_user_path(user) + + assert_redirected_to admin_users_path + assert_predicate user.reload, :admin? + end + + test "deletes a managed user" do + user = users(:member) + + assert_difference "User.count", -1 do + delete admin_user_path(user) + end + + assert_redirected_to admin_users_path + end + + test "deleting the signed-in administrator terminates their session" do + admin = users(:admin) + + assert_difference [ "User.count", "Session.count" ], -1 do + delete admin_user_path(admin) + end + + assert_redirected_to root_path + assert_empty cookies[:session_id] + end + + test "does not demote the final administrator" do + users(:second_admin).update!(role: :user) + admin = users(:admin) + + patch toggle_role_admin_user_path(admin) + + assert_redirected_to admin_users_path + assert_match "last administrator", flash[:alert] + assert_predicate admin.reload, :admin? + end + + test "a self-demoted administrator is redirected to their profile" do + admin = users(:admin) + + patch toggle_role_admin_user_path(admin) + + assert_redirected_to profile_path + assert_predicate admin.reload, :user? + end + + test "does not expose administration to a standard user" do + sign_out + sign_in_as(users(:member)) + + get admin_users_path + + assert_redirected_to profile_path + end +end diff --git a/test/controllers/home_controller_test.rb b/test/controllers/home_controller_test.rb new file mode 100644 index 000000000..96e7be8a0 --- /dev/null +++ b/test/controllers/home_controller_test.rb @@ -0,0 +1,38 @@ +require "test_helper" + +class HomeControllerTest < ActionDispatch::IntegrationTest + test "renders the public landing page with security headers" do + get root_path + + assert_response :success + assert_select "h1", /User management/ + assert_match "frame-ancestors 'none'", response.headers.fetch("Content-Security-Policy") + assert_match(/script-src 'self' 'nonce-[^']+'/i, response.headers.fetch("Content-Security-Policy")) + assert_equal "nosniff", response.headers["X-Content-Type-Options"] + end + + test "redirects a signed-in standard user to the profile" do + sign_in_as(users(:member)) + + get root_path + + assert_redirected_to profile_path + end + + test "redirects a signed-in administrator to the dashboard" do + sign_in_as(users(:admin)) + + get root_path + + assert_redirected_to admin_root_path + end + + test "serves installable application metadata and the service worker endpoint" do + get pwa_manifest_path(format: :json) + assert_response :success + assert_equal "Umanni Users", response.parsed_body.fetch("name") + + get pwa_service_worker_path + assert_response :success + end +end diff --git a/test/controllers/passwords_controller_test.rb b/test/controllers/passwords_controller_test.rb new file mode 100644 index 000000000..0058e9a1a --- /dev/null +++ b/test/controllers/passwords_controller_test.rb @@ -0,0 +1,70 @@ +require "test_helper" + +class PasswordsControllerTest < ActionDispatch::IntegrationTest + setup { @user = users(:member) } + + test "renders password recovery" do + get new_password_path + assert_response :success + end + + test "queues reset email for a known user" do + assert_enqueued_email_with PasswordsMailer, :reset, args: [ @user ] do + post passwords_path, params: { email: @user.email } + end + assert_redirected_to new_session_path + end + + test "normalizes email casing and whitespace for password recovery" do + assert_enqueued_email_with PasswordsMailer, :reset, args: [ @user ] do + post passwords_path, params: { email: " #{@user.email.upcase} " } + end + + assert_redirected_to new_session_path + end + + test "returns identical response for an unknown email" do + assert_no_enqueued_emails do + post passwords_path, params: { email: "missing@example.com" } + end + assert_redirected_to new_session_path + assert_match "if user with that email", flash[:notice] + end + + test "renders a valid reset token" do + get edit_password_path(@user.password_reset_token) + assert_response :success + end + + test "rejects an invalid reset token" do + get edit_password_path("invalid-token") + assert_redirected_to new_password_path + assert_match "invalid or has expired", flash[:alert] + end + + test "updates password and revokes every session" do + @user.sessions.create! + + assert_changes -> { @user.reload.password_digest } do + put password_path(@user.password_reset_token), params: { + user: { password: "NewSecurePass123!", password_confirmation: "NewSecurePass123!" } + } + end + + assert_redirected_to new_session_path + assert_empty @user.sessions.reload + end + + test "rejects non-matching passwords" do + token = @user.password_reset_token + + assert_no_changes -> { @user.reload.password_digest } do + put password_path(token), params: { + user: { password: "NewSecurePass123!", password_confirmation: "DifferentPass123!" } + } + end + + assert_response :unprocessable_entity + assert_select "[role=alert]", /confirmation/ + end +end diff --git a/test/controllers/profiles_controller_test.rb b/test/controllers/profiles_controller_test.rb new file mode 100644 index 000000000..10a46059a --- /dev/null +++ b/test/controllers/profiles_controller_test.rb @@ -0,0 +1,70 @@ +require "test_helper" + +class ProfilesControllerTest < ActionDispatch::IntegrationTest + setup do + @user = users(:member) + sign_in_as(@user) + end + + test "shows only the signed-in profile" do + get profile_path + + assert_response :success + assert_select "h1", @user.full_name + assert_no_match users(:admin).email, response.body + end + + test "renders the edit form" do + get edit_profile_path + + assert_response :success + assert_select "form[action='#{profile_path}']" + end + + test "updates the signed-in profile without accepting a role" do + patch profile_path, params: { + user: { full_name: "Grace Updated", email: "grace.updated@example.com", role: :admin } + } + + assert_redirected_to profile_path + assert_equal "Grace Updated", @user.reload.full_name + assert_predicate @user, :user? + end + + test "renders invalid profile updates" do + patch profile_path, params: { user: { full_name: "", email: "invalid" } } + + assert_response :unprocessable_entity + assert_select "[role=alert]" + end + + test "deletes the account and terminates the session" do + assert_difference [ "User.count", "Session.count" ], -1 do + delete profile_path + end + + assert_redirected_to root_path + assert_empty cookies[:session_id] + end + + test "preserves a final administrator account" do + sign_out + users(:second_admin).update!(role: :user) + sign_in_as(users(:admin)) + + assert_no_difference "User.count" do + delete profile_path + end + + assert_redirected_to profile_path + assert_match "last administrator", flash[:alert] + end + + test "requires authentication" do + sign_out + + get profile_path + + assert_redirected_to new_session_path + end +end diff --git a/test/controllers/registrations_controller_test.rb b/test/controllers/registrations_controller_test.rb new file mode 100644 index 000000000..23fc0f69e --- /dev/null +++ b/test/controllers/registrations_controller_test.rb @@ -0,0 +1,47 @@ +require "test_helper" + +class RegistrationsControllerTest < ActionDispatch::IntegrationTest + test "renders registration for a visitor" do + get new_registration_path + + assert_response :success + assert_select "h1", "Create your user profile" + end + + test "registers, signs in, and forces the standard user role" do + attributes = valid_user_attributes(email: "visitor@example.com").merge(role: :admin) + + assert_difference [ "User.count", "Session.count" ], 1 do + post registration_path, params: { user: attributes } + end + + user = User.find_by!(email: "visitor@example.com") + assert_predicate user, :user? + assert_redirected_to profile_path + end + + test "renders validation feedback without creating an account" do + assert_no_difference "User.count" do + post registration_path, params: { user: valid_user_attributes(email: "invalid") } + end + + assert_response :unprocessable_entity + assert_select "[role=alert]", /Email/ + end + + test "redirects an authenticated user away from registration" do + sign_in_as(users(:member)) + + get new_registration_path + + assert_redirected_to profile_path + end + + test "redirects an authenticated administrator to the dashboard" do + sign_in_as(users(:admin)) + + get new_registration_path + + assert_redirected_to admin_root_path + end +end diff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rb new file mode 100644 index 000000000..96e33148c --- /dev/null +++ b/test/controllers/sessions_controller_test.rb @@ -0,0 +1,67 @@ +require "test_helper" + +class SessionsControllerTest < ActionDispatch::IntegrationTest + setup { @user = users(:member) } + + test "renders sign in" do + get new_session_path + assert_response :success + assert_select "h1", "Sign in to your workspace" + end + + test "redirects an already authenticated user away from sign in" do + sign_in_as(@user) + + get new_session_path + + assert_redirected_to profile_path + end + + test "redirects a standard user to profile" do + post session_path, params: { email: @user.email, password: "SecurePass123!" } + + assert_redirected_to profile_url + assert cookies[:session_id] + end + + test "normalizes email casing and whitespace before authentication" do + post session_path, params: { email: " #{@user.email.upcase} ", password: "SecurePass123!" } + + assert_redirected_to profile_url + assert cookies[:session_id] + end + + test "redirects an administrator to dashboard" do + post session_path, params: { email: users(:admin).email, password: "SecurePass123!" } + + assert_redirected_to admin_root_url + end + + test "returns to a same-host protected page after authentication" do + get edit_profile_path + assert_redirected_to new_session_path + + post session_path, params: { email: @user.email, password: "SecurePass123!" } + + assert_redirected_to edit_profile_url + end + + test "rejects invalid credentials without disclosing which field failed" do + post session_path, params: { email: @user.email, password: "wrong-password" } + + assert_redirected_to new_session_path + assert_equal "The email or password is incorrect.", flash[:alert] + assert_nil cookies[:session_id] + end + + test "destroys the persisted session" do + sign_in_as(@user) + + assert_difference "Session.count", -1 do + delete session_path + end + + assert_redirected_to root_path + assert_empty cookies[:session_id] + end +end diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/fixtures/files/unsupported.txt b/test/fixtures/files/unsupported.txt new file mode 100644 index 000000000..f49d4f76c --- /dev/null +++ b/test/fixtures/files/unsupported.txt @@ -0,0 +1 @@ +This is not a user spreadsheet. diff --git a/test/fixtures/files/valid_users.csv b/test/fixtures/files/valid_users.csv new file mode 100644 index 000000000..a9f8880e0 --- /dev/null +++ b/test/fixtures/files/valid_users.csv @@ -0,0 +1,3 @@ +full_name,email,avatar_image_url,role +Grace Hopper,grace.hopper@example.com,https://example.com/grace.jpg,user +Katherine Johnson,katherine.johnson@example.com,https://example.com/katherine.jpg,admin diff --git a/test/fixtures/files/valid_users.xlsx b/test/fixtures/files/valid_users.xlsx new file mode 100644 index 000000000..aba079d3b Binary files /dev/null and b/test/fixtures/files/valid_users.xlsx differ diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml new file mode 100644 index 000000000..9d76e4648 --- /dev/null +++ b/test/fixtures/users.yml @@ -0,0 +1,22 @@ +<% password_digest = BCrypt::Password.create("SecurePass123!", cost: 4) %> + +admin: + full_name: Ada Admin + email: admin@example.com + password_digest: <%= password_digest %> + role: 1 + avatar_image_url: https://example.com/ada.png + +member: + full_name: Grace Member + email: member@example.com + password_digest: <%= password_digest %> + role: 0 + avatar_image_url: https://example.com/grace.png + +second_admin: + full_name: Linus Admin + email: linus@example.com + password_digest: <%= password_digest %> + role: 1 + avatar_image_url: https://example.com/linus.png diff --git a/test/helpers/.keep b/test/helpers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/integration/.keep b/test/integration/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/jobs/dashboard/broadcast_stats_job_test.rb b/test/jobs/dashboard/broadcast_stats_job_test.rb new file mode 100644 index 000000000..fe0858431 --- /dev/null +++ b/test/jobs/dashboard/broadcast_stats_job_test.rb @@ -0,0 +1,9 @@ +require "test_helper" + +class Dashboard::BroadcastStatsJobTest < ActiveJob::TestCase + test "broadcasts the current dashboard statistics" do + assert_nothing_raised do + Dashboard::BroadcastStatsJob.perform_now + end + end +end diff --git a/test/jobs/imports/process_job_test.rb b/test/jobs/imports/process_job_test.rb new file mode 100644 index 000000000..57ae7056b --- /dev/null +++ b/test/jobs/imports/process_job_test.rb @@ -0,0 +1,105 @@ +require "test_helper" + +class Imports::ProcessJobTest < ActiveJob::TestCase + test "processes every valid row and completes the import" do + user_import = import_from("valid_users.csv", "text/csv") + + assert_difference "User.count", 2 do + Imports::ProcessJob.perform_now(user_import) + end + + user_import.reload + assert_predicate user_import, :completed? + assert_equal 2, user_import.total_rows + assert_equal 2, user_import.processed_rows + assert_equal 2, user_import.succeeded_rows + assert_equal 0, user_import.failed_rows + assert user_import.finished_at + end + + test "processes a valid XLSX workbook" do + user_import = import_from( + "valid_users.xlsx", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + ) + + assert_difference "User.count", 2 do + Imports::ProcessJob.perform_now(user_import) + end + + assert_predicate user_import.reload, :completed? + assert_equal 2, user_import.succeeded_rows + end + + test "completes with errors while preserving successful rows" do + csv = <<~CSV + full_name,email,avatar_image_url,role + New Person,new-person@example.com,https://example.com/new.png,user + Existing Person,#{users(:member).email},https://example.com/existing.png,user + CSV + user_import = import_from_contents(csv) + + assert_difference "User.count", 1 do + Imports::ProcessJob.perform_now(user_import) + end + + user_import.reload + assert_predicate user_import, :completed_with_errors? + assert_equal 1, user_import.succeeded_rows + assert_equal 1, user_import.failed_rows + assert_match "already been taken", user_import.rows.failed.first.error_message + end + + test "marks a structurally invalid spreadsheet as failed" do + user_import = import_from_contents("full_name,email\nAda,ada@example.com\n") + + assert_no_difference "User.count" do + Imports::ProcessJob.perform_now(user_import) + end + + assert_predicate user_import.reload, :failed? + assert_match "Missing required columns", user_import.failure_message + end + + test "is idempotent after reaching a terminal state" do + user_import = import_from("valid_users.csv", "text/csv") + user_import.update!(status: :completed, finished_at: Time.current) + + assert_no_difference [ "User.count", "UserImportRow.count" ] do + Imports::ProcessJob.perform_now(user_import) + end + end + + test "records a safe failure after the final retry of an unexpected error" do + user_import = import_from("valid_users.csv", "text/csv") + blob = user_import.spreadsheet.blob + blob.service.delete(blob.key) + job = Imports::ProcessJob.new(user_import) + job.exception_executions[[ StandardError ].to_s] = 2 + + assert_error_reported(ActiveStorage::FileNotFoundError) do + assert_no_enqueued_jobs do + assert_raises(ActiveStorage::FileNotFoundError) { job.perform_now } + end + end + + user_import.reload + assert_predicate user_import, :failed? + assert_equal "The import could not be completed after multiple attempts.", user_import.failure_message + assert_not_includes user_import.failure_message, blob.key + assert user_import.finished_at + end + + private + def import_from(filename, content_type) + UserImport.create!(created_by: users(:admin), spreadsheet: { + io: File.open(file_fixture(filename)), filename:, content_type: + }) + end + + def import_from_contents(contents) + UserImport.create!(created_by: users(:admin), spreadsheet: { + io: StringIO.new(contents), filename: "users.csv", content_type: "text/csv" + }) + end +end diff --git a/test/mailers/.keep b/test/mailers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/mailers/passwords_mailer_test.rb b/test/mailers/passwords_mailer_test.rb new file mode 100644 index 000000000..8cbfe1004 --- /dev/null +++ b/test/mailers/passwords_mailer_test.rb @@ -0,0 +1,23 @@ +require "test_helper" + +class PasswordsMailerTest < ActionMailer::TestCase + setup { @user = users(:member) } + + test "builds a reset email with an expiring token link" do + email = PasswordsMailer.reset(@user) + + assert_equal [ @user.email ], email.to + assert_equal "Reset your Umanni Users password", email.subject + assert_match %r{http://example\.com/passwords/.+/edit}, email.html_part.body.to_s + assert_match %r{http://example\.com/passwords/.+/edit}, email.text_part.body.to_s + end + + test "builds an invitation email with an account setup link" do + email = PasswordsMailer.invitation(@user) + + assert_equal [ @user.email ], email.to + assert_equal "Set up your Umanni Users account", email.subject + assert_match "Set up your password", email.html_part.body.to_s + assert_match %r{http://example\.com/passwords/.+/edit}, email.text_part.body.to_s + end +end diff --git a/test/models/.keep b/test/models/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/models/user_import_row_test.rb b/test/models/user_import_row_test.rb new file mode 100644 index 000000000..dcb24c7f2 --- /dev/null +++ b/test/models/user_import_row_test.rb @@ -0,0 +1,9 @@ +require "test_helper" + +class UserImportRowTest < ActiveSupport::TestCase + test "requires a physical spreadsheet row number" do + row = UserImportRow.new(row_number: 1, payload: { "email" => "test@example.com" }) + assert_not row.valid? + assert_includes row.errors[:row_number], "must be greater than or equal to 2" + end +end diff --git a/test/models/user_import_test.rb b/test/models/user_import_test.rb new file mode 100644 index 000000000..9a6ece3fc --- /dev/null +++ b/test/models/user_import_test.rb @@ -0,0 +1,84 @@ +require "test_helper" + +class UserImportTest < ActiveSupport::TestCase + test "computes bounded progress" do + user_import = UserImport.new(total_rows: 4, processed_rows: 3) + assert_equal 75, user_import.progress_percentage + + user_import.processed_rows = 8 + assert_equal 100, user_import.progress_percentage + end + + test "returns zero progress before rows are discovered" do + assert_equal 0, UserImport.new.progress_percentage + end + + test "recognizes terminal states" do + assert_not UserImport.new(status: :processing).terminal? + assert UserImport.new(status: :completed_with_errors).terminal? + end + + test "requires a spreadsheet" do + user_import = UserImport.new(created_by: users(:admin)) + assert_not user_import.valid? + assert_includes user_import.errors[:spreadsheet], "can't be blank" + end + + test "requires a creator when an import is first persisted" do + user_import = UserImport.new + user_import.spreadsheet.attach( + io: File.open(file_fixture("valid_users.csv")), filename: "valid_users.csv", content_type: "text/csv" + ) + + assert_not user_import.save + assert_includes user_import.errors[:created_by], "can't be blank" + end + + test "accepts CSV and XLSX spreadsheet attachments" do + csv_import = build_import("valid_users.csv", "text/csv") + xlsx_import = build_import( + "valid_users.xlsx", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + ) + + assert_predicate csv_import, :valid? + assert_predicate xlsx_import, :valid? + end + + test "rejects an unsupported spreadsheet extension and content type" do + user_import = build_import("unsupported.txt", "text/plain") + + assert_not_predicate user_import, :valid? + assert_includes user_import.errors[:spreadsheet], "must be a CSV or XLSX file" + assert_includes user_import.errors[:spreadsheet], "content type does not match its extension" + end + + test "rejects a supported content type paired with the wrong extension" do + user_import = build_import( + "valid_users.csv", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + ) + + assert_not_predicate user_import, :valid? + assert_includes user_import.errors[:spreadsheet], "content type does not match its extension" + end + + test "rejects oversized spreadsheets" do + user_import = UserImport.new(created_by: users(:admin)) + user_import.spreadsheet.attach( + io: StringIO.new("0" * (UserImport::MAX_FILE_SIZE + 1)), + filename: "users.csv", + content_type: "text/csv" + ) + + assert_not_predicate user_import, :valid? + assert_includes user_import.errors[:spreadsheet], "must be smaller than 5 MB" + end + + private + def build_import(filename, content_type) + UserImport.new(created_by: users(:admin), spreadsheet: { + io: File.open(file_fixture(filename)), filename:, content_type: + }) + end +end diff --git a/test/models/user_test.rb b/test/models/user_test.rb new file mode 100644 index 000000000..8083ebe25 --- /dev/null +++ b/test/models/user_test.rb @@ -0,0 +1,90 @@ +require "test_helper" + +class UserTest < ActiveSupport::TestCase + test "is valid with the required domain attributes" do + assert User.new(valid_user_attributes).valid? + end + + test "normalizes name, email, and blank remote avatar" do + user = User.new(valid_user_attributes(full_name: " Ada Lovelace ", email: " ADA@EXAMPLE.COM ", avatar_image_url: " ")) + + assert_equal "Ada Lovelace", user.full_name + assert_equal "ada@example.com", user.email + assert_nil user.avatar_image_url + end + + test "normalizes email values used for account lookup" do + assert_equal "member@example.com", User.normalized_email(" MEMBER@EXAMPLE.COM ") + end + + test "defaults to standard user role" do + assert_predicate User.new, :user? + end + + test "requires an avatar source" do + user = User.new(valid_user_attributes(avatar_image_url: nil)) + + assert_not user.valid? + assert_includes user.errors[:avatar_image], "or a remote avatar URL must be provided" + end + + test "accepts only secure remote avatars without credentials" do + [ "http://example.com/avatar.png", "https://user:pass@example.com/avatar.png", "not a url" ].each do |url| + user = User.new(valid_user_attributes(avatar_image_url: url)) + assert_not user.valid?, "expected #{url.inspect} to be rejected" + end + end + + test "rejects an excessively long remote avatar URL" do + oversized_url = "https://example.com/#{"a" * User::MAX_AVATAR_URL_LENGTH}" + user = User.new(valid_user_attributes(avatar_image_url: oversized_url)) + + assert_not_predicate user, :valid? + assert_includes user.errors[:avatar_image_url], "is too long (maximum is 2048 characters)" + end + + test "enforces case-insensitive email uniqueness" do + user = User.new(valid_user_attributes(email: users(:member).email.upcase)) + + assert_not user.valid? + assert_includes user.errors[:email], "has already been taken" + end + + test "requires a twelve character password" do + user = User.new(valid_user_attributes(password: "too-short", password_confirmation: "too-short")) + + assert_not user.valid? + assert_includes user.errors[:password], "is too short (minimum is 12 characters)" + end + + test "accepts supported avatar uploads" do + user = User.new(valid_user_attributes(avatar_image_url: nil)) + user.avatar_image.attach(io: File.open(Rails.root.join("public/icon.png")), filename: "avatar.png", content_type: "image/png") + + assert_predicate user, :valid? + end + + test "rejects unsupported avatar upload types" do + user = User.new(valid_user_attributes(avatar_image_url: nil)) + user.avatar_image.attach(io: StringIO.new("not an image"), filename: "avatar.txt", content_type: "text/plain") + + assert_not_predicate user, :valid? + assert_includes user.errors[:avatar_image], "must be a JPEG, PNG, or WebP image" + end + + test "rejects oversized avatar uploads" do + user = User.new(valid_user_attributes(avatar_image_url: nil)) + user.avatar_image.attach( + io: StringIO.new("0" * (User::MAX_AVATAR_SIZE + 1)), + filename: "avatar.png", + content_type: "image/png" + ) + + assert_not_predicate user, :valid? + assert_includes user.errors[:avatar_image], "must be smaller than 5 MB" + end + + test "builds initials from the first two names" do + assert_equal "AL", User.new(full_name: "Ada Lovelace Byron").initials + end +end diff --git a/test/queries/dashboard/stats_test.rb b/test/queries/dashboard/stats_test.rb new file mode 100644 index 000000000..386a9e2fe --- /dev/null +++ b/test/queries/dashboard/stats_test.rb @@ -0,0 +1,11 @@ +require "test_helper" + +class Dashboard::StatsTest < ActiveSupport::TestCase + test "returns total and role counts in one result" do + stats = Dashboard::Stats.call + + assert_equal User.count, stats.total + assert_equal User.admin.count, stats.admins + assert_equal User.user.count, stats.users + end +end diff --git a/test/queries/users/search_test.rb b/test/queries/users/search_test.rb new file mode 100644 index 000000000..51855383d --- /dev/null +++ b/test/queries/users/search_test.rb @@ -0,0 +1,25 @@ +require "test_helper" + +class Users::SearchTest < ActiveSupport::TestCase + test "searches names and email addresses case-insensitively" do + by_name = Users::Search.call(query: "grace", page: 1) + by_email = Users::Search.call(query: "LINUS@", page: 1) + + assert_equal [ users(:member) ], by_name.records.to_a + assert_equal [ users(:second_admin) ], by_email.records.to_a + end + + test "escapes SQL wildcard characters" do + result = Users::Search.call(query: "%_", page: 1) + + assert_empty result.records + end + + test "clamps invalid and out-of-range pages" do + first_page = Users::Search.call(query: nil, page: -10) + final_page = Users::Search.call(query: nil, page: 10_000) + + assert_equal 1, first_page.page + assert_equal first_page.total_pages, final_page.page + end +end diff --git a/test/services/imports/progress_updater_test.rb b/test/services/imports/progress_updater_test.rb new file mode 100644 index 000000000..2dd34d9cf --- /dev/null +++ b/test/services/imports/progress_updater_test.rb @@ -0,0 +1,25 @@ +require "test_helper" + +class Imports::ProgressUpdaterTest < ActiveSupport::TestCase + test "recalculates durable counters from row states" do + user_import = create_import + user_import.update!(status: :processing, total_rows: 3, started_at: Time.current) + user_import.rows.create!(row_number: 2, payload: { "email" => "a@example.com" }, status: :succeeded) + user_import.rows.create!(row_number: 3, payload: { "email" => "b@example.com" }, status: :failed) + user_import.rows.create!(row_number: 4, payload: { "email" => "c@example.com" }, status: :pending) + + Imports::ProgressUpdater.call(user_import) + + user_import.reload + assert_equal 2, user_import.processed_rows + assert_equal 1, user_import.succeeded_rows + assert_equal 1, user_import.failed_rows + end + + private + def create_import + UserImport.create!(created_by: users(:admin), spreadsheet: { + io: StringIO.new("placeholder"), filename: "users.csv", content_type: "text/csv" + }) + end +end diff --git a/test/services/imports/row_processor_test.rb b/test/services/imports/row_processor_test.rb new file mode 100644 index 000000000..72ede53f9 --- /dev/null +++ b/test/services/imports/row_processor_test.rb @@ -0,0 +1,72 @@ +require "test_helper" + +class Imports::RowProcessorTest < ActiveSupport::TestCase + include ActiveJob::TestHelper + + test "creates an invited user and marks the row successful" do + row = import_row(email: "imported@example.com", role: "admin") + + assert_enqueued_emails 1 do + assert_difference "User.count", 1 do + Imports::RowProcessor.call(row) + end + end + + assert_predicate row.reload, :succeeded? + assert_predicate row.user, :admin? + assert_nil row.error_message + end + + test "maps no-admin to the standard user role" do + row = import_row(email: "standard@example.com", role: "no-admin") + + Imports::RowProcessor.call(row) + + assert_predicate row.reload.user, :user? + end + + test "isolates validation errors on a row" do + row = import_row(email: users(:member).email) + + assert_no_difference "User.count" do + Imports::RowProcessor.call(row) + end + + assert_predicate row.reload, :failed? + assert_match "Email has already been taken", row.error_message + end + + test "rejects an unsupported role without creating a user" do + row = import_row(email: "invalid-role@example.com", role: "owner") + + assert_no_difference "User.count" do + Imports::RowProcessor.call(row) + end + + assert_predicate row.reload, :failed? + assert_match "Role must be", row.error_message + end + + test "turns a database uniqueness race into a row-level failure" do + row = import_row(email: "racing-import@example.com") + racing_creator = ->(**) { raise ActiveRecord::RecordNotUnique } + + assert_nothing_raised { Imports::RowProcessor.call(row, user_creator: racing_creator) } + + assert_predicate row.reload, :failed? + assert_equal "Email has already been taken.", row.error_message + end + + private + def import_row(email:, role: "user") + user_import = UserImport.create!(created_by: users(:admin), spreadsheet: { + io: StringIO.new("placeholder"), filename: "users.csv", content_type: "text/csv" + }) + user_import.rows.create!(row_number: 2, payload: { + "full_name" => "Imported Person", + "email" => email, + "avatar_image_url" => "https://example.com/imported.png", + "role" => role + }) + end +end diff --git a/test/services/imports/spreadsheet_parser_test.rb b/test/services/imports/spreadsheet_parser_test.rb new file mode 100644 index 000000000..81ae52ae3 --- /dev/null +++ b/test/services/imports/spreadsheet_parser_test.rb @@ -0,0 +1,109 @@ +require "test_helper" +require "tempfile" + +class Imports::SpreadsheetParserTest < ActiveSupport::TestCase + test "parses CSV headers and rows" do + rows = Imports::SpreadsheetParser.call(import_with_fixture("valid_users.csv", "text/csv")) + + assert_equal 2, rows.length + assert_equal 2, rows.first.number + assert_equal "Grace Hopper", rows.first.attributes.fetch("full_name") + assert_equal "user", rows.first.attributes.fetch("role") + end + + test "parses a real XLSX workbook" do + rows = Imports::SpreadsheetParser.call(import_with_fixture( + "valid_users.xlsx", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + )) + + assert_equal 2, rows.length + assert_equal "katherine.johnson@example.com", rows.second.attributes.fetch("email") + end + + test "normalizes friendly header names and ignores blank rows" do + csv = <<~CSV + Full Name,Email,Avatar Image URL,Role + Ada Example,ada-new@example.com,https://example.com/ada.png,admin + ,,, + CSV + + rows = Imports::SpreadsheetParser.call(import_with_csv(csv)) + + assert_equal 1, rows.length + assert_equal "Ada Example", rows.first.attributes.fetch("full_name") + end + + test "rejects missing required columns" do + error = assert_raises(Imports::SpreadsheetParser::Error) do + Imports::SpreadsheetParser.call(import_with_csv("full_name,email\nAda,ada@example.com\n")) + end + + assert_match "Missing required columns: avatar_image_url", error.message + end + + test "rejects empty spreadsheets" do + error = assert_raises(Imports::SpreadsheetParser::Error) do + Imports::SpreadsheetParser.call(import_with_csv("full_name,email,avatar_image_url,role\n")) + end + + assert_match "at least one data row", error.message + end + + test "rejects malformed CSV" do + error = assert_raises(Imports::SpreadsheetParser::Error) do + Imports::SpreadsheetParser.call(import_with_csv("full_name,email,avatar_image_url\n\"unterminated")) + end + + assert_equal "The spreadsheet could not be parsed. Verify the file format and try again.", error.message + end + + test "rejects a sparse XLSX sheet before iterating an unbounded row range" do + sheet = Struct.new(:last_row).new(Imports::SpreadsheetParser::MAX_ROWS + 2) + parser = Imports::SpreadsheetParser.new(import_with_fixture( + "valid_users.xlsx", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + )) + + error = assert_raises(Imports::SpreadsheetParser::Error) do + parser.send(:reject_oversized_sheet!, sheet) + end + + assert_match "cannot contain more than 1000", error.message + end + + test "rejects an XLSX archive with an excessive expanded size" do + parser = Imports::SpreadsheetParser.new(import_with_fixture( + "valid_users.xlsx", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + )) + + Tempfile.create([ "oversized", ".xlsx" ]) do |file| + Zip::OutputStream.open(file.path) do |archive| + archive.put_next_entry("xl/oversized.xml") + chunk = "0" * 1.megabyte + 26.times { archive.write(chunk) } + end + + error = assert_raises(Imports::SpreadsheetParser::Error) do + parser.send(:validate_xlsx_archive!, file.path) + end + + assert_match "expands beyond the 25 MB safety limit", error.message + end + end + + private + def import_with_fixture(filename, content_type) + user_import = UserImport.create!(created_by: users(:admin), spreadsheet: { + io: File.open(file_fixture(filename)), filename:, content_type: + }) + user_import + end + + def import_with_csv(contents) + UserImport.create!(created_by: users(:admin), spreadsheet: { + io: StringIO.new(contents), filename: "users.csv", content_type: "text/csv" + }) + end +end diff --git a/test/services/users/create_test.rb b/test/services/users/create_test.rb new file mode 100644 index 000000000..9d6e236cd --- /dev/null +++ b/test/services/users/create_test.rb @@ -0,0 +1,35 @@ +require "test_helper" + +class Users::CreateTest < ActiveSupport::TestCase + include ActiveJob::TestHelper + + test "creates a visitor account and broadcasts updated statistics" do + assert_enqueued_with(job: Dashboard::BroadcastStatsJob) do + assert_difference "User.count", 1 do + user = Users::Create.call(attributes: valid_user_attributes) + + assert_predicate user, :persisted? + assert_predicate user, :user? + end + end + end + + test "creates an invited account with a random password and invitation email" do + attributes = valid_user_attributes.except(:password, :password_confirmation) + + assert_enqueued_emails 1 do + user = Users::Create.call(attributes:, invite: true, broadcast: false) + + assert_predicate user, :persisted? + assert user.authenticate(user.password) + end + end + + test "does not enqueue side effects when validation fails" do + assert_no_enqueued_jobs do + user = Users::Create.call(attributes: valid_user_attributes(email: "invalid"), invite: true) + + assert_not_predicate user, :persisted? + end + end +end diff --git a/test/services/users/destroy_test.rb b/test/services/users/destroy_test.rb new file mode 100644 index 000000000..44218f627 --- /dev/null +++ b/test/services/users/destroy_test.rb @@ -0,0 +1,72 @@ +require "test_helper" + +class Users::DestroyTest < ActiveSupport::TestCase + include ActiveJob::TestHelper + + test "deletes a standard user and broadcasts updated statistics" do + user = users(:member) + + assert_enqueued_with(job: Dashboard::BroadcastStatsJob) do + assert_difference "User.count", -1 do + Users::Destroy.call(user:) + end + end + + assert_predicate user, :destroyed? + end + + test "does not delete the final administrator" do + users(:second_admin).update!(role: :user) + admin = users(:admin) + + assert_no_difference "User.count" do + Users::Destroy.call(user: admin) + end + + assert_includes admin.errors[:base], Users::Destroy::LAST_ADMIN_MESSAGE + end + + test "allows an administrator deletion while another administrator remains" do + admin = users(:admin) + + assert_difference "User.count", -1 do + Users::Destroy.call(user: admin) + end + end + + test "preserves import history when its administrator is deleted" do + admin = users(:admin) + user_import = UserImport.create!(created_by: admin, spreadsheet: { + io: StringIO.new("full_name,email,avatar_image_url\n"), filename: "users.csv", content_type: "text/csv" + }) + + assert_difference "User.count", -1 do + assert_no_difference "UserImport.count" do + Users::Destroy.call(user: admin) + end + end + + assert_nil user_import.reload.created_by + end + + test "deletes an imported user without deleting its row history" do + user = users(:member) + user_import = UserImport.create!(created_by: users(:admin), spreadsheet: { + io: StringIO.new("full_name,email,avatar_image_url\n"), filename: "users.csv", content_type: "text/csv" + }) + import_row = user_import.rows.create!( + row_number: 2, + payload: { "full_name" => user.full_name, "email" => user.email }, + status: :succeeded, + user: + ) + + assert_difference "User.count", -1 do + assert_no_difference "UserImportRow.count" do + Users::Destroy.call(user:) + end + end + + assert_nil import_row.reload.user + end +end diff --git a/test/services/users/toggle_role_test.rb b/test/services/users/toggle_role_test.rb new file mode 100644 index 000000000..0f7e62efd --- /dev/null +++ b/test/services/users/toggle_role_test.rb @@ -0,0 +1,33 @@ +require "test_helper" + +class Users::ToggleRoleTest < ActiveSupport::TestCase + include ActiveJob::TestHelper + + test "promotes a standard user" do + user = users(:member) + + assert_enqueued_with(job: Dashboard::BroadcastStatsJob) do + Users::ToggleRole.call(user:) + end + + assert_predicate user.reload, :admin? + end + + test "demotes an administrator while another remains" do + admin = users(:admin) + + Users::ToggleRole.call(user: admin) + + assert_predicate admin.reload, :user? + end + + test "does not demote the final administrator" do + users(:second_admin).update!(role: :user) + admin = users(:admin) + + assert_no_enqueued_jobs { Users::ToggleRole.call(user: admin) } + + assert_predicate admin.reload, :admin? + assert_includes admin.errors[:base], Users::ToggleRole::LAST_ADMIN_MESSAGE + end +end diff --git a/test/services/users/update_test.rb b/test/services/users/update_test.rb new file mode 100644 index 000000000..f2e745c75 --- /dev/null +++ b/test/services/users/update_test.rb @@ -0,0 +1,46 @@ +require "test_helper" + +class Users::UpdateTest < ActiveSupport::TestCase + include ActiveJob::TestHelper + + test "updates profile fields without changing the role" do + user = users(:member) + + Users::Update.call(user:, attributes: { full_name: "Updated Member", email: "updated@example.com" }) + + assert_equal "Updated Member", user.reload.full_name + assert_predicate user, :user? + end + + test "an uploaded avatar replaces a remote URL" do + user = users(:member) + upload = Rack::Test::UploadedFile.new(Rails.root.join("public/icon.png"), "image/png") + + Users::Update.call(user:, attributes: { avatar_image: upload }) + + assert_predicate user.reload.avatar_image, :attached? + assert_nil user.avatar_image_url + end + + test "a remote URL replaces an uploaded avatar after a valid save" do + user = users(:member) + user.avatar_image.attach(io: File.open(Rails.root.join("public/icon.png")), filename: "avatar.png", content_type: "image/png") + + assert_enqueued_with(job: ActiveStorage::PurgeJob) do + Users::Update.call(user:, attributes: { avatar_image_url: "https://example.com/new.png" }) + end + + assert_equal "https://example.com/new.png", user.reload.avatar_image_url + end + + test "preserves the existing upload when the replacement URL is invalid" do + user = users(:member) + user.avatar_image.attach(io: File.open(Rails.root.join("public/icon.png")), filename: "avatar.png", content_type: "image/png") + + assert_no_enqueued_jobs do + Users::Update.call(user:, attributes: { avatar_image_url: "http://insecure.example/avatar.png" }) + end + + assert_predicate user.reload.avatar_image, :attached? + end +end diff --git a/test/system/admin_spreadsheet_import_test.rb b/test/system/admin_spreadsheet_import_test.rb new file mode 100644 index 000000000..95f2e66cf --- /dev/null +++ b/test/system/admin_spreadsheet_import_test.rb @@ -0,0 +1,43 @@ +require "application_system_test_case" + +class AdminSpreadsheetImportTest < ApplicationSystemTestCase + test "an administrator imports a CSV and sees completed progress" do + sign_in_as_admin + click_link "Imports" + click_link "New import" + + perform_enqueued_jobs(only: Imports::ProcessJob) do + attach_file "CSV or XLSX spreadsheet", file_fixture("valid_users.csv") + click_button "Queue import" + assert_text "Import queued for background processing." + end + + assert_text(/\bcompleted\b/i) + assert_text "100% complete" + assert_text "2 of 2 rows processed" + assert_text "Created" + end + + test "an administrator imports an XLSX workbook" do + sign_in_as_admin + click_link "Imports" + click_link "New import" + + perform_enqueued_jobs(only: Imports::ProcessJob) do + attach_file "CSV or XLSX spreadsheet", file_fixture("valid_users.xlsx") + click_button "Queue import" + assert_text "Import queued for background processing." + end + + assert_text(/\bcompleted\b/i) + assert_text "2 of 2 rows processed" + end + + private + def sign_in_as_admin + visit new_session_path + fill_in "Email", with: users(:admin).email + fill_in "Password", with: "SecurePass123!" + click_button "Sign in" + end +end diff --git a/test/system/admin_user_management_test.rb b/test/system/admin_user_management_test.rb new file mode 100644 index 000000000..247e41b8a --- /dev/null +++ b/test/system/admin_user_management_test.rb @@ -0,0 +1,40 @@ +require "application_system_test_case" + +class AdminUserManagementTest < ApplicationSystemTestCase + test "an administrator creates, searches, promotes, and deletes a user" do + sign_in_as_admin + + assert_text "User dashboard" + assert_text "Total users" + click_link "Users" + click_link "Add user" + + fill_in "Full name", with: "Mary Jackson" + fill_in "Email", with: "mary.jackson@example.com" + fill_in "Remote image URL", with: "https://example.com/mary.png" + click_button "Create user" + + assert_text "User created. Password setup instructions were queued." + fill_in "Search by name or email", with: "mary.jackson" + click_button "Search" + assert_text "Mary Jackson" + + accept_confirm { click_button "Make admin" } + assert_text "Role changed to admin." + + fill_in "Search by name or email", with: "mary.jackson" + click_button "Search" + accept_confirm { click_button "Delete" } + + assert_text "User deleted." + assert_no_text "Mary Jackson" + end + + private + def sign_in_as_admin + visit new_session_path + fill_in "Email", with: users(:admin).email + fill_in "Password", with: "SecurePass123!" + click_button "Sign in" + end +end diff --git a/test/system/visitor_registration_test.rb b/test/system/visitor_registration_test.rb new file mode 100644 index 000000000..e6268353b --- /dev/null +++ b/test/system/visitor_registration_test.rb @@ -0,0 +1,32 @@ +require "application_system_test_case" + +class VisitorRegistrationTest < ApplicationSystemTestCase + test "a visitor registers, edits the profile, and signs out" do + visit root_path + click_link "Create your account" + + fill_in "Full name", with: "Dorothy Vaughan" + fill_in "Email", with: "dorothy@example.com" + fill_in "Password", with: "SecurePass123!", match: :first + fill_in "Password confirmation", with: "SecurePass123!" + attach_file "Upload image", Rails.root.join("public/icon.png") + assert_text "Local image selected" + click_button "Create account" + + assert_text "Welcome! Your account is ready." + assert_text "Dorothy Vaughan" + assert_text "dorothy@example.com" + assert_text(/\buser\b/i) + + click_link "Edit profile" + fill_in "Full name", with: "Dorothy J. Vaughan" + click_button "Save profile" + + assert_text "Your profile was updated." + assert_text "Dorothy J. Vaughan" + + click_button "Sign out" + assert_text "You have been signed out." + assert_link "Create your account" + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 000000000..37f236f86 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,26 @@ +ENV["RAILS_ENV"] ||= "test" +require "simplecov" + +SimpleCov.start "rails" do + enable_coverage :branch + minimum_coverage line: 90, branch: 80 unless ENV["COVERAGE"] == "false" +end + +require_relative "../config/environment" +require "rails/test_help" +require_relative "test_helpers/session_test_helper" + +module ActiveSupport + class TestCase + include ActiveJob::TestHelper + include ActionMailer::TestHelper + + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... + end +end diff --git a/test/test_helpers/session_test_helper.rb b/test/test_helpers/session_test_helper.rb new file mode 100644 index 000000000..38332965a --- /dev/null +++ b/test/test_helpers/session_test_helper.rb @@ -0,0 +1,32 @@ +module SessionTestHelper + def sign_in_as(user) + Current.session = user.sessions.create!(user_agent: "Rails test", ip_address: "127.0.0.1") + + ActionDispatch::TestRequest.create.cookie_jar.tap do |cookie_jar| + cookie_jar.signed[:session_id] = Current.session.id + cookies["session_id"] = cookie_jar[:session_id] + end + end + + def sign_out + Current.session&.destroy! + cookies.delete("session_id") + end + + def valid_user_attributes(overrides = {}) + { + full_name: "Test User", + email: "user-#{SecureRandom.hex(4)}@example.com", + avatar_image_url: "https://example.com/avatar.png", + password: "SecurePass123!", + password_confirmation: "SecurePass123!", + role: :user + }.merge(overrides) + end +end + +ActiveSupport.on_load(:action_dispatch_integration_test) do + include SessionTestHelper +end + +ActiveSupport::TestCase.include SessionTestHelper diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/tmp/pids/.keep b/tmp/pids/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/vendor/.keep b/vendor/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/vendor/javascript/.keep b/vendor/javascript/.keep new file mode 100644 index 000000000..e69de29bb