diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..59d4d91 --- /dev/null +++ b/.env.example @@ -0,0 +1,3 @@ +CLERK_JS_URL=https://YOUR_SUBDOMAIN.clerk.accounts.dev/npm/@clerk/clerk-js@latest/dist/clerk.browser.js +CLERK_PUBLISHABLE_KEY=pk_test_****** +CLERK_SECRET_KEY=sk_test_****** \ No newline at end of file diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 18f74d9..da6ba73 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -1,20 +1,28 @@ name: Ruby -on: [push,pull_request] +on: + push: + branches: + - main + pull_request: jobs: - build: + test: runs-on: ubuntu-latest + name: Ruby ${{ matrix.ruby }} + strategy: + matrix: + ruby: + - "3.3.5" steps: - - uses: actions/checkout@v2 - - name: Set up Ruby - uses: ruby/setup-ruby@v1 - with: - ruby-version: 3.0.1 - - name: Run the default task - run: | - gem install bundler -v 2.2.15 - bundle install - bundle exec rake -env: - CLERK_PUBLISHABLE_KEY: 'pk_test_ZXhhbXBsZS5jb20k' + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + + - name: Unit Tests + run: bundle exec rake spec diff --git a/.gitignore b/.gitignore index 7a10690..75c21ea 100644 --- a/.gitignore +++ b/.gitignore @@ -8,8 +8,14 @@ /tmp/ .byebug_history -.ruby-version *.gem .idea +# rspec failure tracking +.rspec_status + +# Environment variables +.env +.env.* +!.env.example diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..34c5164 --- /dev/null +++ b/.rspec @@ -0,0 +1,3 @@ +--format documentation +--color +--require spec_helper diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..fa7adc7 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +3.3.5 diff --git a/CHANGELOG.md b/CHANGELOG.md index c7eee0d..7c65fb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,16 @@ +## 4.0.0.beta4 - 2025-01-06 + +[BREAKING] This release introduces our new `clerk-http-client` gem, which is a generated directly from the Clerk API OpenAPI specs. This will help to ensure that the SDK is always in sync with the Clerk API. + +- feat: Add support for the `clerk-http-client` gem [https://github.com/clerk/clerk-sdk-ruby/pull/77] +- feat: Add support for Revalidation [https://github.com/clerk/clerk-sdk-ruby/pull/77] +- feat: Add support for Rails API mode [https://github.com/clerk/clerk-sdk-ruby/pull/77] +- feat: Add support for Sinatra [https://github.com/clerk/clerk-sdk-ruby/pull/77] +- feat: Middleware cache defaults to `Rails.cache` -> `ActiveSupport::Cache::MemoryStore` (if available) -> no caching [https://github.com/clerk/clerk-sdk-ruby/pull/77] +- chore: Refactor Clerk helper methods for Rails and Rack [https://github.com/clerk/clerk-sdk-ruby/pull/77] +- fix: Update configuration naming of `api_key` to `secret_key` [https://github.com/clerk/clerk-sdk-ruby/pull/77] +- docs: Add example applications for Rails, Sinatra, and Rack under `apps/` [https://github.com/clerk/clerk-sdk-ruby/pull/77] + ## 4.0.0.beta3 - 2024-04-02 - fix: Make publishable_key and secret_key required without making the envs required [https://github.com/clerk/clerk-sdk-ruby/pull/53] diff --git a/Gemfile b/Gemfile index 7590240..efcc19d 100644 --- a/Gemfile +++ b/Gemfile @@ -2,9 +2,32 @@ source "https://rubygems.org" -# Specify your gem's dependencies in clerk-sdk-ruby.gemspec +# Specify your gem's dependencies in clerk.gemspec gemspec -gem "rake", "~> 13.0" +group :development do + gem "activesupport", "~> 8.0", require: false + gem "dotenv", "~> 3.1", require: false + gem "puma", "~> 6.4", ">= 6.4.3", require: false + gem "rack", "~> 3.1", ">= 3.1.8", require: false + gem "rbs", "~> 3.6" + gem "rake", "~> 13.0" + gem "rackup", "~> 2.2", require: false + gem "rb-fsevent", "~> 0.11", ">= 0.11.2", platform: [:ruby], require: false + gem "rerun", "~> 0.14", require: false + gem "sinatra", "~> 4.1", require: false + gem "standard", "~> 1.42" + gem "wdm", "~> 0.2", platform: [:mswin, :windows] +end -gem "minitest", "~> 5.0" +group :development, :test do + gem "rspec", "~> 3.0" + gem "rspec-rails", "~> 7.1" + gem "guard-rspec", "~> 4.7", require: false + gem "guard-rake", "~> 1.0", require: false +end + +group :test do + gem "simplecov", require: false + gem "climate_control", require: false +end diff --git a/Gemfile.lock b/Gemfile.lock index fdf2b94..da97d8e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,8 @@ PATH remote: . specs: - clerk-sdk-ruby (4.0.0.beta3) + clerk-sdk-ruby (4.0.0.beta4) + clerk-http-client (~> 0.0.1) concurrent-ruby (~> 1.1) faraday (>= 1.4.1, < 3.0) jwt (~> 2.5) @@ -9,31 +10,286 @@ PATH GEM remote: https://rubygems.org/ specs: - base64 (0.1.1) + actionpack (8.0.1) + actionview (= 8.0.1) + activesupport (= 8.0.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) + actionview (8.0.1) + activesupport (= 8.0.1) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activesupport (8.0.1) + base64 + benchmark (>= 0.3) + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + ast (2.4.2) + base64 (0.2.0) + benchmark (0.4.0) + bigdecimal (3.1.9) + builder (3.3.0) byebug (11.1.3) - concurrent-ruby (1.2.2) - faraday (2.7.11) + clerk-http-client (0.0.1) + faraday (>= 1.0.1, < 3.0) + faraday-multipart + marcel + climate_control (1.2.0) + coderay (1.1.3) + concurrent-ruby (1.3.4) + connection_pool (2.4.1) + crass (1.0.6) + date (3.4.1) + diff-lcs (1.5.1) + docile (1.4.1) + dotenv (3.1.7) + drb (2.2.1) + erubi (1.13.1) + faraday (2.12.2) + faraday-net_http (>= 2.0, < 3.5) + json + logger + faraday-multipart (1.1.0) + multipart-post (~> 2.0) + faraday-net_http (3.4.0) + net-http (>= 0.5.0) + ffi (1.17.1-arm64-darwin) + ffi (1.17.1-x86_64-linux-gnu) + formatador (1.1.0) + guard (2.19.1) + formatador (>= 0.2.4) + listen (>= 2.7, < 4.0) + logger (~> 1.6) + lumberjack (>= 1.0.12, < 2.0) + nenv (~> 0.1) + notiffany (~> 0.0) + ostruct (~> 0.6) + pry (>= 0.13.0) + shellany (~> 0.0) + thor (>= 0.18.1) + guard-compat (1.2.1) + guard-rake (1.0.0) + guard + rake + guard-rspec (4.7.3) + guard (~> 2.1) + guard-compat (~> 1.1) + rspec (>= 2.99.0, < 4.0) + i18n (1.14.6) + concurrent-ruby (~> 1.0) + io-console (0.8.0) + irb (1.14.3) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + json (2.9.1) + jwt (2.10.1) base64 - faraday-net_http (>= 2.0, < 3.1) - ruby2_keywords (>= 0.0.4) - faraday-net_http (3.0.2) - jwt (2.7.1) - minitest (5.20.0) - rake (13.1.0) + language_server-protocol (3.17.0.3) + lint_roller (1.1.0) + listen (3.9.0) + rb-fsevent (~> 0.10, >= 0.10.3) + rb-inotify (~> 0.9, >= 0.9.10) + logger (1.6.4) + loofah (2.24.0) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + lumberjack (1.2.10) + marcel (1.0.4) + method_source (1.1.0) + minitest (5.25.4) + multipart-post (2.4.1) + mustermann (3.0.3) + ruby2_keywords (~> 0.0.1) + nenv (0.3.0) + net-http (0.6.0) + uri + nio4r (2.7.4) + nokogiri (1.18.1-arm64-darwin) + racc (~> 1.4) + nokogiri (1.18.1-x86_64-darwin) + racc (~> 1.4) + nokogiri (1.18.1-x86_64-linux-gnu) + racc (~> 1.4) + notiffany (0.1.3) + nenv (~> 0.1) + shellany (~> 0.0) + ostruct (0.6.1) + parallel (1.26.3) + parser (3.3.6.0) + ast (~> 2.4.1) + racc + pry (0.15.2) + coderay (~> 1.1) + method_source (~> 1.0) + psych (5.2.2) + date + stringio + puma (6.5.0) + nio4r (~> 2.0) + racc (1.8.1) + rack (3.1.8) + rack-protection (4.1.1) + base64 (>= 0.1.0) + logger (>= 1.6.0) + rack (>= 3.0.0, < 4) + rack-session (2.1.0) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.2.0) + rack (>= 1.3) + rackup (2.2.1) + rack (>= 3) + rails-dom-testing (2.2.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.2) + loofah (~> 2.21) + 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.0.1) + actionpack (= 8.0.1) + activesupport (= 8.0.1) + irb (~> 1.13) + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.2.1) + rb-fsevent (0.11.2) + rb-inotify (0.11.1) + ffi (~> 1.0) + rbs (3.8.1) + logger + rdoc (6.10.0) + psych (>= 4.0.0) + regexp_parser (2.10.0) + reline (0.6.0) + io-console (~> 0.5) + rerun (0.14.0) + listen (~> 3.0) + rspec (3.13.0) + rspec-core (~> 3.13.0) + rspec-expectations (~> 3.13.0) + rspec-mocks (~> 3.13.0) + rspec-core (3.13.2) + rspec-support (~> 3.13.0) + rspec-expectations (3.13.3) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-mocks (3.13.2) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-rails (7.1.0) + actionpack (>= 7.0) + activesupport (>= 7.0) + railties (>= 7.0) + rspec-core (~> 3.13) + rspec-expectations (~> 3.13) + rspec-mocks (~> 3.13) + rspec-support (~> 3.13) + rspec-support (3.13.2) + rubocop (1.69.2) + json (~> 2.3) + language_server-protocol (>= 3.17.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.36.2, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.37.0) + parser (>= 3.3.1.0) + rubocop-performance (1.23.1) + rubocop (>= 1.48.1, < 2.0) + rubocop-ast (>= 1.31.1, < 2.0) + ruby-progressbar (1.13.0) ruby2_keywords (0.0.5) - timecop (0.9.8) + securerandom (0.4.1) + shellany (0.0.1) + simplecov (0.22.0) + docile (~> 1.1) + simplecov-html (~> 0.11) + simplecov_json_formatter (~> 0.1) + simplecov-html (0.13.1) + simplecov_json_formatter (0.1.4) + sinatra (4.1.1) + logger (>= 1.6.0) + mustermann (~> 3.0) + rack (>= 3.0.0, < 4) + rack-protection (= 4.1.1) + rack-session (>= 2.0.0, < 3) + tilt (~> 2.0) + standard (1.43.0) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.0) + rubocop (~> 1.69.1) + standard-custom (~> 1.0.0) + standard-performance (~> 1.6) + standard-custom (1.0.2) + lint_roller (~> 1.0) + rubocop (~> 1.50) + standard-performance (1.6.0) + lint_roller (~> 1.1) + rubocop-performance (~> 1.23.0) + stringio (3.1.2) + thor (1.3.2) + tilt (2.5.0) + timecop (0.9.10) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (3.1.3) + unicode-emoji (~> 4.0, >= 4.0.4) + unicode-emoji (4.0.4) + uri (1.0.2) + useragent (0.16.11) + zeitwerk (2.7.1) PLATFORMS arm64-darwin-22 + arm64-darwin-23 + arm64-darwin-24 universal-darwin-21 x86_64-linux DEPENDENCIES + activesupport (~> 8.0) byebug (~> 11.1) clerk-sdk-ruby! - minitest (~> 5.0) + climate_control + dotenv (~> 3.1) + guard-rake (~> 1.0) + guard-rspec (~> 4.7) + puma (~> 6.4, >= 6.4.3) + rack (~> 3.1, >= 3.1.8) + rackup (~> 2.2) rake (~> 13.0) + rb-fsevent (~> 0.11, >= 0.11.2) + rbs (~> 3.6) + rerun (~> 0.14) + rspec (~> 3.0) + rspec-rails (~> 7.1) + simplecov + sinatra (~> 4.1) + standard (~> 1.42) timecop (~> 0.9.4) + wdm (~> 0.2) BUNDLED WITH - 2.3.25 + 2.6.2 diff --git a/Guardfile b/Guardfile new file mode 100644 index 0000000..7703c57 --- /dev/null +++ b/Guardfile @@ -0,0 +1,14 @@ +guard :rspec, cmd: "bundle exec rspec", group: :spec do + require "guard/rspec/dsl" + dsl = Guard::RSpec::Dsl.new(self) + + # RSpec files + rspec = dsl.rspec + watch(rspec.spec_helper) { rspec.spec_dir } + watch(rspec.spec_support) { rspec.spec_dir } + watch(rspec.spec_files) + + # Ruby files + ruby = dsl.ruby + dsl.watch_spec_files_for(ruby.lib_files) +end diff --git a/README.md b/README.md index cd575eb..44cdc2b 100644 --- a/README.md +++ b/README.md @@ -87,8 +87,7 @@ supported configuration settings their environment variable equivalents: ```ruby Clerk.configure do |c| - c.api_key = "your_api_key" # if omitted: ENV["CLERK_SECRET_KEY"] - API calls will fail if unset - c.base_url = "https://..." # if omitted: ENV["CLERK_API_BASE"] - defaults to "https://api.clerk.com/v1/" + c.secret_key = "sk_(test|live)_...." # if omitted: ENV["CLERK_SECRET_KEY"] - API calls will fail if unset c.publishable_key = "pk_(test|live)_...." # if omitted: ENV["CLERK_PUBLISHABLE_KEY"] - Handshake mechanism (check section below) will fail if unset c.logger = Logger.new(STDOUT) # if omitted, no logging c.middleware_cache_store = ActiveSupport::Cache::FileStore.new("/tmp/clerk_middleware_cache") # if omitted: no caching @@ -101,9 +100,8 @@ arguments to the constructor: ```ruby clerk = Clerk::SDK.new( - api_key: "X", - base_url: "Y", logger: Logger.new() + secret_key: "X", ) ``` @@ -126,6 +124,22 @@ of `Clerk::Proxy`. To get the session or the user of the session, you call `session` or `user` respectively. In case there is no session, you can retrieve the API error with the `error` getter method. +```ruby +use Clerk::Rack::Middleware +``` + +### Reverification middleware + +The SDK comes with a revalidation middleware which will automatically revalidate the session when the user navigates to a protected route. + +```ruby +use Clerk::Rack::Reverification, + preset: Clerk::StepUp::Preset::LAX, + routes: ["/*"] +``` + + + ## Rails integration The SDK will automatically add the [Rack middleware](#rack-middleware) to the @@ -133,18 +147,55 @@ middleware stack. For easier access to the Clerk session and user, include the `Clerk::Authenticatable` concern in your controller: ```ruby -require "clerk/authenticatable" - class ApplicationController < ActionController::Base include Clerk::Authenticatable end + +class AdminController < ApplicationController + before_action :require_reverification!, only: [:protected] + + def index + @user = clerk.user + end + + def protected + render json: {message: clerk.user? ? "Valid session" : "Not logged in"} + end +end ``` -This gives your controller and views access to the following methods: +This gives your controller and views access to the following methods and more: + +- `clerk.session` +- `clerk.user` +- `clerk.user?` + +## Sinatra integration + +The SDK enables the use of Extensions to add Clerk support to your Sinatra application. + +`Sinatra::Clerk` will automatically add the [Rack middleware](#rack-middleware)to the +middleware stack and enable easy access to the Clerk session and user helper methods. -- `clerk_session` -- `clerk_user` -- `clerk_user_signed_in?` +```ruby +class App < Sinatra::Base + register Sinatra::Clerk + + get "/" do + erb :index, format: :html5 + end + + get "/admin" do + @user = clerk.user + erb :index, format: :html5 + end + + get "/protected" do + require_reverification! + {message: clerk.user? ? "Valid session" : "Not logged in"}.to_json + end +end +``` ## Internals @@ -171,11 +222,20 @@ With the handshake, we can resolve the authentication state on the backend and e ## Development After checking out the repo, run `bin/setup` to install dependencies. Then, run -`bundle exec rake` to run the tests. You can also run `bin/console` for an +`bundle exec rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. +To run the example applications, run: + +```bash +rake app:rack +rake app:rails +rake app:rails:api +rake app:sinatra +``` + ## Release To release a new version: diff --git a/Rakefile b/Rakefile index 8ca97e1..389eb5a 100644 --- a/Rakefile +++ b/Rakefile @@ -1,12 +1,56 @@ # frozen_string_literal: true require "bundler/gem_tasks" -require "rake/testtask" +require "standard/rake" -Rake::TestTask.new(:test) do |t| - t.libs << "test" - t.libs << "lib" - t.test_files = FileList["test/**/*_test.rb"] +################################ +# COVERAGE +################################ + +desc "Open coverage report" +task(:cov) { system "open coverage/index.html" } + +################################ +# TESTING +################################ + +desc "Run all tests" +task spec: "spec:all" + +namespace :spec do + task(:all) { system "bundle exec rspec" } + + desc "Run tests on file changes" + task(:watch) { system "bundle exec guard -g spec" } + + desc "Run failed tests only" + task(:failed) { system "bundle exec rspec --only-failures" } +end + +################################ +# PLAYGROUND APPLICATIONS +################################ + +namespace :app do + desc "Run Rails (full stack) application" + task rails: "rails:full" + + namespace :rails do + task :full do + cd ("apps/rails-full") { system "bin/rails server" } + end + + desc "Run Rails (API only) application" + task :api do + cd ("apps/rails-api") { system "bin/rails server" } + end + end + + desc "Run Rack application" + task(:rack) { system "rerun --dir lib,apps/rack --pattern '**/*.{rb,ru}' -- bundle exec puma apps/rack/config.ru -p 3000" } + + desc "Run Sinatra application" + task(:sinatra) { system "rerun --dir lib,apps/sinatra --pattern '**/*.{erb,rb,ru}' -- bundle exec puma apps/sinatra/config.ru -p 3000 -v" } end -task default: :test + diff --git a/apps/rack/app.rb b/apps/rack/app.rb new file mode 100644 index 0000000..da515a3 --- /dev/null +++ b/apps/rack/app.rb @@ -0,0 +1,67 @@ +require "erb" +require "clerk" + +class App + def call(env) + # # Example: Without using `Clerk::Rack::Reverification` Middleware + # preset = Clerk::StepUp::Preset::LAX + # if env["clerk"].user_needs_reverification?(preset) + # return env["clerk"].user_reverification_rack_response(preset) + # end + + respond_with(200) do + user = env["clerk"].user + user ? "Authenticated User: #{user.first_name} (#{user.id})" : "Not Authenticated" + end + end + + private + + def respond_with(status, plain_body = nil, &html_body) + return [status, {"Content-Type" => "text/plain; charset=utf-8"}, [plain_body]] unless block_given? + + compiled = <<-HTML + + + Rack + + + + + +

Rack

+

#{yield}

+
+ + + HTML + + [status, {"Content-Type" => "text/html; charset=utf-8"}, [compiled]] + end +end diff --git a/apps/rack/config.ru b/apps/rack/config.ru new file mode 100644 index 0000000..3d58449 --- /dev/null +++ b/apps/rack/config.ru @@ -0,0 +1,17 @@ +require "active_support" +require "rack" +require "clerk/rack" +require "dotenv" + +require_relative "app" +require_relative "middleware/disable_paths" + +Dotenv.load(".env") + +use DisablePaths, paths: ["/favicon.ico"] +use Clerk::Rack::Middleware +use Clerk::Rack::Reverification, + preset: Clerk::StepUp::Preset::LAX, + routes: ["/*"] + +run App.new diff --git a/apps/rack/middleware/disable_paths.rb b/apps/rack/middleware/disable_paths.rb new file mode 100644 index 0000000..e93c016 --- /dev/null +++ b/apps/rack/middleware/disable_paths.rb @@ -0,0 +1,13 @@ +class DisablePaths + def initialize(app, paths: []) + @app = app + @paths = {} + + paths.each { |p| @paths[p] = true } + end + + def call(env) + return [404, {}, []] if @paths[env["PATH_INFO"]] + @app.call(env) + end +end diff --git a/apps/rails-api/.dockerignore b/apps/rails-api/.dockerignore new file mode 100644 index 0000000..98a89a3 --- /dev/null +++ b/apps/rails-api/.dockerignore @@ -0,0 +1,41 @@ +# 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 CI service files. +/.github + +# Ignore development files +/.devcontainer + +# Ignore Docker-related files +/.dockerignore +/Dockerfile* diff --git a/apps/rails-api/.gitattributes b/apps/rails-api/.gitattributes new file mode 100644 index 0000000..8dc4323 --- /dev/null +++ b/apps/rails-api/.gitattributes @@ -0,0 +1,9 @@ +# See https://git-scm.com/docs/gitattributes for more about git attribute files. + +# Mark the database schema as having been generated. +db/schema.rb linguist-generated + +# Mark any vendored files as having been vendored. +vendor/* linguist-vendored +config/credentials/*.yml.enc diff=rails_credentials +config/credentials.yml.enc diff=rails_credentials diff --git a/apps/rails-api/.gitignore b/apps/rails-api/.gitignore new file mode 100644 index 0000000..063233c --- /dev/null +++ b/apps/rails-api/.gitignore @@ -0,0 +1,32 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# Temporary files generated by your text editor or operating system +# belong in git's global ignore instead: +# `$XDG_CONFIG_HOME/git/ignore` or `~/.config/git/ignore` + +# Ignore bundler config. +/.bundle + +# Ignore all environment files. +/.env* + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +# Ignore master key for decrypting credentials and more. +/config/master.key diff --git a/apps/rails-api/.kamal/hooks/docker-setup.sample b/apps/rails-api/.kamal/hooks/docker-setup.sample new file mode 100755 index 0000000..2fb07d7 --- /dev/null +++ b/apps/rails-api/.kamal/hooks/docker-setup.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Docker set up on $KAMAL_HOSTS..." diff --git a/apps/rails-api/.kamal/hooks/post-deploy.sample b/apps/rails-api/.kamal/hooks/post-deploy.sample new file mode 100755 index 0000000..75efafc --- /dev/null +++ b/apps/rails-api/.kamal/hooks/post-deploy.sample @@ -0,0 +1,14 @@ +#!/bin/sh + +# A sample post-deploy hook +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLE (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +echo "$KAMAL_PERFORMER deployed $KAMAL_VERSION to $KAMAL_DESTINATION in $KAMAL_RUNTIME seconds" diff --git a/apps/rails-api/.kamal/hooks/post-proxy-reboot.sample b/apps/rails-api/.kamal/hooks/post-proxy-reboot.sample new file mode 100755 index 0000000..1435a67 --- /dev/null +++ b/apps/rails-api/.kamal/hooks/post-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooted kamal-proxy on $KAMAL_HOSTS" diff --git a/apps/rails-api/.kamal/hooks/pre-build.sample b/apps/rails-api/.kamal/hooks/pre-build.sample new file mode 100755 index 0000000..f87d811 --- /dev/null +++ b/apps/rails-api/.kamal/hooks/pre-build.sample @@ -0,0 +1,51 @@ +#!/bin/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_ROLE (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/apps/rails-api/.kamal/hooks/pre-connect.sample b/apps/rails-api/.kamal/hooks/pre-connect.sample new file mode 100755 index 0000000..18e61d7 --- /dev/null +++ b/apps/rails-api/.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_ROLE (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/apps/rails-api/.kamal/hooks/pre-deploy.sample b/apps/rails-api/.kamal/hooks/pre-deploy.sample new file mode 100755 index 0000000..1b280c7 --- /dev/null +++ b/apps/rails-api/.kamal/hooks/pre-deploy.sample @@ -0,0 +1,109 @@ +#!/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_ROLE (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 = `git config --get remote.origin.url`.strip.delete_prefix("https://github.com/") + @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 +end + + +$stdout.sync = true + +puts "Checking build status..." +attempts = 0 +checks = GithubStatusChecks.new + +begin + 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/apps/rails-api/.kamal/hooks/pre-proxy-reboot.sample b/apps/rails-api/.kamal/hooks/pre-proxy-reboot.sample new file mode 100755 index 0000000..061f805 --- /dev/null +++ b/apps/rails-api/.kamal/hooks/pre-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooting kamal-proxy on $KAMAL_HOSTS..." diff --git a/apps/rails-api/.kamal/secrets b/apps/rails-api/.kamal/secrets new file mode 100644 index 0000000..9a771a3 --- /dev/null +++ b/apps/rails-api/.kamal/secrets @@ -0,0 +1,17 @@ +# Secrets defined here are available for reference under registry/password, env/secret, builder/secrets, +# and accessories/*/env/secret in config/deploy.yml. All secrets should be pulled from either +# password manager, ENV, or a file. DO NOT ENTER RAW CREDENTIALS HERE! This file needs to be safe for git. + +# Example of extracting secrets from 1password (or another compatible pw manager) +# SECRETS=$(kamal secrets fetch --adapter 1password --account your-account --from Vault/Item KAMAL_REGISTRY_PASSWORD RAILS_MASTER_KEY) +# KAMAL_REGISTRY_PASSWORD=$(kamal secrets extract KAMAL_REGISTRY_PASSWORD ${SECRETS}) +# RAILS_MASTER_KEY=$(kamal secrets extract RAILS_MASTER_KEY ${SECRETS}) + +# Use a GITHUB_TOKEN if private repositories are needed for the image +# GITHUB_TOKEN=$(gh config get -h github.com oauth_token) + +# Grab the registry password from ENV +KAMAL_REGISTRY_PASSWORD=$KAMAL_REGISTRY_PASSWORD + +# Improve security by using a password manager. Never check config/master.key into git! +RAILS_MASTER_KEY=$(cat config/master.key) diff --git a/apps/rails-api/.rubocop.yml b/apps/rails-api/.rubocop.yml new file mode 100644 index 0000000..f9d86d4 --- /dev/null +++ b/apps/rails-api/.rubocop.yml @@ -0,0 +1,8 @@ +# Omakase Ruby styling for Rails +inherit_gem: { rubocop-rails-omakase: rubocop.yml } + +# Overwrite or add rules to create your own house style +# +# # Use `[a, [b, c]]` not `[ a, [ b, c ] ]` +# Layout/SpaceInsideArrayLiteralBrackets: +# Enabled: false diff --git a/apps/rails-api/.ruby-version b/apps/rails-api/.ruby-version new file mode 100644 index 0000000..fa7adc7 --- /dev/null +++ b/apps/rails-api/.ruby-version @@ -0,0 +1 @@ +3.3.5 diff --git a/apps/rails-api/Dockerfile b/apps/rails-api/Dockerfile new file mode 100644 index 0000000..8a6b91f --- /dev/null +++ b/apps/rails-api/Dockerfile @@ -0,0 +1,69 @@ +# 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 rails_api . +# docker run -d -p 80:80 -e RAILS_MASTER_KEY= --name rails_api rails_api + +# 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=3.3.5 +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 sqlite3 && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Set production environment +ENV RAILS_ENV="production" \ + BUNDLE_DEPLOYMENT="1" \ + BUNDLE_PATH="/usr/local/bundle" \ + BUNDLE_WITHOUT="development" + +# 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 pkg-config && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Install application gems +COPY Gemfile Gemfile.lock ./ +RUN bundle install && \ + rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ + bundle exec bootsnap precompile --gemfile + +# Copy application code +COPY . . + +# Precompile bootsnap code for faster boot times +RUN bundle exec bootsnap precompile app/ lib/ + + + + +# Final stage for app image +FROM base + +# Copy built artifacts: gems, application +COPY --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}" +COPY --from=build /rails /rails + +# 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 && \ + chown -R rails:rails db log storage tmp +USER 1000:1000 + +# Entrypoint prepares the database. +ENTRYPOINT ["/rails/bin/docker-entrypoint"] + +# Start server via Thruster by default, this can be overwritten at runtime +EXPOSE 80 +CMD ["./bin/thrust", "./bin/rails", "server"] diff --git a/apps/rails-api/Gemfile b/apps/rails-api/Gemfile new file mode 100644 index 0000000..249095d --- /dev/null +++ b/apps/rails-api/Gemfile @@ -0,0 +1,54 @@ +source "https://rubygems.org" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 8.0.0" +# Use sqlite3 as the database for Active Record +gem "sqlite3", ">= 2.1" +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", ">= 5.0" +# 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.7" + +# 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" + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin Ajax possible +# gem "rack-cors" + +path "../.." do + gem "clerk-sdk-ruby", require: "clerk" +end + + +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" + + # 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 + +gem "dotenv-rails", "~> 3.1" diff --git a/apps/rails-api/Gemfile.lock b/apps/rails-api/Gemfile.lock new file mode 100644 index 0000000..e849af6 --- /dev/null +++ b/apps/rails-api/Gemfile.lock @@ -0,0 +1,374 @@ +PATH + remote: ../.. + specs: + clerk-sdk-ruby (4.0.0.beta4) + clerk-http-client (~> 0.0.1) + concurrent-ruby (~> 1.1) + faraday (>= 1.4.1, < 3.0) + jwt (~> 2.5) + +GEM + remote: https://rubygems.org/ + specs: + actioncable (8.0.1) + actionpack (= 8.0.1) + activesupport (= 8.0.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.0.1) + actionpack (= 8.0.1) + activejob (= 8.0.1) + activerecord (= 8.0.1) + activestorage (= 8.0.1) + activesupport (= 8.0.1) + mail (>= 2.8.0) + actionmailer (8.0.1) + actionpack (= 8.0.1) + actionview (= 8.0.1) + activejob (= 8.0.1) + activesupport (= 8.0.1) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.0.1) + actionview (= 8.0.1) + activesupport (= 8.0.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.0.1) + actionpack (= 8.0.1) + activerecord (= 8.0.1) + activestorage (= 8.0.1) + activesupport (= 8.0.1) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.0.1) + activesupport (= 8.0.1) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (8.0.1) + activesupport (= 8.0.1) + globalid (>= 0.3.6) + activemodel (8.0.1) + activesupport (= 8.0.1) + activerecord (8.0.1) + activemodel (= 8.0.1) + activesupport (= 8.0.1) + timeout (>= 0.4.0) + activestorage (8.0.1) + actionpack (= 8.0.1) + activejob (= 8.0.1) + activerecord (= 8.0.1) + activesupport (= 8.0.1) + marcel (~> 1.0) + activesupport (8.0.1) + base64 + benchmark (>= 0.3) + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + ast (2.4.2) + base64 (0.2.0) + bcrypt_pbkdf (1.1.1) + bcrypt_pbkdf (1.1.1-arm64-darwin) + bcrypt_pbkdf (1.1.1-x86_64-darwin) + benchmark (0.4.0) + bigdecimal (3.1.9) + bootsnap (1.18.4) + msgpack (~> 1.2) + brakeman (7.0.0) + racc + builder (3.3.0) + clerk-http-client (0.0.1) + faraday (>= 1.0.1, < 3.0) + faraday-multipart + marcel + concurrent-ruby (1.3.4) + connection_pool (2.4.1) + crass (1.0.6) + date (3.4.1) + debug (1.10.0) + irb (~> 1.10) + reline (>= 0.3.8) + dotenv (3.1.7) + dotenv-rails (3.1.7) + dotenv (= 3.1.7) + railties (>= 6.1) + drb (2.2.1) + ed25519 (1.3.0) + erubi (1.13.1) + et-orbi (1.2.11) + tzinfo + faraday (2.12.2) + faraday-net_http (>= 2.0, < 3.5) + json + logger + faraday-multipart (1.1.0) + multipart-post (~> 2.0) + faraday-net_http (3.4.0) + net-http (>= 0.5.0) + fugit (1.11.1) + et-orbi (~> 1, >= 1.2.11) + raabro (~> 1.4) + globalid (1.2.1) + activesupport (>= 6.1) + i18n (1.14.6) + concurrent-ruby (~> 1.0) + io-console (0.8.0) + irb (1.14.3) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + json (2.9.1) + jwt (2.10.1) + base64 + kamal (2.4.0) + activesupport (>= 7.0) + base64 (~> 0.2) + bcrypt_pbkdf (~> 1.0) + concurrent-ruby (~> 1.2) + dotenv (~> 3.1) + ed25519 (~> 1.2) + 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.3) + logger (1.6.4) + loofah (2.24.0) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.8.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.4) + mini_mime (1.1.5) + mini_portile2 (2.8.8) + minitest (5.25.4) + msgpack (1.7.5) + multipart-post (2.4.1) + net-http (0.6.0) + uri + net-imap (0.5.5) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-scp (4.0.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.0) + net-protocol + net-ssh (7.3.0) + nio4r (2.7.4) + nokogiri (1.18.1) + mini_portile2 (~> 2.8.2) + racc (~> 1.4) + nokogiri (1.18.1-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.1-aarch64-linux-musl) + racc (~> 1.4) + nokogiri (1.18.1-arm-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.1-arm-linux-musl) + racc (~> 1.4) + nokogiri (1.18.1-arm64-darwin) + racc (~> 1.4) + nokogiri (1.18.1-x86_64-darwin) + racc (~> 1.4) + nokogiri (1.18.1-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.1-x86_64-linux-musl) + racc (~> 1.4) + ostruct (0.6.1) + parallel (1.26.3) + parser (3.3.6.0) + ast (~> 2.4.1) + racc + psych (5.2.2) + date + stringio + puma (6.5.0) + nio4r (~> 2.0) + raabro (1.4.0) + racc (1.8.1) + rack (3.1.8) + rack-session (2.1.0) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.2.0) + rack (>= 1.3) + rackup (2.2.1) + rack (>= 3) + rails (8.0.1) + actioncable (= 8.0.1) + actionmailbox (= 8.0.1) + actionmailer (= 8.0.1) + actionpack (= 8.0.1) + actiontext (= 8.0.1) + actionview (= 8.0.1) + activejob (= 8.0.1) + activemodel (= 8.0.1) + activerecord (= 8.0.1) + activestorage (= 8.0.1) + activesupport (= 8.0.1) + bundler (>= 1.15.0) + railties (= 8.0.1) + rails-dom-testing (2.2.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.2) + loofah (~> 2.21) + 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.0.1) + actionpack (= 8.0.1) + activesupport (= 8.0.1) + irb (~> 1.13) + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.2.1) + rdoc (6.10.0) + psych (>= 4.0.0) + regexp_parser (2.10.0) + reline (0.6.0) + io-console (~> 0.5) + rubocop (1.69.2) + json (~> 2.3) + language_server-protocol (>= 3.17.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.36.2, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.37.0) + parser (>= 3.3.1.0) + rubocop-minitest (0.36.0) + rubocop (>= 1.61, < 2.0) + rubocop-ast (>= 1.31.1, < 2.0) + rubocop-performance (1.23.1) + rubocop (>= 1.48.1, < 2.0) + rubocop-ast (>= 1.31.1, < 2.0) + rubocop-rails (2.28.0) + activesupport (>= 4.2.0) + rack (>= 1.1) + rubocop (>= 1.52.0, < 2.0) + rubocop-ast (>= 1.31.1, < 2.0) + rubocop-rails-omakase (1.0.0) + rubocop + rubocop-minitest + rubocop-performance + rubocop-rails + ruby-progressbar (1.13.0) + securerandom (0.4.1) + solid_cable (3.0.5) + actioncable (>= 7.2) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_cache (1.0.6) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_queue (1.1.2) + activejob (>= 7.1) + activerecord (>= 7.1) + concurrent-ruby (>= 1.3.1) + fugit (~> 1.11.0) + railties (>= 7.1) + thor (~> 1.3.1) + sqlite3 (2.5.0-aarch64-linux-gnu) + sqlite3 (2.5.0-aarch64-linux-musl) + sqlite3 (2.5.0-arm-linux-gnu) + sqlite3 (2.5.0-arm-linux-musl) + sqlite3 (2.5.0-arm64-darwin) + sqlite3 (2.5.0-x86-linux-gnu) + sqlite3 (2.5.0-x86-linux-musl) + sqlite3 (2.5.0-x86_64-darwin) + sqlite3 (2.5.0-x86_64-linux-gnu) + sqlite3 (2.5.0-x86_64-linux-musl) + sshkit (1.23.2) + base64 + net-scp (>= 1.1.2) + net-sftp (>= 2.1.2) + net-ssh (>= 2.8.0) + ostruct + stringio (3.1.2) + thor (1.3.2) + thruster (0.1.10) + thruster (0.1.10-aarch64-linux) + thruster (0.1.10-arm64-darwin) + thruster (0.1.10-x86_64-darwin) + thruster (0.1.10-x86_64-linux) + timeout (0.4.3) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (3.1.3) + unicode-emoji (~> 4.0, >= 4.0.4) + unicode-emoji (4.0.4) + uri (1.0.2) + useragent (0.16.11) + websocket-driver (0.7.7) + base64 + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + zeitwerk (2.7.1) + +PLATFORMS + aarch64-linux + aarch64-linux-gnu + aarch64-linux-musl + arm-linux + arm-linux-gnu + arm-linux-musl + arm64-darwin + x86-linux + x86-linux-gnu + x86-linux-musl + x86_64-darwin + x86_64-linux + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + bootsnap + brakeman + clerk-sdk-ruby! + debug + dotenv-rails (~> 3.1) + kamal + puma (>= 5.0) + rails (~> 8.0.0) + rubocop-rails-omakase + solid_cable + solid_cache + solid_queue + sqlite3 (>= 2.1) + thruster + tzinfo-data + +BUNDLED WITH + 2.6.2 diff --git a/apps/rails-api/README.md b/apps/rails-api/README.md new file mode 100644 index 0000000..7db80e4 --- /dev/null +++ b/apps/rails-api/README.md @@ -0,0 +1,24 @@ +# README + +This README would normally document whatever steps are necessary to get the +application up and running. + +Things you may want to cover: + +* Ruby version + +* System dependencies + +* Configuration + +* Database creation + +* Database initialization + +* How to run the test suite + +* Services (job queues, cache servers, search engines, etc.) + +* Deployment instructions + +* ... diff --git a/apps/rails-api/Rakefile b/apps/rails-api/Rakefile new file mode 100644 index 0000000..9a5ea73 --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/app/controllers/application_controller.rb b/apps/rails-api/app/controllers/application_controller.rb new file mode 100644 index 0000000..61a7047 --- /dev/null +++ b/apps/rails-api/app/controllers/application_controller.rb @@ -0,0 +1,3 @@ +class ApplicationController < ActionController::API + include Clerk::Authenticatable +end diff --git a/apps/rails-api/app/controllers/home_controller.rb b/apps/rails-api/app/controllers/home_controller.rb new file mode 100644 index 0000000..7ca6031 --- /dev/null +++ b/apps/rails-api/app/controllers/home_controller.rb @@ -0,0 +1,5 @@ +class HomeController < ApplicationController + def index + render json: clerk.user || {message: "Not authenticated"} + end +end diff --git a/apps/rails-api/app/jobs/application_job.rb b/apps/rails-api/app/jobs/application_job.rb new file mode 100644 index 0000000..d394c3d --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/app/mailers/application_mailer.rb b/apps/rails-api/app/mailers/application_mailer.rb new file mode 100644 index 0000000..3c34c81 --- /dev/null +++ b/apps/rails-api/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" +end diff --git a/apps/rails-api/app/models/application_record.rb b/apps/rails-api/app/models/application_record.rb new file mode 100644 index 0000000..b63caeb --- /dev/null +++ b/apps/rails-api/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/apps/rails-api/app/views/layouts/mailer.html.erb b/apps/rails-api/app/views/layouts/mailer.html.erb new file mode 100644 index 0000000..3aac900 --- /dev/null +++ b/apps/rails-api/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/apps/rails-api/app/views/layouts/mailer.text.erb b/apps/rails-api/app/views/layouts/mailer.text.erb new file mode 100644 index 0000000..37f0bdd --- /dev/null +++ b/apps/rails-api/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/apps/rails-api/bin/brakeman b/apps/rails-api/bin/brakeman new file mode 100755 index 0000000..ace1c9b --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/bin/bundle b/apps/rails-api/bin/bundle new file mode 100755 index 0000000..50da5fd --- /dev/null +++ b/apps/rails-api/bin/bundle @@ -0,0 +1,109 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a.match?(Gem::Version::ANCHORED_VERSION_PATTERN) + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../Gemfile", __dir__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, ".locked") + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || + cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + bundler_gem_version.approximate_recommendation + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/apps/rails-api/bin/dev b/apps/rails-api/bin/dev new file mode 100755 index 0000000..5f91c20 --- /dev/null +++ b/apps/rails-api/bin/dev @@ -0,0 +1,2 @@ +#!/usr/bin/env ruby +exec "./bin/rails", "server", *ARGV diff --git a/apps/rails-api/bin/docker-entrypoint b/apps/rails-api/bin/docker-entrypoint new file mode 100755 index 0000000..57567d6 --- /dev/null +++ b/apps/rails-api/bin/docker-entrypoint @@ -0,0 +1,14 @@ +#!/bin/bash -e + +# Enable jemalloc for reduced memory usage and latency. +if [ -z "${LD_PRELOAD+x}" ]; then + LD_PRELOAD=$(find /usr/lib -name libjemalloc.so.2 -print -quit) + export LD_PRELOAD +fi + +# 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/apps/rails-api/bin/jobs b/apps/rails-api/bin/jobs new file mode 100755 index 0000000..dcf59f3 --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/bin/kamal b/apps/rails-api/bin/kamal new file mode 100755 index 0000000..cbe59b9 --- /dev/null +++ b/apps/rails-api/bin/kamal @@ -0,0 +1,27 @@ +#!/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__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("kamal", "kamal") diff --git a/apps/rails-api/bin/rails b/apps/rails-api/bin/rails new file mode 100755 index 0000000..efc0377 --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/bin/rake b/apps/rails-api/bin/rake new file mode 100755 index 0000000..4fbf10b --- /dev/null +++ b/apps/rails-api/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/apps/rails-api/bin/rubocop b/apps/rails-api/bin/rubocop new file mode 100755 index 0000000..40330c0 --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/bin/setup b/apps/rails-api/bin/setup new file mode 100755 index 0000000..be3db3c --- /dev/null +++ b/apps/rails-api/bin/setup @@ -0,0 +1,34 @@ +#!/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" + + 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/apps/rails-api/bin/thrust b/apps/rails-api/bin/thrust new file mode 100755 index 0000000..36bde2d --- /dev/null +++ b/apps/rails-api/bin/thrust @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("thruster", "thrust") diff --git a/apps/rails-api/config.ru b/apps/rails-api/config.ru new file mode 100644 index 0000000..4a3c09a --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/config/application.rb b/apps/rails-api/config/application.rb new file mode 100644 index 0000000..b81739e --- /dev/null +++ b/apps/rails-api/config/application.rb @@ -0,0 +1,36 @@ +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) + +# Load environment variables manually from shared .env file +require "dotenv/rails" +Dotenv::Rails.files.unshift(File.expand_path(File.join("..", "..", ".env"))) + +module RailsApi + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 8.0 + + # 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]) + + # 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") + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/apps/rails-api/config/boot.rb b/apps/rails-api/config/boot.rb new file mode 100644 index 0000000..988a5dd --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/config/cable.yml b/apps/rails-api/config/cable.yml new file mode 100644 index 0000000..b9adc5a --- /dev/null +++ b/apps/rails-api/config/cable.yml @@ -0,0 +1,17 @@ +# 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: async + +test: + adapter: test + +production: + adapter: solid_cable + connects_to: + database: + writing: cable + polling_interval: 0.1.seconds + message_retention: 1.day diff --git a/apps/rails-api/config/cache.yml b/apps/rails-api/config/cache.yml new file mode 100644 index 0000000..19d4908 --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/config/credentials.yml.enc b/apps/rails-api/config/credentials.yml.enc new file mode 100644 index 0000000..4be75d4 --- /dev/null +++ b/apps/rails-api/config/credentials.yml.enc @@ -0,0 +1 @@ +DxqE9vmSeT9Klo+KJDhexo4vQZXc4+vELnjH3Ajkh+aTfnR9mkTMkXhq7FwifMXvmXMtMoc1pZH9GuIJ9hvI3maLlPjYeb7Ktext15q8+xTP0hJrw7vpVQvqxMMC/pRVv0mFbzGBdQaOVer9toCFYSs3L+rrA3mbPOhc9uub+jwWAz3N61gjPOifX4Lu3vqU484m5lK35xHNyACcy2IUxv+1ijk+42pgedWFCiYvuANi3Lc9sb1SHRA8Tn4jVoj842WAQ4abiVg2P4IFGhSaveGP6zmanyoRg11UBlc62SmmnQL9kpaTnDWZqsf16dJ6pNkT3mvgjFRjhy9lvT+gbXLtJNqS8GP13KpO4kmLVD7YNXtjFyyqHamPaUeSUOZ8C8STeSl6YiU+40Ia9yIQ47zsNLLIaRR4MWhQGIEf+H0ZdwmmMOzGUGs+p6R6/RJb6W+JvI4wl8lgLlQBXOhA8Mi8sCYG+1nJQPXRAGIZ3uvH0cQqUGhWodrr--OJs3x4FP6O6jMsR0--oF4iFB4bTnDh0TJVPfIl3w== \ No newline at end of file diff --git a/apps/rails-api/config/database.yml b/apps/rails-api/config/database.yml new file mode 100644 index 0000000..2640cb5 --- /dev/null +++ b/apps/rails-api/config/database.yml @@ -0,0 +1,41 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: storage/development.sqlite3 + +# 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: storage/test.sqlite3 + + +# Store production database in the storage/ directory, which by default +# is mounted as a persistent Docker volume in config/deploy.yml. +production: + primary: + <<: *default + database: storage/production.sqlite3 + cache: + <<: *default + database: storage/production_cache.sqlite3 + migrations_paths: db/cache_migrate + queue: + <<: *default + database: storage/production_queue.sqlite3 + migrations_paths: db/queue_migrate + cable: + <<: *default + database: storage/production_cable.sqlite3 + migrations_paths: db/cable_migrate diff --git a/apps/rails-api/config/deploy.yml b/apps/rails-api/config/deploy.yml new file mode 100644 index 0000000..159b9bd --- /dev/null +++ b/apps/rails-api/config/deploy.yml @@ -0,0 +1,116 @@ +# Name of your application. Used to uniquely configure containers. +service: rails_api + +# Name of the container image. +image: your-user/rails_api + +# Deploy to these servers. +servers: + web: + - 192.168.0.1 + # job: + # hosts: + # - 192.168.0.1 + # cmd: bin/jobs + +# Enable SSL auto certification via Let's Encrypt and allow for multiple apps on a single web server. +# Remove this section when using multiple web servers and ensure you terminate SSL at your load balancer. +# +# Note: If using Cloudflare, set encryption mode in SSL/TLS setting to "Full" to enable CF-to-app encryption. +proxy: + ssl: true + host: app.example.com + +# Credentials for your image host. +registry: + # Specify the registry server, if you're not using Docker Hub + # server: registry.digitalocean.com / ghcr.io / ... + username: your-user + + # Always use an access token rather than real password when possible. + password: + - KAMAL_REGISTRY_PASSWORD + +# Inject ENV variables into containers (secrets come from .kamal/secrets). +env: + secret: + - RAILS_MASTER_KEY + clear: + # Run the Solid Queue Supervisor inside the web server's Puma process to do jobs. + # When you start using multiple servers, you should split out job processing to a dedicated machine. + SOLID_QUEUE_IN_PUMA: true + + # Set number of processes dedicated to Solid Queue (default: 1) + # JOB_CONCURRENCY: 3 + + # Set number of cores available to the application on each server (default: 1). + # WEB_CONCURRENCY: 2 + + # Match this to any external database server to configure Active Record correctly + # Use rails_api-db for a db accessory server on same machine via local kamal docker network. + # DB_HOST: 192.168.0.2 + + # Log everything from Rails + # RAILS_LOG_LEVEL: debug + +# Aliases are triggered with "bin/kamal ". You can overwrite arguments on invocation: +# "bin/kamal logs -r job" will tail logs from the first server in the job section. +aliases: + console: app exec --interactive --reuse "bin/rails console" + shell: app exec --interactive --reuse "bash" + logs: app logs -f + dbc: app exec --interactive --reuse "bin/rails dbconsole" + + +# Use a persistent storage volume for sqlite database files and local Active Storage files. +# Recommended to change this to a mounted volume path that is backed up off server. +volumes: + - "rails_api_storage:/rails/storage" + + +# Bridge fingerprinted assets, like JS and CSS, between versions to avoid +# hitting 404 on in-flight requests. Combines all files from new and old +# version inside the asset_path. +asset_path: /rails/public/assets + +# Configure the image builder. +builder: + arch: amd64 + + # # Build image via remote server (useful for faster amd64 builds on arm64 computers) + # remote: ssh://docker@docker-builder-server + # + # # Pass arguments and secrets to the Docker build process + # args: + # RUBY_VERSION: 3.3.5 + # secrets: + # - GITHUB_TOKEN + # - RAILS_MASTER_KEY + +# Use a different ssh user than root +# ssh: +# user: app + +# Use accessory services (secrets come from .kamal/secrets). +# accessories: +# db: +# image: mysql:8.0 +# host: 192.168.0.2 +# # Change to 3306 to expose port to the world instead of just local network. +# port: "127.0.0.1:3306:3306" +# env: +# clear: +# MYSQL_ROOT_HOST: '%' +# secret: +# - MYSQL_ROOT_PASSWORD +# files: +# - config/mysql/production.cnf:/etc/mysql/my.cnf +# - db/production.sql:/docker-entrypoint-initdb.d/setup.sql +# directories: +# - data:/var/lib/mysql +# redis: +# image: redis:7.0 +# host: 192.168.0.2 +# port: 6379 +# directories: +# - data:/data diff --git a/apps/rails-api/config/environment.rb b/apps/rails-api/config/environment.rb new file mode 100644 index 0000000..cac5315 --- /dev/null +++ b/apps/rails-api/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/apps/rails-api/config/environments/development.rb b/apps/rails-api/config/environments/development.rb new file mode 100644 index 0000000..e7722fc --- /dev/null +++ b/apps/rails-api/config/environments/development.rb @@ -0,0 +1,70 @@ +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.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 + + # 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 + + # 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/apps/rails-api/config/environments/production.rb b/apps/rails-api/config/environments/production.rb new file mode 100644 index 0000000..967ae67 --- /dev/null +++ b/apps/rails-api/config/environments/production.rb @@ -0,0 +1,88 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # 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 + + # 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 + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + config.assume_ssl = true + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + config.force_ssl = true + + # Skip http-to-https redirect for the default health check endpoint. + # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } + + # 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: "example.com" } + + # Specify outgoing SMTP server. Remember to add smtp/* credentials via rails credentials:edit. + # config.action_mailer.smtp_settings = { + # user_name: Rails.application.credentials.dig(:smtp, :user_name), + # password: Rails.application.credentials.dig(:smtp, :password), + # address: "smtp.example.com", + # port: 587, + # authentication: :plain + # } + + # 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 ] + + # Enable DNS rebinding protection and other `Host` header attacks. + # config.hosts = [ + # "example.com", # Allow requests from example.com + # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` + # ] + # + # Skip DNS rebinding protection for the default health check endpoint. + # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } +end diff --git a/apps/rails-api/config/environments/test.rb b/apps/rails-api/config/environments/test.rb new file mode 100644 index 0000000..c2095b1 --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/config/initializers/cors.rb b/apps/rails-api/config/initializers/cors.rb new file mode 100644 index 0000000..0c5dd99 --- /dev/null +++ b/apps/rails-api/config/initializers/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin Ajax requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins "example.com" +# +# resource "*", +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/apps/rails-api/config/initializers/filter_parameter_logging.rb b/apps/rails-api/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..c0b717f --- /dev/null +++ b/apps/rails-api/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 +] diff --git a/apps/rails-api/config/initializers/inflections.rb b/apps/rails-api/config/initializers/inflections.rb new file mode 100644 index 0000000..3860f65 --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/config/locales/en.yml b/apps/rails-api/config/locales/en.yml new file mode 100644 index 0000000..6c349ae --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/config/puma.rb b/apps/rails-api/config/puma.rb new file mode 100644 index 0000000..a248513 --- /dev/null +++ b/apps/rails-api/config/puma.rb @@ -0,0 +1,41 @@ +# 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. +# +# 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/apps/rails-api/config/queue.yml b/apps/rails-api/config/queue.yml new file mode 100644 index 0000000..9eace59 --- /dev/null +++ b/apps/rails-api/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: 0.1 + +development: + <<: *default + +test: + <<: *default + +production: + <<: *default diff --git a/apps/rails-api/config/recurring.yml b/apps/rails-api/config/recurring.yml new file mode 100644 index 0000000..d045b19 --- /dev/null +++ b/apps/rails-api/config/recurring.yml @@ -0,0 +1,10 @@ +# production: +# periodic_cleanup: +# class: CleanSoftDeletedRecordsJob +# queue: background +# args: [ 1000, { batch_size: 500 } ] +# schedule: every hour +# periodic_command: +# command: "SoftDeletedRecord.due.delete_all" +# priority: 2 +# schedule: at 5am every day diff --git a/apps/rails-api/config/routes.rb b/apps/rails-api/config/routes.rb new file mode 100644 index 0000000..b08daea --- /dev/null +++ b/apps/rails-api/config/routes.rb @@ -0,0 +1,10 @@ +Rails.application.routes.draw do + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # 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 + + # Defines the root path route ("/") + root "home#index" +end diff --git a/apps/rails-api/config/storage.yml b/apps/rails-api/config/storage.yml new file mode 100644 index 0000000..4942ab6 --- /dev/null +++ b/apps/rails-api/config/storage.yml @@ -0,0 +1,34 @@ +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 %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/apps/rails-api/db/cable_schema.rb b/apps/rails-api/db/cable_schema.rb new file mode 100644 index 0000000..2366660 --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/db/cache_schema.rb b/apps/rails-api/db/cache_schema.rb new file mode 100644 index 0000000..6005a29 --- /dev/null +++ b/apps/rails-api/db/cache_schema.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +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/apps/rails-api/db/queue_schema.rb b/apps/rails-api/db/queue_schema.rb new file mode 100644 index 0000000..85194b6 --- /dev/null +++ b/apps/rails-api/db/queue_schema.rb @@ -0,0 +1,129 @@ +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.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_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 + + 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/apps/rails-api/db/seeds.rb b/apps/rails-api/db/seeds.rb new file mode 100644 index 0000000..4fbd6ed --- /dev/null +++ b/apps/rails-api/db/seeds.rb @@ -0,0 +1,9 @@ +# This file should ensure the existence of records required to run the application in every environment (production, +# development, test). The code here should be idempotent so that it can be executed at any point in every environment. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Example: +# +# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| +# MovieGenre.find_or_create_by!(name: genre_name) +# end diff --git a/apps/rails-api/public/robots.txt b/apps/rails-api/public/robots.txt new file mode 100644 index 0000000..c19f78a --- /dev/null +++ b/apps/rails-api/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/apps/rails-api/test/controllers/home_controller_test.rb b/apps/rails-api/test/controllers/home_controller_test.rb new file mode 100644 index 0000000..eac0e33 --- /dev/null +++ b/apps/rails-api/test/controllers/home_controller_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class HomeControllerTest < ActionDispatch::IntegrationTest + # test "the truth" do + # assert true + # end +end diff --git a/apps/rails-api/test/test_helper.rb b/apps/rails-api/test/test_helper.rb new file mode 100644 index 0000000..0c22470 --- /dev/null +++ b/apps/rails-api/test/test_helper.rb @@ -0,0 +1,15 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +module ActiveSupport + class TestCase + # 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/apps/rails-full/.dockerignore b/apps/rails-full/.dockerignore new file mode 100644 index 0000000..7540593 --- /dev/null +++ b/apps/rails-full/.dockerignore @@ -0,0 +1,47 @@ +# 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 CI service files. +/.github + +# Ignore development files +/.devcontainer + +# Ignore Docker-related files +/.dockerignore +/Dockerfile* diff --git a/apps/rails-full/.gitattributes b/apps/rails-full/.gitattributes new file mode 100644 index 0000000..8dc4323 --- /dev/null +++ b/apps/rails-full/.gitattributes @@ -0,0 +1,9 @@ +# See https://git-scm.com/docs/gitattributes for more about git attribute files. + +# Mark the database schema as having been generated. +db/schema.rb linguist-generated + +# Mark any vendored files as having been vendored. +vendor/* linguist-vendored +config/credentials/*.yml.enc diff=rails_credentials +config/credentials.yml.enc diff=rails_credentials diff --git a/apps/rails-full/.gitignore b/apps/rails-full/.gitignore new file mode 100644 index 0000000..f92525c --- /dev/null +++ b/apps/rails-full/.gitignore @@ -0,0 +1,34 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# Temporary files generated by your text editor or operating system +# belong in git's global ignore instead: +# `$XDG_CONFIG_HOME/git/ignore` or `~/.config/git/ignore` + +# Ignore bundler config. +/.bundle + +# Ignore all environment files. +/.env* + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +/public/assets + +# Ignore master key for decrypting credentials and more. +/config/master.key diff --git a/apps/rails-full/.kamal/hooks/docker-setup.sample b/apps/rails-full/.kamal/hooks/docker-setup.sample new file mode 100755 index 0000000..2fb07d7 --- /dev/null +++ b/apps/rails-full/.kamal/hooks/docker-setup.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Docker set up on $KAMAL_HOSTS..." diff --git a/apps/rails-full/.kamal/hooks/post-deploy.sample b/apps/rails-full/.kamal/hooks/post-deploy.sample new file mode 100755 index 0000000..75efafc --- /dev/null +++ b/apps/rails-full/.kamal/hooks/post-deploy.sample @@ -0,0 +1,14 @@ +#!/bin/sh + +# A sample post-deploy hook +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLE (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +echo "$KAMAL_PERFORMER deployed $KAMAL_VERSION to $KAMAL_DESTINATION in $KAMAL_RUNTIME seconds" diff --git a/apps/rails-full/.kamal/hooks/post-proxy-reboot.sample b/apps/rails-full/.kamal/hooks/post-proxy-reboot.sample new file mode 100755 index 0000000..1435a67 --- /dev/null +++ b/apps/rails-full/.kamal/hooks/post-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooted kamal-proxy on $KAMAL_HOSTS" diff --git a/apps/rails-full/.kamal/hooks/pre-build.sample b/apps/rails-full/.kamal/hooks/pre-build.sample new file mode 100755 index 0000000..f87d811 --- /dev/null +++ b/apps/rails-full/.kamal/hooks/pre-build.sample @@ -0,0 +1,51 @@ +#!/bin/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_ROLE (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/apps/rails-full/.kamal/hooks/pre-connect.sample b/apps/rails-full/.kamal/hooks/pre-connect.sample new file mode 100755 index 0000000..18e61d7 --- /dev/null +++ b/apps/rails-full/.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_ROLE (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/apps/rails-full/.kamal/hooks/pre-deploy.sample b/apps/rails-full/.kamal/hooks/pre-deploy.sample new file mode 100755 index 0000000..1b280c7 --- /dev/null +++ b/apps/rails-full/.kamal/hooks/pre-deploy.sample @@ -0,0 +1,109 @@ +#!/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_ROLE (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 = `git config --get remote.origin.url`.strip.delete_prefix("https://github.com/") + @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 +end + + +$stdout.sync = true + +puts "Checking build status..." +attempts = 0 +checks = GithubStatusChecks.new + +begin + 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/apps/rails-full/.kamal/hooks/pre-proxy-reboot.sample b/apps/rails-full/.kamal/hooks/pre-proxy-reboot.sample new file mode 100755 index 0000000..061f805 --- /dev/null +++ b/apps/rails-full/.kamal/hooks/pre-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooting kamal-proxy on $KAMAL_HOSTS..." diff --git a/apps/rails-full/.kamal/secrets b/apps/rails-full/.kamal/secrets new file mode 100644 index 0000000..9a771a3 --- /dev/null +++ b/apps/rails-full/.kamal/secrets @@ -0,0 +1,17 @@ +# Secrets defined here are available for reference under registry/password, env/secret, builder/secrets, +# and accessories/*/env/secret in config/deploy.yml. All secrets should be pulled from either +# password manager, ENV, or a file. DO NOT ENTER RAW CREDENTIALS HERE! This file needs to be safe for git. + +# Example of extracting secrets from 1password (or another compatible pw manager) +# SECRETS=$(kamal secrets fetch --adapter 1password --account your-account --from Vault/Item KAMAL_REGISTRY_PASSWORD RAILS_MASTER_KEY) +# KAMAL_REGISTRY_PASSWORD=$(kamal secrets extract KAMAL_REGISTRY_PASSWORD ${SECRETS}) +# RAILS_MASTER_KEY=$(kamal secrets extract RAILS_MASTER_KEY ${SECRETS}) + +# Use a GITHUB_TOKEN if private repositories are needed for the image +# GITHUB_TOKEN=$(gh config get -h github.com oauth_token) + +# Grab the registry password from ENV +KAMAL_REGISTRY_PASSWORD=$KAMAL_REGISTRY_PASSWORD + +# Improve security by using a password manager. Never check config/master.key into git! +RAILS_MASTER_KEY=$(cat config/master.key) diff --git a/apps/rails-full/.rubocop.yml b/apps/rails-full/.rubocop.yml new file mode 100644 index 0000000..f9d86d4 --- /dev/null +++ b/apps/rails-full/.rubocop.yml @@ -0,0 +1,8 @@ +# Omakase Ruby styling for Rails +inherit_gem: { rubocop-rails-omakase: rubocop.yml } + +# Overwrite or add rules to create your own house style +# +# # Use `[a, [b, c]]` not `[ a, [ b, c ] ]` +# Layout/SpaceInsideArrayLiteralBrackets: +# Enabled: false diff --git a/apps/rails-full/.ruby-version b/apps/rails-full/.ruby-version new file mode 100644 index 0000000..fa7adc7 --- /dev/null +++ b/apps/rails-full/.ruby-version @@ -0,0 +1 @@ +3.3.5 diff --git a/apps/rails-full/Dockerfile b/apps/rails-full/Dockerfile new file mode 100644 index 0000000..50561f2 --- /dev/null +++ b/apps/rails-full/Dockerfile @@ -0,0 +1,72 @@ +# 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 rails_full . +# docker run -d -p 80:80 -e RAILS_MASTER_KEY= --name rails_full rails_full + +# 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=3.3.5 +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 sqlite3 && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Set production environment +ENV RAILS_ENV="production" \ + BUNDLE_DEPLOYMENT="1" \ + BUNDLE_PATH="/usr/local/bundle" \ + BUNDLE_WITHOUT="development" + +# 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 pkg-config && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Install application gems +COPY Gemfile Gemfile.lock ./ +RUN bundle install && \ + rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ + bundle exec bootsnap precompile --gemfile + +# Copy application code +COPY . . + +# Precompile bootsnap code for faster boot times +RUN bundle exec bootsnap precompile 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 + +# Copy built artifacts: gems, application +COPY --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}" +COPY --from=build /rails /rails + +# 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 && \ + chown -R rails:rails db log storage tmp +USER 1000:1000 + +# Entrypoint prepares the database. +ENTRYPOINT ["/rails/bin/docker-entrypoint"] + +# Start server via Thruster by default, this can be overwritten at runtime +EXPOSE 80 +CMD ["./bin/thrust", "./bin/rails", "server"] diff --git a/apps/rails-full/Gemfile b/apps/rails-full/Gemfile new file mode 100644 index 0000000..52da35e --- /dev/null +++ b/apps/rails-full/Gemfile @@ -0,0 +1,70 @@ +source "https://rubygems.org" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 8.0.0" +# The modern asset pipeline for Rails [https://github.com/rails/propshaft] +gem "propshaft" +# Use sqlite3 as the database for Active Record +gem "sqlite3", ">= 2.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" +# 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.7" + +# 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" + +path "../.." do + gem "clerk-sdk-ruby", require: "clerk" +end + + +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" + + # 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" +end + +gem "dotenv-rails", "~> 3.1" diff --git a/apps/rails-full/Gemfile.lock b/apps/rails-full/Gemfile.lock new file mode 100644 index 0000000..6e4dade --- /dev/null +++ b/apps/rails-full/Gemfile.lock @@ -0,0 +1,429 @@ +PATH + remote: ../.. + specs: + clerk-sdk-ruby (4.0.0.beta4) + clerk-http-client (~> 0.0.1) + concurrent-ruby (~> 1.1) + faraday (>= 1.4.1, < 3.0) + jwt (~> 2.5) + +GEM + remote: https://rubygems.org/ + specs: + actioncable (8.0.1) + actionpack (= 8.0.1) + activesupport (= 8.0.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.0.1) + actionpack (= 8.0.1) + activejob (= 8.0.1) + activerecord (= 8.0.1) + activestorage (= 8.0.1) + activesupport (= 8.0.1) + mail (>= 2.8.0) + actionmailer (8.0.1) + actionpack (= 8.0.1) + actionview (= 8.0.1) + activejob (= 8.0.1) + activesupport (= 8.0.1) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.0.1) + actionview (= 8.0.1) + activesupport (= 8.0.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.0.1) + actionpack (= 8.0.1) + activerecord (= 8.0.1) + activestorage (= 8.0.1) + activesupport (= 8.0.1) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.0.1) + activesupport (= 8.0.1) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (8.0.1) + activesupport (= 8.0.1) + globalid (>= 0.3.6) + activemodel (8.0.1) + activesupport (= 8.0.1) + activerecord (8.0.1) + activemodel (= 8.0.1) + activesupport (= 8.0.1) + timeout (>= 0.4.0) + activestorage (8.0.1) + actionpack (= 8.0.1) + activejob (= 8.0.1) + activerecord (= 8.0.1) + activesupport (= 8.0.1) + marcel (~> 1.0) + activesupport (8.0.1) + base64 + benchmark (>= 0.3) + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + addressable (2.8.7) + public_suffix (>= 2.0.2, < 7.0) + ast (2.4.2) + base64 (0.2.0) + bcrypt_pbkdf (1.1.1) + bcrypt_pbkdf (1.1.1-arm64-darwin) + bcrypt_pbkdf (1.1.1-x86_64-darwin) + benchmark (0.4.0) + bigdecimal (3.1.9) + bindex (0.8.1) + bootsnap (1.18.4) + msgpack (~> 1.2) + brakeman (7.0.0) + racc + builder (3.3.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) + clerk-http-client (0.0.1) + faraday (>= 1.0.1, < 3.0) + faraday-multipart + marcel + concurrent-ruby (1.3.4) + connection_pool (2.4.1) + crass (1.0.6) + date (3.4.1) + debug (1.10.0) + irb (~> 1.10) + reline (>= 0.3.8) + dotenv (3.1.7) + dotenv-rails (3.1.7) + dotenv (= 3.1.7) + railties (>= 6.1) + drb (2.2.1) + ed25519 (1.3.0) + erubi (1.13.1) + et-orbi (1.2.11) + tzinfo + faraday (2.12.2) + faraday-net_http (>= 2.0, < 3.5) + json + logger + faraday-multipart (1.1.0) + multipart-post (~> 2.0) + faraday-net_http (3.4.0) + net-http (>= 0.5.0) + fugit (1.11.1) + et-orbi (~> 1, >= 1.2.11) + raabro (~> 1.4) + globalid (1.2.1) + activesupport (>= 6.1) + i18n (1.14.6) + concurrent-ruby (~> 1.0) + importmap-rails (2.1.0) + actionpack (>= 6.0.0) + activesupport (>= 6.0.0) + railties (>= 6.0.0) + io-console (0.8.0) + irb (1.14.3) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + jbuilder (2.13.0) + actionview (>= 5.0.0) + activesupport (>= 5.0.0) + json (2.9.1) + jwt (2.10.1) + base64 + kamal (2.4.0) + activesupport (>= 7.0) + base64 (~> 0.2) + bcrypt_pbkdf (~> 1.0) + concurrent-ruby (~> 1.2) + dotenv (~> 3.1) + ed25519 (~> 1.2) + 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.3) + logger (1.6.4) + loofah (2.24.0) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.8.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.4) + matrix (0.4.2) + mini_mime (1.1.5) + mini_portile2 (2.8.8) + minitest (5.25.4) + msgpack (1.7.5) + multipart-post (2.4.1) + net-http (0.6.0) + uri + net-imap (0.5.5) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-scp (4.0.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.0) + net-protocol + net-ssh (7.3.0) + nio4r (2.7.4) + nokogiri (1.18.1) + mini_portile2 (~> 2.8.2) + racc (~> 1.4) + nokogiri (1.18.1-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.1-aarch64-linux-musl) + racc (~> 1.4) + nokogiri (1.18.1-arm-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.1-arm-linux-musl) + racc (~> 1.4) + nokogiri (1.18.1-arm64-darwin) + racc (~> 1.4) + nokogiri (1.18.1-x86_64-darwin) + racc (~> 1.4) + nokogiri (1.18.1-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.1-x86_64-linux-musl) + racc (~> 1.4) + ostruct (0.6.1) + parallel (1.26.3) + parser (3.3.6.0) + ast (~> 2.4.1) + racc + propshaft (1.1.0) + actionpack (>= 7.0.0) + activesupport (>= 7.0.0) + rack + railties (>= 7.0.0) + psych (5.2.2) + date + stringio + public_suffix (6.0.1) + puma (6.5.0) + nio4r (~> 2.0) + raabro (1.4.0) + racc (1.8.1) + rack (3.1.8) + rack-session (2.1.0) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.2.0) + rack (>= 1.3) + rackup (2.2.1) + rack (>= 3) + rails (8.0.1) + actioncable (= 8.0.1) + actionmailbox (= 8.0.1) + actionmailer (= 8.0.1) + actionpack (= 8.0.1) + actiontext (= 8.0.1) + actionview (= 8.0.1) + activejob (= 8.0.1) + activemodel (= 8.0.1) + activerecord (= 8.0.1) + activestorage (= 8.0.1) + activesupport (= 8.0.1) + bundler (>= 1.15.0) + railties (= 8.0.1) + rails-dom-testing (2.2.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.2) + loofah (~> 2.21) + 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.0.1) + actionpack (= 8.0.1) + activesupport (= 8.0.1) + irb (~> 1.13) + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.2.1) + rdoc (6.10.0) + psych (>= 4.0.0) + regexp_parser (2.10.0) + reline (0.6.0) + io-console (~> 0.5) + rexml (3.4.0) + rubocop (1.69.2) + json (~> 2.3) + language_server-protocol (>= 3.17.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.36.2, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.37.0) + parser (>= 3.3.1.0) + rubocop-minitest (0.36.0) + rubocop (>= 1.61, < 2.0) + rubocop-ast (>= 1.31.1, < 2.0) + rubocop-performance (1.23.1) + rubocop (>= 1.48.1, < 2.0) + rubocop-ast (>= 1.31.1, < 2.0) + rubocop-rails (2.28.0) + activesupport (>= 4.2.0) + rack (>= 1.1) + rubocop (>= 1.52.0, < 2.0) + rubocop-ast (>= 1.31.1, < 2.0) + rubocop-rails-omakase (1.0.0) + rubocop + rubocop-minitest + rubocop-performance + rubocop-rails + ruby-progressbar (1.13.0) + rubyzip (2.4.1) + securerandom (0.4.1) + selenium-webdriver (4.27.0) + base64 (~> 0.2) + logger (~> 1.4) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 3.0) + websocket (~> 1.0) + solid_cable (3.0.5) + actioncable (>= 7.2) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_cache (1.0.6) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_queue (1.1.2) + activejob (>= 7.1) + activerecord (>= 7.1) + concurrent-ruby (>= 1.3.1) + fugit (~> 1.11.0) + railties (>= 7.1) + thor (~> 1.3.1) + sqlite3 (2.5.0-aarch64-linux-gnu) + sqlite3 (2.5.0-aarch64-linux-musl) + sqlite3 (2.5.0-arm-linux-gnu) + sqlite3 (2.5.0-arm-linux-musl) + sqlite3 (2.5.0-arm64-darwin) + sqlite3 (2.5.0-x86-linux-gnu) + sqlite3 (2.5.0-x86-linux-musl) + sqlite3 (2.5.0-x86_64-darwin) + sqlite3 (2.5.0-x86_64-linux-gnu) + sqlite3 (2.5.0-x86_64-linux-musl) + sshkit (1.23.2) + base64 + 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) + stringio (3.1.2) + thor (1.3.2) + thruster (0.1.10) + thruster (0.1.10-aarch64-linux) + thruster (0.1.10-arm64-darwin) + thruster (0.1.10-x86_64-darwin) + thruster (0.1.10-x86_64-linux) + timeout (0.4.3) + turbo-rails (2.0.11) + actionpack (>= 6.0.0) + railties (>= 6.0.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (3.1.3) + unicode-emoji (~> 4.0, >= 4.0.4) + unicode-emoji (4.0.4) + uri (1.0.2) + useragent (0.16.11) + web-console (4.2.1) + actionview (>= 6.0.0) + activemodel (>= 6.0.0) + bindex (>= 0.4.0) + railties (>= 6.0.0) + websocket (1.2.11) + websocket-driver (0.7.7) + base64 + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.7.1) + +PLATFORMS + aarch64-linux + aarch64-linux-gnu + aarch64-linux-musl + arm-linux + arm-linux-gnu + arm-linux-musl + arm64-darwin + x86-linux + x86-linux-gnu + x86-linux-musl + x86_64-darwin + x86_64-linux + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + bootsnap + brakeman + capybara + clerk-sdk-ruby! + debug + dotenv-rails (~> 3.1) + importmap-rails + jbuilder + kamal + propshaft + puma (>= 5.0) + rails (~> 8.0.0) + rubocop-rails-omakase + selenium-webdriver + solid_cable + solid_cache + solid_queue + sqlite3 (>= 2.1) + stimulus-rails + thruster + turbo-rails + tzinfo-data + web-console + +BUNDLED WITH + 2.6.2 diff --git a/apps/rails-full/README.md b/apps/rails-full/README.md new file mode 100644 index 0000000..7db80e4 --- /dev/null +++ b/apps/rails-full/README.md @@ -0,0 +1,24 @@ +# README + +This README would normally document whatever steps are necessary to get the +application up and running. + +Things you may want to cover: + +* Ruby version + +* System dependencies + +* Configuration + +* Database creation + +* Database initialization + +* How to run the test suite + +* Services (job queues, cache servers, search engines, etc.) + +* Deployment instructions + +* ... diff --git a/apps/rails-full/Rakefile b/apps/rails-full/Rakefile new file mode 100644 index 0000000..9a5ea73 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/app/assets/stylesheets/application.css b/apps/rails-full/app/assets/stylesheets/application.css new file mode 100644 index 0000000..fe93333 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/app/controllers/application_controller.rb b/apps/rails-full/app/controllers/application_controller.rb new file mode 100644 index 0000000..6b9f2e4 --- /dev/null +++ b/apps/rails-full/app/controllers/application_controller.rb @@ -0,0 +1,6 @@ +class ApplicationController < ActionController::Base + include Clerk::Authenticatable + + # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. + allow_browser versions: :modern +end diff --git a/apps/rails-full/app/controllers/home_controller.rb b/apps/rails-full/app/controllers/home_controller.rb new file mode 100644 index 0000000..71a49c7 --- /dev/null +++ b/apps/rails-full/app/controllers/home_controller.rb @@ -0,0 +1,11 @@ +class HomeController < ApplicationController + before_action :require_reverification!, only: [:protected], preset: Clerk::StepUp::Preset::STRICT + + def index + @user = clerk.user + end + + def protected + render json: {message: clerk.user? ? "Valid session" : "Not logged in"} + end +end diff --git a/apps/rails-full/app/helpers/application_helper.rb b/apps/rails-full/app/helpers/application_helper.rb new file mode 100644 index 0000000..de6be79 --- /dev/null +++ b/apps/rails-full/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/apps/rails-full/app/helpers/home_helper.rb b/apps/rails-full/app/helpers/home_helper.rb new file mode 100644 index 0000000..23de56a --- /dev/null +++ b/apps/rails-full/app/helpers/home_helper.rb @@ -0,0 +1,2 @@ +module HomeHelper +end diff --git a/apps/rails-full/app/javascript/application.js b/apps/rails-full/app/javascript/application.js new file mode 100644 index 0000000..0d7b494 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/app/javascript/controllers/application.js b/apps/rails-full/app/javascript/controllers/application.js new file mode 100644 index 0000000..1213e85 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/app/javascript/controllers/hello_controller.js b/apps/rails-full/app/javascript/controllers/hello_controller.js new file mode 100644 index 0000000..5975c07 --- /dev/null +++ b/apps/rails-full/app/javascript/controllers/hello_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + connect() { + this.element.textContent = "Hello World!" + } +} diff --git a/apps/rails-full/app/javascript/controllers/index.js b/apps/rails-full/app/javascript/controllers/index.js new file mode 100644 index 0000000..1156bf8 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/app/jobs/application_job.rb b/apps/rails-full/app/jobs/application_job.rb new file mode 100644 index 0000000..d394c3d --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/app/mailers/application_mailer.rb b/apps/rails-full/app/mailers/application_mailer.rb new file mode 100644 index 0000000..3c34c81 --- /dev/null +++ b/apps/rails-full/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" +end diff --git a/apps/rails-full/app/models/application_record.rb b/apps/rails-full/app/models/application_record.rb new file mode 100644 index 0000000..b63caeb --- /dev/null +++ b/apps/rails-full/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/apps/rails-full/app/views/home/index.html.erb b/apps/rails-full/app/views/home/index.html.erb new file mode 100644 index 0000000..888d8a5 --- /dev/null +++ b/apps/rails-full/app/views/home/index.html.erb @@ -0,0 +1,7 @@ +

+ <% if @user %> + Authenticated User: <%= @user.first_name %> (<%= @user.id %>) + <% else %> + Not Authenticated + <% end %> +

\ No newline at end of file diff --git a/apps/rails-full/app/views/layouts/application.html.erb b/apps/rails-full/app/views/layouts/application.html.erb new file mode 100644 index 0000000..d4d5c92 --- /dev/null +++ b/apps/rails-full/app/views/layouts/application.html.erb @@ -0,0 +1,60 @@ + + + + <%= content_for(:title) || "Rails Full" %> + + + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= yield :head %> + + <%# Enable PWA manifest for installable apps (make sure to enable in config/routes.rb too!) %> + <%#= 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 %> + + + +

Rails (Full Stack)

+ <%= yield %> +
+ + diff --git a/apps/rails-full/app/views/layouts/mailer.html.erb b/apps/rails-full/app/views/layouts/mailer.html.erb new file mode 100644 index 0000000..3aac900 --- /dev/null +++ b/apps/rails-full/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/apps/rails-full/app/views/layouts/mailer.text.erb b/apps/rails-full/app/views/layouts/mailer.text.erb new file mode 100644 index 0000000..37f0bdd --- /dev/null +++ b/apps/rails-full/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/apps/rails-full/app/views/pwa/manifest.json.erb b/apps/rails-full/app/views/pwa/manifest.json.erb new file mode 100644 index 0000000..cc09aa9 --- /dev/null +++ b/apps/rails-full/app/views/pwa/manifest.json.erb @@ -0,0 +1,22 @@ +{ + "name": "RailsFull", + "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": "RailsFull.", + "theme_color": "red", + "background_color": "red" +} diff --git a/apps/rails-full/app/views/pwa/service-worker.js b/apps/rails-full/app/views/pwa/service-worker.js new file mode 100644 index 0000000..b3a13fb --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/bin/brakeman b/apps/rails-full/bin/brakeman new file mode 100755 index 0000000..ace1c9b --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/bin/bundle b/apps/rails-full/bin/bundle new file mode 100755 index 0000000..50da5fd --- /dev/null +++ b/apps/rails-full/bin/bundle @@ -0,0 +1,109 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a.match?(Gem::Version::ANCHORED_VERSION_PATTERN) + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../Gemfile", __dir__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, ".locked") + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || + cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + bundler_gem_version.approximate_recommendation + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/apps/rails-full/bin/dev b/apps/rails-full/bin/dev new file mode 100755 index 0000000..5f91c20 --- /dev/null +++ b/apps/rails-full/bin/dev @@ -0,0 +1,2 @@ +#!/usr/bin/env ruby +exec "./bin/rails", "server", *ARGV diff --git a/apps/rails-full/bin/docker-entrypoint b/apps/rails-full/bin/docker-entrypoint new file mode 100755 index 0000000..57567d6 --- /dev/null +++ b/apps/rails-full/bin/docker-entrypoint @@ -0,0 +1,14 @@ +#!/bin/bash -e + +# Enable jemalloc for reduced memory usage and latency. +if [ -z "${LD_PRELOAD+x}" ]; then + LD_PRELOAD=$(find /usr/lib -name libjemalloc.so.2 -print -quit) + export LD_PRELOAD +fi + +# 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/apps/rails-full/bin/importmap b/apps/rails-full/bin/importmap new file mode 100755 index 0000000..36502ab --- /dev/null +++ b/apps/rails-full/bin/importmap @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby + +require_relative "../config/application" +require "importmap/commands" diff --git a/apps/rails-full/bin/jobs b/apps/rails-full/bin/jobs new file mode 100755 index 0000000..dcf59f3 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/bin/kamal b/apps/rails-full/bin/kamal new file mode 100755 index 0000000..cbe59b9 --- /dev/null +++ b/apps/rails-full/bin/kamal @@ -0,0 +1,27 @@ +#!/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__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("kamal", "kamal") diff --git a/apps/rails-full/bin/rails b/apps/rails-full/bin/rails new file mode 100755 index 0000000..efc0377 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/bin/rake b/apps/rails-full/bin/rake new file mode 100755 index 0000000..4fbf10b --- /dev/null +++ b/apps/rails-full/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/apps/rails-full/bin/rubocop b/apps/rails-full/bin/rubocop new file mode 100755 index 0000000..40330c0 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/bin/setup b/apps/rails-full/bin/setup new file mode 100755 index 0000000..be3db3c --- /dev/null +++ b/apps/rails-full/bin/setup @@ -0,0 +1,34 @@ +#!/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" + + 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/apps/rails-full/bin/thrust b/apps/rails-full/bin/thrust new file mode 100755 index 0000000..36bde2d --- /dev/null +++ b/apps/rails-full/bin/thrust @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("thruster", "thrust") diff --git a/apps/rails-full/config.ru b/apps/rails-full/config.ru new file mode 100644 index 0000000..4a3c09a --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/config/application.rb b/apps/rails-full/config/application.rb new file mode 100644 index 0000000..47f0c4a --- /dev/null +++ b/apps/rails-full/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) + +# Load environment variables manually from shared .env file +require "dotenv/rails" +Dotenv::Rails.files.unshift(File.expand_path(File.join("..", "..", ".env"))) + +module RailsFull + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 8.0 + + # 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]) + + # 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/apps/rails-full/config/boot.rb b/apps/rails-full/config/boot.rb new file mode 100644 index 0000000..988a5dd --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/config/cable.yml b/apps/rails-full/config/cable.yml new file mode 100644 index 0000000..b9adc5a --- /dev/null +++ b/apps/rails-full/config/cable.yml @@ -0,0 +1,17 @@ +# 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: async + +test: + adapter: test + +production: + adapter: solid_cable + connects_to: + database: + writing: cable + polling_interval: 0.1.seconds + message_retention: 1.day diff --git a/apps/rails-full/config/cache.yml b/apps/rails-full/config/cache.yml new file mode 100644 index 0000000..19d4908 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/config/credentials.yml.enc b/apps/rails-full/config/credentials.yml.enc new file mode 100644 index 0000000..0ae1a82 --- /dev/null +++ b/apps/rails-full/config/credentials.yml.enc @@ -0,0 +1 @@ +HjFmR7rvjb6I8x4lUwbNJW7XxLVXkqUz2gONRhdXNK4flRFut+273GglF3i0hxNc/au4TlXai1EdH4dnE3nlnT/FADvU07kG8J5Q/HTT6IlvObtcw4uDgFtMVx/IvbitIjB9c2amaFKbBucjy9nBpopewh4TZbmJevA1QtGRI9V3A6eDeUuTHM3MM34q7oKV/kx5EH3njPxYGx6lWwQMmTDhkLB0bjf6erdNRVsglZVXmSs9opTO5vmoAkOBFb4GdtOXq297BBNTW2Cnc/BhW403IuIMxBX9R9299n0TNsRSITWKnXZ+VqPlxwM2/tZwiZlfd5R22KqzZC4a7dRdwZ24y46LBMsIk+6q2rosV0a6S+hN+FDYTkGMjj2kYlYjfMKJjIGf6xM8n59YOgh/Ir9V/ouf42W30ZDFkauX8XL0ygQRvICESGzg4QEakkoPJoHboiUmnUoOBCfUbXg50C2+dAiFUayKO8vORg4UsVXSdg6AES9K9rk6--5BPhfQGoIFXv/74y--dDR6BykRl0GAw/Dc89/vQQ== \ No newline at end of file diff --git a/apps/rails-full/config/database.yml b/apps/rails-full/config/database.yml new file mode 100644 index 0000000..2640cb5 --- /dev/null +++ b/apps/rails-full/config/database.yml @@ -0,0 +1,41 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: storage/development.sqlite3 + +# 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: storage/test.sqlite3 + + +# Store production database in the storage/ directory, which by default +# is mounted as a persistent Docker volume in config/deploy.yml. +production: + primary: + <<: *default + database: storage/production.sqlite3 + cache: + <<: *default + database: storage/production_cache.sqlite3 + migrations_paths: db/cache_migrate + queue: + <<: *default + database: storage/production_queue.sqlite3 + migrations_paths: db/queue_migrate + cable: + <<: *default + database: storage/production_cable.sqlite3 + migrations_paths: db/cable_migrate diff --git a/apps/rails-full/config/deploy.yml b/apps/rails-full/config/deploy.yml new file mode 100644 index 0000000..c1f6620 --- /dev/null +++ b/apps/rails-full/config/deploy.yml @@ -0,0 +1,116 @@ +# Name of your application. Used to uniquely configure containers. +service: rails_full + +# Name of the container image. +image: your-user/rails_full + +# Deploy to these servers. +servers: + web: + - 192.168.0.1 + # job: + # hosts: + # - 192.168.0.1 + # cmd: bin/jobs + +# Enable SSL auto certification via Let's Encrypt and allow for multiple apps on a single web server. +# Remove this section when using multiple web servers and ensure you terminate SSL at your load balancer. +# +# Note: If using Cloudflare, set encryption mode in SSL/TLS setting to "Full" to enable CF-to-app encryption. +proxy: + ssl: true + host: app.example.com + +# Credentials for your image host. +registry: + # Specify the registry server, if you're not using Docker Hub + # server: registry.digitalocean.com / ghcr.io / ... + username: your-user + + # Always use an access token rather than real password when possible. + password: + - KAMAL_REGISTRY_PASSWORD + +# Inject ENV variables into containers (secrets come from .kamal/secrets). +env: + secret: + - RAILS_MASTER_KEY + clear: + # Run the Solid Queue Supervisor inside the web server's Puma process to do jobs. + # When you start using multiple servers, you should split out job processing to a dedicated machine. + SOLID_QUEUE_IN_PUMA: true + + # Set number of processes dedicated to Solid Queue (default: 1) + # JOB_CONCURRENCY: 3 + + # Set number of cores available to the application on each server (default: 1). + # WEB_CONCURRENCY: 2 + + # Match this to any external database server to configure Active Record correctly + # Use rails_full-db for a db accessory server on same machine via local kamal docker network. + # DB_HOST: 192.168.0.2 + + # Log everything from Rails + # RAILS_LOG_LEVEL: debug + +# Aliases are triggered with "bin/kamal ". You can overwrite arguments on invocation: +# "bin/kamal logs -r job" will tail logs from the first server in the job section. +aliases: + console: app exec --interactive --reuse "bin/rails console" + shell: app exec --interactive --reuse "bash" + logs: app logs -f + dbc: app exec --interactive --reuse "bin/rails dbconsole" + + +# Use a persistent storage volume for sqlite database files and local Active Storage files. +# Recommended to change this to a mounted volume path that is backed up off server. +volumes: + - "rails_full_storage:/rails/storage" + + +# Bridge fingerprinted assets, like JS and CSS, between versions to avoid +# hitting 404 on in-flight requests. Combines all files from new and old +# version inside the asset_path. +asset_path: /rails/public/assets + +# Configure the image builder. +builder: + arch: amd64 + + # # Build image via remote server (useful for faster amd64 builds on arm64 computers) + # remote: ssh://docker@docker-builder-server + # + # # Pass arguments and secrets to the Docker build process + # args: + # RUBY_VERSION: 3.3.5 + # secrets: + # - GITHUB_TOKEN + # - RAILS_MASTER_KEY + +# Use a different ssh user than root +# ssh: +# user: app + +# Use accessory services (secrets come from .kamal/secrets). +# accessories: +# db: +# image: mysql:8.0 +# host: 192.168.0.2 +# # Change to 3306 to expose port to the world instead of just local network. +# port: "127.0.0.1:3306:3306" +# env: +# clear: +# MYSQL_ROOT_HOST: '%' +# secret: +# - MYSQL_ROOT_PASSWORD +# files: +# - config/mysql/production.cnf:/etc/mysql/my.cnf +# - db/production.sql:/docker-entrypoint-initdb.d/setup.sql +# directories: +# - data:/var/lib/mysql +# redis: +# image: redis:7.0 +# host: 192.168.0.2 +# port: 6379 +# directories: +# - data:/data diff --git a/apps/rails-full/config/environment.rb b/apps/rails-full/config/environment.rb new file mode 100644 index 0000000..cac5315 --- /dev/null +++ b/apps/rails-full/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/apps/rails-full/config/environments/development.rb b/apps/rails-full/config/environments/development.rb new file mode 100644 index 0000000..4cc21c4 --- /dev/null +++ b/apps/rails-full/config/environments/development.rb @@ -0,0 +1,72 @@ +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 + + # 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 + + # 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/apps/rails-full/config/environments/production.rb b/apps/rails-full/config/environments/production.rb new file mode 100644 index 0000000..351afa4 --- /dev/null +++ b/apps/rails-full/config/environments/production.rb @@ -0,0 +1,91 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # 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 + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + config.assume_ssl = true + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + config.force_ssl = true + + # Skip http-to-https redirect for the default health check endpoint. + # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } + + # 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: "example.com" } + + # Specify outgoing SMTP server. Remember to add smtp/* credentials via rails credentials:edit. + # config.action_mailer.smtp_settings = { + # user_name: Rails.application.credentials.dig(:smtp, :user_name), + # password: Rails.application.credentials.dig(:smtp, :password), + # address: "smtp.example.com", + # port: 587, + # authentication: :plain + # } + + # 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 ] + + # Enable DNS rebinding protection and other `Host` header attacks. + # config.hosts = [ + # "example.com", # Allow requests from example.com + # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` + # ] + # + # Skip DNS rebinding protection for the default health check endpoint. + # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } +end diff --git a/apps/rails-full/config/environments/test.rb b/apps/rails-full/config/environments/test.rb new file mode 100644 index 0000000..c2095b1 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/config/importmap.rb b/apps/rails-full/config/importmap.rb new file mode 100644 index 0000000..909dfc5 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/config/initializers/assets.rb b/apps/rails-full/config/initializers/assets.rb new file mode 100644 index 0000000..4873244 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/config/initializers/clerk.rb b/apps/rails-full/config/initializers/clerk.rb new file mode 100644 index 0000000..0e8cfe9 --- /dev/null +++ b/apps/rails-full/config/initializers/clerk.rb @@ -0,0 +1,4 @@ +Clerk.configure do |config| + # config.publishable_key = ENV["CLERK_PUBLISHABLE_KEY"] + # config.secret_key = ENV["CLERK_SECRET_KEY"] +end diff --git a/apps/rails-full/config/initializers/content_security_policy.rb b/apps/rails-full/config/initializers/content_security_policy.rb new file mode 100644 index 0000000..b3076b3 --- /dev/null +++ b/apps/rails-full/config/initializers/content_security_policy.rb @@ -0,0 +1,25 @@ +# 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, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap, inline scripts, and inline styles. +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src style-src) +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/apps/rails-full/config/initializers/filter_parameter_logging.rb b/apps/rails-full/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..c0b717f --- /dev/null +++ b/apps/rails-full/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 +] diff --git a/apps/rails-full/config/initializers/inflections.rb b/apps/rails-full/config/initializers/inflections.rb new file mode 100644 index 0000000..3860f65 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/config/locales/en.yml b/apps/rails-full/config/locales/en.yml new file mode 100644 index 0000000..6c349ae --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/config/puma.rb b/apps/rails-full/config/puma.rb new file mode 100644 index 0000000..a248513 --- /dev/null +++ b/apps/rails-full/config/puma.rb @@ -0,0 +1,41 @@ +# 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. +# +# 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/apps/rails-full/config/queue.yml b/apps/rails-full/config/queue.yml new file mode 100644 index 0000000..9eace59 --- /dev/null +++ b/apps/rails-full/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: 0.1 + +development: + <<: *default + +test: + <<: *default + +production: + <<: *default diff --git a/apps/rails-full/config/recurring.yml b/apps/rails-full/config/recurring.yml new file mode 100644 index 0000000..d045b19 --- /dev/null +++ b/apps/rails-full/config/recurring.yml @@ -0,0 +1,10 @@ +# production: +# periodic_cleanup: +# class: CleanSoftDeletedRecordsJob +# queue: background +# args: [ 1000, { batch_size: 500 } ] +# schedule: every hour +# periodic_command: +# command: "SoftDeletedRecord.due.delete_all" +# priority: 2 +# schedule: at 5am every day diff --git a/apps/rails-full/config/routes.rb b/apps/rails-full/config/routes.rb new file mode 100644 index 0000000..15fe572 --- /dev/null +++ b/apps/rails-full/config/routes.rb @@ -0,0 +1,15 @@ +Rails.application.routes.draw do + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # 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 + + # Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb) + # get "manifest" => "rails/pwa#manifest", as: :pwa_manifest + # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker + + get "protected" => "home#protected", :as => :protected + # Defines the root path route ("/") + root "home#index" +end diff --git a/apps/rails-full/config/storage.yml b/apps/rails-full/config/storage.yml new file mode 100644 index 0000000..4942ab6 --- /dev/null +++ b/apps/rails-full/config/storage.yml @@ -0,0 +1,34 @@ +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 %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/apps/rails-full/db/cable_schema.rb b/apps/rails-full/db/cable_schema.rb new file mode 100644 index 0000000..2366660 --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/db/cache_schema.rb b/apps/rails-full/db/cache_schema.rb new file mode 100644 index 0000000..6005a29 --- /dev/null +++ b/apps/rails-full/db/cache_schema.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +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/apps/rails-full/db/queue_schema.rb b/apps/rails-full/db/queue_schema.rb new file mode 100644 index 0000000..85194b6 --- /dev/null +++ b/apps/rails-full/db/queue_schema.rb @@ -0,0 +1,129 @@ +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.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_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 + + 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/apps/rails-full/db/seeds.rb b/apps/rails-full/db/seeds.rb new file mode 100644 index 0000000..4fbd6ed --- /dev/null +++ b/apps/rails-full/db/seeds.rb @@ -0,0 +1,9 @@ +# This file should ensure the existence of records required to run the application in every environment (production, +# development, test). The code here should be idempotent so that it can be executed at any point in every environment. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Example: +# +# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| +# MovieGenre.find_or_create_by!(name: genre_name) +# end diff --git a/apps/rails-full/public/400.html b/apps/rails-full/public/400.html new file mode 100644 index 0000000..282dbc8 --- /dev/null +++ b/apps/rails-full/public/400.html @@ -0,0 +1,114 @@ + + + + + + + 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/apps/rails-full/public/404.html b/apps/rails-full/public/404.html new file mode 100644 index 0000000..c0670bc --- /dev/null +++ b/apps/rails-full/public/404.html @@ -0,0 +1,114 @@ + + + + + + + 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/apps/rails-full/public/406-unsupported-browser.html b/apps/rails-full/public/406-unsupported-browser.html new file mode 100644 index 0000000..9532a9c --- /dev/null +++ b/apps/rails-full/public/406-unsupported-browser.html @@ -0,0 +1,114 @@ + + + + + + + Your browser is not supported (406 Not Acceptable) + + + + + + + + + + + + + +
+
+ +
+
+

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

+
+
+ + + + diff --git a/apps/rails-full/public/422.html b/apps/rails-full/public/422.html new file mode 100644 index 0000000..8bcf060 --- /dev/null +++ b/apps/rails-full/public/422.html @@ -0,0 +1,114 @@ + + + + + + + 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/apps/rails-full/public/500.html b/apps/rails-full/public/500.html new file mode 100644 index 0000000..d77718c --- /dev/null +++ b/apps/rails-full/public/500.html @@ -0,0 +1,114 @@ + + + + + + + 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/apps/rails-full/public/icon.png b/apps/rails-full/public/icon.png new file mode 100644 index 0000000..c4c9dbf Binary files /dev/null and b/apps/rails-full/public/icon.png differ diff --git a/apps/rails-full/public/icon.svg b/apps/rails-full/public/icon.svg new file mode 100644 index 0000000..04b34bf --- /dev/null +++ b/apps/rails-full/public/icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/apps/rails-full/public/robots.txt b/apps/rails-full/public/robots.txt new file mode 100644 index 0000000..c19f78a --- /dev/null +++ b/apps/rails-full/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/apps/rails-full/test/application_system_test_case.rb b/apps/rails-full/test/application_system_test_case.rb new file mode 100644 index 0000000..cee29fd --- /dev/null +++ b/apps/rails-full/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :headless_chrome, screen_size: [ 1400, 1400 ] +end diff --git a/apps/rails-full/test/controllers/home_controller_test.rb b/apps/rails-full/test/controllers/home_controller_test.rb new file mode 100644 index 0000000..eac0e33 --- /dev/null +++ b/apps/rails-full/test/controllers/home_controller_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class HomeControllerTest < ActionDispatch::IntegrationTest + # test "the truth" do + # assert true + # end +end diff --git a/apps/rails-full/test/test_helper.rb b/apps/rails-full/test/test_helper.rb new file mode 100644 index 0000000..0c22470 --- /dev/null +++ b/apps/rails-full/test/test_helper.rb @@ -0,0 +1,15 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +module ActiveSupport + class TestCase + # 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/apps/sinatra/app.rb b/apps/sinatra/app.rb new file mode 100644 index 0000000..7743da0 --- /dev/null +++ b/apps/sinatra/app.rb @@ -0,0 +1,29 @@ +require "active_support" +require "clerk/sinatra" +require "sinatra/base" +require "dotenv" + +Dotenv.load(".env") + +class App < Sinatra::Base + register Sinatra::Clerk + + before "/protected*" do + require_reverification! + end + + get "/" do + erb :index, format: :html5 + end + + get "/admin" do + @user = clerk.user + erb :index, format: :html5 + end + + get "/protected" do + {message: clerk.user? ? "Valid session" : "Not logged in"}.to_json + end + + # run! if app_file == $0 +end diff --git a/apps/sinatra/config.ru b/apps/sinatra/config.ru new file mode 100644 index 0000000..24b49f6 --- /dev/null +++ b/apps/sinatra/config.ru @@ -0,0 +1,2 @@ +require_relative './app' +run App \ No newline at end of file diff --git a/apps/sinatra/views/index.erb b/apps/sinatra/views/index.erb new file mode 100644 index 0000000..b04fde0 --- /dev/null +++ b/apps/sinatra/views/index.erb @@ -0,0 +1,44 @@ + + + + + + + Sinatra + + + + + +

Sinatra

+

<%= clerk.user ? "Authenticated User: #{clerk.user.first_name} (#{clerk.user.id}) " : "Not Authenticated" %>

+
+ + diff --git a/clerk-sdk-ruby.gemspec b/clerk-sdk-ruby.gemspec index ecfee9d..c967ec7 100644 --- a/clerk-sdk-ruby.gemspec +++ b/clerk-sdk-ruby.gemspec @@ -9,7 +9,7 @@ Gem::Specification.new do |spec| spec.email = ["ruby-sdk@clerk.dev"] spec.summary = "Clerk SDK for Ruby." - spec.description = "Client SDK for the Clerk backend API." + spec.description = "Client SDK for the Clerk" spec.homepage = "https://github.com/clerkinc/clerk-sdk-ruby" spec.license = "MIT" spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0") @@ -29,6 +29,7 @@ Gem::Specification.new do |spec| spec.add_dependency "faraday", ">= 1.4.1", "< 3.0" spec.add_dependency "jwt", '~> 2.5' + spec.add_dependency "clerk-http-client", "~> 0.0.1" spec.add_dependency "concurrent-ruby", "~> 1.1" spec.add_development_dependency "byebug", "~> 11.1" diff --git a/lib/clerk.rb b/lib/clerk.rb index 5076910..527a5ba 100644 --- a/lib/clerk.rb +++ b/lib/clerk.rb @@ -1,63 +1,27 @@ # frozen_string_literal: true -require_relative "clerk/version" -require_relative "clerk/constants" -require_relative "clerk/sdk" +require "clerk/configuration" +require "clerk/constants" +require "clerk/error" +require "clerk/sdk" +require "clerk/version" + +if defined?(::Rails) + require "clerk/rails" +end module Clerk class << self def configure - yield(configuration) + if block_given? + yield(configuration) + else + configuration + end end def configuration - @configuration ||= Config.new - end - end - - class Config - PRODUCTION_BASE_URL = "https://api.clerk.dev/v1/".freeze - attr_accessor :api_key, :base_url, :publishable_key, :logger, :middleware_cache_store - - # An array of route paths on which the middleware will not execute. - # - # Only request paths that match _exactly_ one of the routes will be skipped. - # As a special case, if a route ends with '/*', then all request paths that - # match the route's prefix will be skipped. - # - # For example, given the following configuration: - # - # excluded_routes = ["/foo", "/bar/*"] - # - # the following requests will be excluded: - # - # - /foo - # - /bar/baz - # - /bar/abc/xyz - # - # while the following requests will NOT be excluded: - # - # - /foo/bar - # - /bar - # - attr_accessor :excluded_routes - - def initialize - @base_url = ENV.fetch("CLERK_API_BASE", PRODUCTION_BASE_URL) - @api_key = ENV["CLERK_API_KEY"] - - secret_key = ENV["CLERK_SECRET_KEY"] - if secret_key && !secret_key.empty? - @api_key = secret_key - end - - @publishable_key = ENV["CLERK_PUBLISHABLE_KEY"] - - @excluded_routes = [] + @configuration ||= Clerk::Configuration.default end end end - -if defined?(::Rails) - require_relative "clerk/railtie" -end diff --git a/lib/clerk/authenticatable.rb b/lib/clerk/authenticatable.rb index e2b01d1..7d36108 100644 --- a/lib/clerk/authenticatable.rb +++ b/lib/clerk/authenticatable.rb @@ -1,79 +1,32 @@ # frozen_string_literal: true -require 'active_support/concern' +require "active_support/concern" module Clerk - # Concern containing Clerk Auth related helper methods module Authenticatable extend ActiveSupport::Concern protected - # Returns the verified claims as retrieved from the session token. - def clerk_session_claims - request.env['clerk'].session_claims + def clerk + request.env["clerk"] end - # Returns the verified session token. - def clerk_session_token - request.env['clerk'].session_token + def require_reverification!(preset = StepUp::Preset::STRICT, &block) + clerk.user_require_reverification!(preset) do + return yield(preset) if block_given? + render_reverification!(preset) + end end - # Makes a request to the Clerk API to fetch the data of the authenticated - # session's user. If caching is configured (see - # Config.middleware_cache_store), subsequent calls will return the cached - # object. - def clerk_user - request.env['clerk'].user - end - - # Returns the verified user_id from the token claims without making a request to Clerk API. - def clerk_user_id - request.env['clerk'].user_id - end - - # Makes a request to the Clerk API to fetch the data of the authenticated - # session's organization. If caching is configured (see - # Config.middleware_cache_store), subsequent calls will return the cached - # object. - def clerk_organization - request.env['clerk'].org - end - - # Returns the verified organization_id from the token claims without making a request to Clerk API. - def clerk_organization_id - request.env['clerk'].org_id - end - - def clerk_organization_role - request.env['clerk'].org_role - end - - def clerk_organization_permissions - request.env['clerk'].org_permissions - end - - def clerk_user_signed_in? - !!clerk_session_claims - end - - def clerk_sign_in_url - ENV.fetch('CLERK_SIGN_IN_URL') - end - - def clerk_sign_up_url - ENV.fetch('CLERK_SIGN_UP_URL') - end - - def clerk_user_profile_url - ENV.fetch('CLERK_USER_PROFILE_URL') + def render_reverification!(preset = nil) + render status: 403, json: StepUp::Reverification.error_payload(preset) end included do - helper_method :clerk_session_claims, :clerk_user, :clerk_user_id, :clerk_user_signed_in?, - :clerk_sign_in_url, :clerk_sign_up_url, :clerk_user_profile_url, - :clerk_organization, :clerk_organization_id, :clerk_organization_role, - :clerk_organization_permissions + if respond_to?(:helper_method) + helper_method :clerk, :require_reverification!, :render_reverification! + end end end end diff --git a/lib/clerk/authenticate_context.rb b/lib/clerk/authenticate_context.rb index d43df06..62e9403 100644 --- a/lib/clerk/authenticate_context.rb +++ b/lib/clerk/authenticate_context.rb @@ -1,94 +1,65 @@ # frozen_string_literal: true -require 'ostruct' -require 'forwardable' -require 'base64' +require "ostruct" +require "forwardable" module Clerk - ## # This class represents a parameter object used to contain all request and configuration # information required by the middleware to resolve the current request state. # link: https://refactoring.guru/introduce-parameter-object class AuthenticateContext extend Forwardable - ## # Expose the url of the request that this parameter object was created from as a URI object. attr_reader :clerk_url - ## # Expose properties that does not require validations or complex logic to retrieve # values by delegating them to the cookies or headers variables. def_delegators :@cookies, :session_token_in_cookie, :client_uat def_delegators :@headers, :session_token_in_header, :sec_fetch_dest - ## - # Creates a new parameter object using Rack::Request and Clerk::Config objects. + # Creates a new parameter object using ::Rack::Request and Clerk::Config objects. def initialize(request, config) @clerk_url = URI.parse(request.url) @config = config @cookies = OpenStruct.new({ - session_token_in_cookie: request.cookies[SESSION_COOKIE], - client_uat: request.cookies[CLIENT_UAT_COOKIE], - handshake_token: request.cookies[HANDSHAKE_COOKIE], - dev_browser: request.cookies[DEV_BROWSER_COOKIE] - }) + client_uat: request.cookies[CLIENT_UAT_COOKIE], + dev_browser: request.cookies[DEV_BROWSER_COOKIE], + handshake_token: request.cookies[HANDSHAKE_COOKIE], + session_token_in_cookie: request.cookies[SESSION_COOKIE] + }) @headers = OpenStruct.new({ - session_token_in_header: request.env[AUTHORIZATION_HEADER].to_s.gsub(/bearer/i, - '').strip, - sec_fetch_dest: request.env[SEC_FETCH_DEST_HEADER], - accept: request.env[ACCEPT_HEADER].to_s, - origin: request.env[ORIGIN_HEADER].to_s, - host: request.host, - port: request.port - }) + accept: request.env[ACCEPT_HEADER].to_s, + host: request.host, + origin: request.env[ORIGIN_HEADER].to_s, + port: request.port, + sec_fetch_dest: request.env[SEC_FETCH_DEST_HEADER], + session_token_in_header: request.env[AUTHORIZATION_HEADER].to_s.gsub(/bearer/i, "").strip + }) end - ## # The following properties are part of the props supported in all the AuthenticateContext # objects across all of our SDKs (eg JS, Go) def secret_key - raise Errors::Configuration, 'Clerk secret key is not set' if @config.api_key.to_s.empty? + raise ConfigurationError, "Clerk secret key is not set" if @config.secret_key.to_s.empty? - @config.api_key.to_s + @config.secret_key.to_s end def publishable_key - raise Errors::Configuration, 'Clerk publishable key is not set' if @config.publishable_key.to_s.to_s.empty? + raise ConfigurationError, "Clerk publishable key is not set" if @config.publishable_key.to_s.to_s.empty? @config.publishable_key.to_s end - def domain - # TODO(dimkl): Add multi-domain support - '' - end - - def is_satellite? - # TODO(dimkl): Add multi-domain support - false - end - - def proxy_url - # TODO(dimkl): Add multi-domain support - '' + def proxy_url? + !proxy_url.empty? end def handshake_token - @handshake_token ||= retrieve_from_query_string(@clerk_url, - HANDSHAKE_COOKIE) || @cookies.handshake_token.to_s - end - - def clerk_synced? - # TODO(dimkl): Add multi-domain support - false - end - - def clerk_redirect_url - # TODO(dimkl): Add multi-domain support - '' + @handshake_token ||= Utils.retrieve_from_query_string(@clerk_url, HANDSHAKE_COOKIE) || @cookies.handshake_token.to_s end def dev_browser @@ -97,32 +68,32 @@ def dev_browser # The frontend_api returned is without protocol prefix def frontend_api - return '' unless valid_publishable_key?(publishable_key.to_s) + return "" unless Utils.valid_publishable_key?(publishable_key.to_s) - @frontend_api ||= if !proxy_url.empty? - proxy_url - elsif development_instance? && !domain.empty? - "clerk.#{domain}" - else - # remove $ postfix - decode_publishable_key(publishable_key).chop - end + @frontend_api ||= if proxy_url? + proxy_url + elsif development_instance? && !domain.empty? + "clerk.#{domain}" + else + # remove $ postfix + Utils.decode_publishable_key(publishable_key).chop.to_s + end end def development_instance? - secret_key.start_with?('sk_test_') + secret_key.start_with?("sk_test_") end def production_instance? - secret_key.start_with?('sk_live_') + secret_key.start_with?("sk_live_") end def document_request? - @headers.sec_fetch_dest == 'document' + @headers.sec_fetch_dest == "document" end def accepts_html? - @headers.accept&.start_with?('text/html') + @headers.accept&.start_with?("text/html") end def eligible_for_multi_domain? @@ -139,7 +110,7 @@ def cross_origin_request? return false if @headers.origin.nil? # strip scheme - origin = @headers.origin.strip.sub(%r{\A(\w+:)?//}, '') + origin = @headers.origin.strip.sub(%r{\A(\w+:)?//}, "") return false if origin.empty? # Rack's host and port helpers are reverse-proxy-aware; that @@ -167,29 +138,31 @@ def session_token_in_cookie? end def dev_browser_in_url - retrieve_from_query_string(@clerk_url, DEV_BROWSER_COOKIE) + Utils.retrieve_from_query_string(@clerk_url, DEV_BROWSER_COOKIE) end - private + def dev_browser_in_url? + !!dev_browser_in_url + end - def valid_publishable_key?(publishable_key) - valid_publishable_key_prefix?(publishable_key) && valid_publishable_key_postfix?(publishable_key) + def domain + "" # TODO: Add multi-domain support end - def valid_publishable_key_prefix?(publishable_key) - publishable_key.start_with?('pk_live_') || publishable_key.start_with?('pk_test_') + def is_satellite? + false # TODO: Add multi-domain support end - def valid_publishable_key_postfix?(publishable_key) - decode_publishable_key(publishable_key).end_with?('$') + def proxy_url + "" # TODO: Add multi-domain support end - def decode_publishable_key(publishable_key) - Base64.decode64(publishable_key.split('_')[2].to_s) + def clerk_synced? + false # TODO: Add multi-domain support end - def retrieve_from_query_string(url, key) - Rack::Utils.parse_query(url.query)[key] + def clerk_redirect_url + "" # TODO: Add multi-domain support end end end diff --git a/lib/clerk/authenticate_request.rb b/lib/clerk/authenticate_request.rb index 121558c..954213c 100644 --- a/lib/clerk/authenticate_request.rb +++ b/lib/clerk/authenticate_request.rb @@ -1,20 +1,20 @@ # frozen_string_literal: true +require "clerk/proxy" +require "rack/utils" + module Clerk - ## # This class represents a service object used to determine the current request state # for the current env passed based on a provided Clerk::AuthenticateContext. # There is only 1 public method exposed (`resolve`) to be invoked with a env parameter. class AuthenticateRequest attr_reader :auth_context - ## # Creates a new instance using Clerk::AuthenticateContext object. def initialize(auth_context) @auth_context = auth_context end - ## # Determines the current request state by verifying a Clerk token in headers or cookies. # The possible outcomes of this method are `signed-in`, `signed-out` or `handshake` states. # The return values are the same as a return value of a rack middleware `[http_status_code, headers, body]`. @@ -41,13 +41,15 @@ def resolve_header_token(env) claims = verify_token(auth_context.session_token_in_header) return signed_in(env, claims, auth_context.session_token_in_header) if claims - rescue JWT::DecodeError - # malformed JSON authorization header - return signed_out(reason: TokenVerificationErrorReason::TOKEN_INVALID) rescue JWT::ExpiredSignature + # Expired token return signed_out(enforce_auth: true, reason: TokenVerificationErrorReason::TOKEN_EXPIRED) rescue JWT::InvalidIatError + # Token not active yet return signed_out(enforce_auth: true, reason: TokenVerificationErrorReason::TOKEN_NOT_ACTIVE_YET) + rescue JWT::DecodeError + # Malformed JWT (NOTE: Must be the last rescue block as it catches all decoding errors) + return signed_out(reason: TokenVerificationErrorReason::TOKEN_INVALID) end # Clerk.js should refresh the token and retry @@ -61,7 +63,7 @@ def resolve_cookie_token(env) return resolve_handshake(env) if auth_context.handshake_token? - if auth_context.development_instance? && !!auth_context.dev_browser_in_url + if auth_context.development_instance? && auth_context.dev_browser_in_url? return handle_handshake_maybe_status(env, reason: AuthErrorReason::DEV_BROWSER_SYNC) end @@ -69,21 +71,21 @@ def resolve_cookie_token(env) return handle_handshake_maybe_status(env, reason: AuthErrorReason::DEV_BROWSER_MISSING) end - # TODO(dimkl): Add multi-domain support for production + # TODO: Add multi-domain support for production # if auth_context.production_instance? && auth_context.eligible_for_multi_domain? - # return handle_handshake_maybe_status(env, reason: AuthErrorReason::SATELLITE_COOKIE_NEEDS_SYNCING) + # return handle_handshake_maybe_status(env, reason: AuthErrorReason::SATELLITE_COOKIE_NEEDS_SYNCING) # end - # TODO(dimkl): Add multi-domain support for development + # TODO: Add multi-domain support for development # if auth_context.development_instance? && auth_context.eligible_for_multi_domain? - # trigger handshake using auth_context.sign_in_url as base redirect_url - # return handle_handshake_maybe_status(env, reason: AuthErrorReason::SATELLITE_COOKIE_NEEDS_SYNCING, '', headers) + # # trigger handshake using auth_context.sign_in_url as base redirect_url + # # return handle_handshake_maybe_status(env, reason: AuthErrorReason::SATELLITE_COOKIE_NEEDS_SYNCING, '', headers) # end - # TODO(dimkl): Add multi-domain support for development in primary + # TODO: Add multi-domain support for development in primary # if auth_context.development_instance? && !auth_context.is_satellite? && auth_context.clerk_redirect_url - # trigger handshake using auth_context.clerk_redirect_url as base redirect_url + mark it as clerk_synced - # return handle_handshake_maybe_status(env, reason: AuthErrorReason::PRIMARY_RESPONDS_TO_SYNCING, '', headers) + # # trigger handshake using auth_context.clerk_redirect_url as base redirect_url + mark it as clerk_synced + # # return handle_handshake_maybe_status(env, reason: AuthErrorReason::PRIMARY_RESPONDS_TO_SYNCING, '', headers) # end if !auth_context.active_client? && !auth_context.session_token_in_cookie? @@ -100,46 +102,46 @@ def resolve_cookie_token(env) end begin - token = verify_token(auth_context.session_token_in_cookie) - return signed_out unless token + claims = verify_token(auth_context.session_token_in_cookie) + return signed_out unless claims - if token['iat'] < auth_context.client_uat.to_i + if claims["iat"] < auth_context.client_uat.to_i return handle_handshake_maybe_status(env, reason: AuthErrorReason::SESSION_TOKEN_OUTDATED) end - return signed_in(env, token, auth_context.session_token_in_cookie) + signed_in(env, claims, auth_context.session_token_in_cookie) rescue JWT::ExpiredSignature - return handshake(env, reason: TokenVerificationErrorReason::TOKEN_EXPIRED) + handshake(env, reason: TokenVerificationErrorReason::TOKEN_EXPIRED) rescue JWT::InvalidIatError - return handshake(env, reason: TokenVerificationErrorReason::TOKEN_NOT_ACTIVE_YET) + handshake(env, reason: TokenVerificationErrorReason::TOKEN_NOT_ACTIVE_YET) + rescue JWT::DecodeError + signed_out(reason: TokenVerificationErrorReason::TOKEN_INVALID) + rescue + signed_out end - - signed_out end def resolve_handshake(env) headers = { - 'Access-Control-Allow-Origin' => 'null', - 'Access-Control-Allow-Credentials' => 'true' + "Access-Control-Allow-Origin" => "null", + "Access-Control-Allow-Credentials" => "true" } - - session_token = '' + session_token = nil # Return signed-out outcome if the handshake verification fails handshake_payload = verify_token(auth_context.handshake_token) unless handshake_payload - return signed_out(enforce_auth: true, - reason: TokenVerificationErrorReason::JWK_FAILED_TO_RESOLVE) + return signed_out(enforce_auth: true, reason: TokenVerificationErrorReason::JWK_FAILED_TO_RESOLVE) end # Retrieve the cookie directives included in handshake token payload and convert it to set-cookie headers # Also retrieve the session token separately to determine the outcome of the request cookies_to_set = handshake_payload[HANDSHAKE_COOKIE_DIRECTIVES_KEY] || [] cookies_to_set.each do |cookie| - headers[COOKIE_HEADER] ||= [] - headers[COOKIE_HEADER] << cookie + headers[SET_COOKIE_HEADER] ||= [] + headers[SET_COOKIE_HEADER] << cookie - session_token = cookie.split(';')[0].split('=')[1] if cookie.start_with?("#{SESSION_COOKIE}=") + session_token = cookie.split(";")[0].split("=")[1] if cookie.start_with?("#{SESSION_COOKIE}=") end # Clear handshake token from query params and set headers to redirect to the initial request url @@ -163,7 +165,7 @@ def handle_handshake_maybe_status(env, **opts) # A outcome def handshake(_env, **opts) - redirect_headers = { LOCATION_HEADER => redirect_to_handshake } + redirect_headers = {LOCATION_HEADER => redirect_to_handshake} [307, debug_auth_headers(**opts).merge(redirect_headers), []] end @@ -172,16 +174,16 @@ def signed_out(**opts) headers = opts.delete(:headers) || {} enforce_auth = opts.delete(:enforce_auth) - if enforce_auth - [401, debug_auth_headers(**opts).merge(headers), []] - else - [nil, headers, []] - end + [ + enforce_auth ? 401 : nil, + debug_auth_headers(**opts).merge(headers), + [] + ] end # C outcome def signed_in(env, claims, token, **headers) - env['clerk'] = ProxyV2.new(session_claims: claims, session_token: token) + env["clerk"] = Proxy.new(session_claims: claims, session_token: token) [nil, headers, []] end @@ -196,21 +198,22 @@ def redirect_to_handshake remove_from_query_string(redirect_url, DEV_BROWSER_COOKIE) handshake_url = URI.parse("https://#{auth_context.frontend_api}/v1/client/handshake") - handshake_url_qs = Rack::Utils.parse_query(handshake_url.query) - handshake_url_qs['redirect_url'] = redirect_url + handshake_url_qs = ::Rack::Utils.parse_query(handshake_url.query) + handshake_url_qs["redirect_url"] = redirect_url if auth_context.development_instance? && auth_context.dev_browser? handshake_url_qs[DEV_BROWSER_COOKIE] = auth_context.dev_browser end - handshake_url.query = handshake_url_qs.to_query + handshake_url.query = ::Rack::Utils.build_query(handshake_url_qs) handshake_url.to_s end def remove_from_query_string(url, key) - qs = Rack::Utils.parse_query(url.query) + qs = ::Rack::Utils.parse_query(url.query) qs.delete(key) - url.query = qs.to_query + + url.query = ::Rack::Utils.build_query(qs) end def verify_token(token, **opts) @@ -220,7 +223,7 @@ def verify_token(token, **opts) sdk.verify_token(token, **opts) rescue JWT::ExpiredSignature, JWT::InvalidIatError => e raise e - rescue JWT::DecodeError, JWT::RequiredDependencyError + rescue JWT::DecodeError, JWT::RequiredDependencyError => _ false end end @@ -244,7 +247,7 @@ def verify_token_with_retry(env, token) end def sdk - Clerk::SDK.new + SDK.new end def debug_auth_headers(reason: nil, message: nil, status: nil) diff --git a/lib/clerk/configuration.rb b/lib/clerk/configuration.rb new file mode 100644 index 0000000..889a546 --- /dev/null +++ b/lib/clerk/configuration.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +require "clerk-http-client" + +module Clerk + class Configuration + attr_reader :cache_store + attr_reader :debug + attr_reader :excluded_routes + attr_reader :publishable_key + attr_reader :secret_key + + def initialize + @excluded_routes = [] + @publishable_key = ENV["CLERK_PUBLISHABLE_KEY"] + @secret_key = ENV["CLERK_SECRET_KEY"] + + # Default to Rails.cache or ActiveSupport::Cache::MemoryStore, if available, otherwise nil + @cache_store = if defined?(::Rails) + ::Rails.cache + elsif defined?(::ActiveSupport::Cache::MemoryStore) + ::ActiveSupport::Cache::MemoryStore.new + end + + ClerkHttpClient.configure do |config| + unless secret_key.nil? || secret_key.empty? + config.access_token = @secret_key + end + end + end + + def self.default + @@default ||= new + end + + def update(options) + options.each do |key, value| + send(:"#{key}=", value) + end + end + + def debug=(value) + ClerkHttpClient::Configuration.default.debugging = value + @debug = value + end + + def cache_store=(store) + if !store + @cache_store = nil + return + end + + raise ArgumentError, "cache_store must respond to :fetch" unless store.respond_to?(:fetch) + + @cache_store = store + end + + def excluded_routes=(routes) + raise ArgumentError, "excluded_routes must be an array" unless routes.is_a?(Array) + raise ArgumentError, "All elements in the excluded_routes array must be strings" unless routes.all? { |r| r.is_a?(String) } + + @excluded_routes = routes + end + + def publishable_key=(pk) + raise ArgumentError, "publishable_key must start with 'pk_'" unless pk.start_with?("pk_") + + @publishable_key = pk + end + + def secret_key=(sk) + raise ArgumentError, "secret_key must start with 'sk_'" unless sk.start_with?("sk_") + + ClerkHttpClient::Configuration.default.access_token = sk + @secret_key = sk + end + end +end diff --git a/lib/clerk/constants.rb b/lib/clerk/constants.rb index 4cfb4ce..2ccc560 100644 --- a/lib/clerk/constants.rb +++ b/lib/clerk/constants.rb @@ -1,51 +1,72 @@ # frozen_string_literal: true module Clerk - SESSION_COOKIE = '__session' - CLIENT_UAT_COOKIE = '__client_uat' + SESSION_COOKIE = "__session" + CLIENT_UAT_COOKIE = "__client_uat" # Dev Browser - DEV_BROWSER_COOKIE = '__clerk_db_jwt' + DEV_BROWSER_COOKIE = "__clerk_db_jwt" # Handshake - HANDSHAKE_COOKIE = '__clerk_handshake' - HANDSHAKE_COOKIE_DIRECTIVES_KEY = 'handshake' + HANDSHAKE_COOKIE = "__clerk_handshake" + HANDSHAKE_COOKIE_DIRECTIVES_KEY = "handshake" # auth debug response headers - AUTH_STATUS_HEADER = 'X-Clerk-Auth-Status' - AUTH_REASON_HEADER = 'X-Clerk-Auth-Reason' - AUTH_MESSAGE_HEADER = 'X-Clerk-Auth-Message' + AUTH_STATUS_HEADER = "X-Clerk-Auth-Status" + AUTH_REASON_HEADER = "X-Clerk-Auth-Reason" + AUTH_MESSAGE_HEADER = "X-Clerk-Auth-Message" - CONTENT_TYPE_HEADER = 'Content-Type' - SEC_FETCH_DEST_HEADER = 'HTTP_SEC_FETCH_DEST' + CONTENT_TYPE_HEADER = "Content-Type" + SEC_FETCH_DEST_HEADER = "HTTP_SEC_FETCH_DEST" # headers used in response - should be lowered case and without http prefix - LOCATION_HEADER = 'Location' - COOKIE_HEADER = 'Set-Cookie' + LOCATION_HEADER = "Location" + SET_COOKIE_HEADER = "set-cookie" # clerk url related headers - AUTHORIZATION_HEADER = 'HTTP_AUTHORIZATION' - ACCEPT_HEADER = 'HTTP_ACCEPT' - USER_AGENT_HEADER = 'HTTP_USER_AGENT' - ORIGIN_HEADER = 'HTTP_ORIGIN' + AUTHORIZATION_HEADER = "HTTP_AUTHORIZATION" + ACCEPT_HEADER = "HTTP_ACCEPT" + USER_AGENT_HEADER = "HTTP_USER_AGENT" + ORIGIN_HEADER = "HTTP_ORIGIN" module TokenVerificationErrorReason - TOKEN_INVALID = 'token-invalid' - TOKEN_EXPIRED = 'token-expired' - TOKEN_NOT_ACTIVE_YET = 'token-not-active-yet' - JWK_FAILED_TO_RESOLVE = 'jwk-failed-to-resolve' + TOKEN_INVALID = "token-invalid" + TOKEN_EXPIRED = "token-expired" + TOKEN_NOT_ACTIVE_YET = "token-not-active-yet" + JWK_FAILED_TO_RESOLVE = "jwk-failed-to-resolve" end module AuthErrorReason - CLIENT_UAT_WITHOUT_SESSION_TOKEN = 'client-uat-but-no-session-token' - DEV_BROWSER_SYNC = 'dev-browser-sync' - DEV_BROWSER_MISSING = 'dev-browser-missing' - PRIMARY_RESPONDS_TO_SYNCING = 'primary-responds-to-syncing' - SATELLITE_COOKIE_NEEDS_SYNCING = 'satellite-needs-syncing' - SESSION_TOKEN_AND_UAT_MISSING = 'session-token-and-uat-missing' - SESSION_TOKEN_MISSING = 'session-token-missing' - SESSION_TOKEN_OUTDATED = 'session-token-outdated' - SESSION_TOKEN_WITHOUT_CLIENT_UAT = 'session-token-but-no-client-uat' - UNEXPECTED_ERROR = 'unexpected-error' + CLIENT_UAT_WITHOUT_SESSION_TOKEN = "client-uat-but-no-session-token" + DEV_BROWSER_SYNC = "dev-browser-sync" + DEV_BROWSER_MISSING = "dev-browser-missing" + PRIMARY_RESPONDS_TO_SYNCING = "primary-responds-to-syncing" + SATELLITE_COOKIE_NEEDS_SYNCING = "satellite-needs-syncing" + SESSION_TOKEN_AND_UAT_MISSING = "session-token-and-uat-missing" + SESSION_TOKEN_MISSING = "session-token-missing" + SESSION_TOKEN_OUTDATED = "session-token-outdated" + SESSION_TOKEN_WITHOUT_CLIENT_UAT = "session-token-but-no-client-uat" + UNEXPECTED_ERROR = "unexpected-error" + end + + module StepUp + module Preset + STRICT_MFA = {after_minutes: 10, level: :multi_factor} + STRICT = {after_minutes: 10, level: :second_factor} + MODERATE = {after_minutes: 60, level: :second_factor} + LAX = {after_minutes: 1440, level: :second_factor} + end + + module Reverification + def self.error_payload(missing_config) + { + clerk_error: { + type: "forbidden", + reason: "reverification-error", + metadata: {reverification: missing_config} + } + } + end + end end end diff --git a/lib/clerk/error.rb b/lib/clerk/error.rb new file mode 100644 index 0000000..7441077 --- /dev/null +++ b/lib/clerk/error.rb @@ -0,0 +1,17 @@ +module Clerk + class Error < StandardError + attr_reader :status + + def initialize(msg, status:) + @errors = msg["errors"] + @status = status + super(msg.merge(status: status)) + end + end + + class AuthenticationError < Error; end + + class ConfigurationError < StandardError; end + + class FatalError < Error; end +end diff --git a/lib/clerk/errors.rb b/lib/clerk/errors.rb deleted file mode 100644 index 34686b0..0000000 --- a/lib/clerk/errors.rb +++ /dev/null @@ -1,22 +0,0 @@ -module Clerk - module Errors - class Base < StandardError - attr_reader :status - - def initialize(msg, status:) - @errors = msg["errors"] - @status = status - super(msg.merge("status" => status)) - end - end - - class Fatal < Base - end - - class Authentication < Base - end - - class Configuration < StandardError - end - end -end diff --git a/lib/clerk/jwks_cache.rb b/lib/clerk/jwks_cache.rb index 29d71fa..ec86919 100644 --- a/lib/clerk/jwks_cache.rb +++ b/lib/clerk/jwks_cache.rb @@ -1,32 +1,37 @@ -class JWKSCache - def initialize(lifetime) - @lifetime = lifetime - @jwks = nil - @last_update = nil - @lock = Concurrent::ReadWriteLock.new - end +require "concurrent" - def fetch(sdk, force_refresh: false, kid_not_found: false) - should_refresh = @lock.with_read_lock do - @jwks.nil? || @last_update.nil? || force_refresh || - (Time.now.to_i-@last_update > @lifetime) || - (kid_not_found && Time.now.to_i-@last_update > 300) +module Clerk + class JWKSCache + def initialize(lifetime) + @lifetime = lifetime + @jwks = nil + @last_update = nil + @lock = Concurrent::ReadWriteLock.new end - if should_refresh - @lock.with_write_lock do - @last_update = Time.now.to_i + def fetch(sdk, force_refresh: false, kid_not_found: false) + should_refresh = @lock.with_read_lock do + now = Time.now.to_i + + @jwks.nil? || @last_update.nil? || force_refresh || + (now - @last_update > @lifetime) || + (kid_not_found && now - @last_update > 300) + end - @jwks = begin - sdk.jwks.all["keys"] - rescue Clerk::Errors::Base - nil + if should_refresh + @lock.with_write_lock do + @last_update = Time.now.to_i + @jwks = begin + sdk.jwks.get.keys.map(&:to_hash) + rescue Clerk::Error, ClerkHttpClient::ApiError + nil + end end end - end - @lock.with_read_lock do - @jwks + @lock.with_read_lock do + @jwks + end end end end diff --git a/lib/clerk/proxy.rb b/lib/clerk/proxy.rb index ed1ebbd..0d089e6 100644 --- a/lib/clerk/proxy.rb +++ b/lib/clerk/proxy.rb @@ -1,155 +1,127 @@ -require 'clerk' -require_relative 'authenticate_context' -require_relative 'authenticate_request' +require "clerk" +require "clerk/authenticate_context" +require "clerk/authenticate_request" module Clerk class Proxy - attr_reader :session_id, :error - - def initialize(env) - req = Rack::Request.new(env) - @token = req.cookies[SESSION_COOKIE] - @session_id = req.params['_clerk_session_id'] - @session = nil - @user_id = nil - @user = nil - end + CACHE_TTL = 60 # seconds - def session - return nil if @token.nil? - return @session if @session + attr_reader :session_claims, :session_token - begin - @session = fetch_session - rescue Errors::Authentication => e - @error = e - end - @session + def initialize(session_claims: nil, session_token: nil) + @session_claims = session_claims + @session_token = session_token end - def user_id - @user_id ||= session.dig('user_id') + def user? + !@session_claims.nil? end def user - return nil if session.nil? + return nil unless user? @user ||= fetch_user(user_id) end - def debug - (instance_variables - [:@sdk]).map do |ivar| - [ivar.to_s, instance_variable_get(ivar)] - end.to_h - end - - private + def user_id + return nil unless user? - def sdk - @sdk ||= SDK.new + @session_claims["sub"] end - def cache_key - @cache_key ||= @token.split('.')[1] + def organization? + !organization_id.nil? end - def fetch_session - if session_id - cached_fetch("clerk_session:#{session_id}:#{cache_key}") do - sdk.sessions.verify_token(session_id, @token) - end - else - cached_fetch("clerk_session:#{cache_key}") do - client = sdk.clients.verify_token(@token) - @session_id = client['last_active_session_id'] - client['sessions'].find do |sess| - sess['id'] == @session_id - end - end - end - end + def organization + return nil unless organization? - def fetch_user(user_id) - cached_fetch("clerk_user:#{user_id}") do - sdk.users.find(user_id) - end + @org ||= fetch_org(organization_id) end - def cached_fetch(key, &block) - if store = Clerk.configuration.middleware_cache_store - store.fetch(key, expires_in: cache_ttl, &block) - else - yield - end - end + def organization_id + return nil unless user? - def cache_ttl - 60 + @session_claims["org_id"] end - end - class ProxyV2 - CACHE_TTL = 60 # seconds - - attr_reader :session_claims, :session_token + def organization_role + return nil if @session_claims.nil? - def initialize(session_claims: nil, session_token: nil) - @session_claims = session_claims - @session_token = session_token + @session_claims["org_role"] end - def user - return nil if user_id.nil? + def organization_permissions + return nil if @session_claims.nil? - @user ||= fetch_user(user_id) + @session_claims["org_permissions"] end - def user_id - return nil if @session_claims.nil? + # Returns true if the session needs to perform step up verification + def user_reverified?(params) + return false unless user? - @session_claims['sub'] - end + fva = session_claims["fva"] - def org - return nil if org_id.nil? + # the feature is disabled + return true if fva.nil? - @org ||= fetch_org(org_id) - end + level = params[:level] + after_minutes = params[:after_minutes].to_i + + return false if after_minutes.nil? || level.nil? - def org_id - return nil if user_id.nil? + factor1_age, factor2_age = fva + is_valid_factor1 = factor1_age != -1 && after_minutes > factor1_age + is_valid_factor2 = factor2_age != -1 && after_minutes > factor2_age - @session_claims['org_id'] + case level + when :first_factor + is_valid_factor1 + when :second_factor + (factor2_age == -1) ? is_valid_factor1 : is_valid_factor2 + when :multi_factor + (factor2_age == -1) ? is_valid_factor1 : is_valid_factor1 && is_valid_factor2 + end end - def org_role - return nil if @session_claims.nil? + def user_needs_reverification?(preset = StepUp::Preset::STRICT) + !user_reverified?(preset) + end - @session_claims['org_role'] + def user_require_reverification!(preset = StepUp::Preset::STRICT, &block) + return unless user_needs_reverification?(preset) + yield(preset) if block_given? end - def org_permissions - return nil if @session_claims.nil? + def user_reverification_rack_response(config = nil) + raise ArgumentError, "Missing config, please pass a preset a la `Clerk::StepUp::Preset::*`" if config.nil? - @session_claims['org_permissions'] + [ + 403, + {"Content-Type" => "application/json"}, + [StepUp::Reverification.error_payload(config).to_json] + ] end private def fetch_user(user_id) - cached_fetch("clerk_user:#{user_id}") do + cached_fetch("clerk:user:#{user_id}") do sdk.users.find(user_id) end end def fetch_org(org_id) - cached_fetch("clerk_org:#{org_id}") do + cached_fetch("clerk:org:#{org_id}") do sdk.organizations.find(org_id) end end def cached_fetch(key, &block) - if store = Clerk.configuration.middleware_cache_store + store = Clerk.configuration.cache_store + + if store store.fetch(key, expires_in: CACHE_TTL, &block) else yield diff --git a/lib/clerk/rack.rb b/lib/clerk/rack.rb new file mode 100644 index 0000000..ace2c6f --- /dev/null +++ b/lib/clerk/rack.rb @@ -0,0 +1,2 @@ +require "clerk" +require "clerk/rack_middleware" diff --git a/lib/clerk/rack_middleware.rb b/lib/clerk/rack_middleware.rb index a36b46c..ad755cb 100644 --- a/lib/clerk/rack_middleware.rb +++ b/lib/clerk/rack_middleware.rb @@ -1,16 +1,112 @@ -require_relative 'sdk' -require_relative 'proxy' +require "clerk" +require "clerk/authenticate_context" +require "clerk/authenticate_request" +require "clerk/proxy" +require "clerk/utils" module Clerk - class RackMiddleware - def initialize(app) - @app = app + module Rack + class Middleware + def initialize(app, options = {}) + @app = app + + Clerk.configuration.update(options) if options + @excluded_routes, @excluded_routes_wildcards = Clerk::Utils.filter_routes(Clerk.configuration.excluded_routes) + end + + def call(env) + env["clerk.initialized"] = true + + req = ::Rack::Request.new(env) + + if @excluded_routes[req.path] + env["clerk.excluded_route"] = true + return @app.call(env) + end + + @excluded_routes_wildcards.each do |route| + if req.path.start_with?(route) + env["clerk.excluded_route"] = true + return @app.call(env) + end + end + + env["clerk"] = Clerk::Proxy.new + + auth_context = AuthenticateContext.new(req, Clerk.configuration) + auth_request = AuthenticateRequest.new(auth_context) + + status, auth_request_headers, body = auth_request.resolve(env) + + return [status, auth_request_headers, body] if status + + status, headers, body = @app.call(env) + + unless auth_request_headers.empty? + # Remove them to avoid overriding existing cookies set in headers by other middlewares + auth_request_cookies = auth_request_headers.delete(SET_COOKIE_HEADER.downcase) + # merge non-cookie related headers into response headers + headers.merge!(auth_request_headers) + + set_cookie_headers!(headers, auth_request_cookies) if auth_request_cookies + end + + [status, headers, body] + end + + private + + def parse_cookie_key(cookie_header) + cookie_header.split(";")[0].split("=")[0] + end + + def set_cookie_headers!(headers, cookie_headers) + cookie_headers.each do |cookie_header| + cookie_key = parse_cookie_key(cookie_header) + cookie = ::Rack::Utils.parse_cookies_header(cookie_header) + cookie_params = convert_http_cookie_to_cookie_setter_params(cookie_key, cookie) + ::Rack::Utils.set_cookie_header!(headers, cookie_key, cookie_params) + end + end + + def convert_http_cookie_to_cookie_setter_params(cookie_key, cookie) + # convert cookie to to match cookie setter method params (lowercase symbolized keys with `:value` key) + cookie_params = cookie.transform_keys { |k| k.downcase.to_sym } + # drop the current cookie name key to avoid polluting the expected cookie params + cookie_params[:value] = cookie_params.delete(cookie_key.to_sym) + + # Ensure secure and httponly are set to true if present + cookie_params[:secure] = cookie_params.has_key?(:secure) + cookie_params[:httponly] = cookie_params.has_key?(:httponly) + + # fix issue with cookie expiration expected to be Date type + cookie_params[:expires] = Date.parse(cookie_params[:expires]) if cookie_params[:expires] + + cookie_params + end end - def call(env) - req = Rack::Request.new(env) - env['clerk'] = Proxy.new(env) - @app.call(env) + class Reverification + def initialize(app, routes: ["/*"], preset: Clerk::StepUp::Preset::STRICT) + @app = app + @preset = preset + + @included_routes, @included_routes_wildcards = Clerk::Utils.filter_routes(routes) + end + + def call(env) + raise Clerk::ConfigurationError, "`Clerk::Rack::Reverification` must be initialized after `Clerk::Rack::Middleware`" unless env["clerk.initialized"] + return @app.call(env) if env["clerk.excluded_route"] + + req = ::Rack::Request.new(env) + valid_route = @included_routes[req.path] || @included_routes_wildcards.any? { |route| req.path.start_with?(route) } + + if valid_route && env["clerk"].user_needs_reverification?(@preset) + return env["clerk"].user_reverification_rack_response(@preset) + end + + @app.call(env) + end end end end diff --git a/lib/clerk/rack_middleware_v2.rb b/lib/clerk/rack_middleware_v2.rb deleted file mode 100644 index b6d7c8c..0000000 --- a/lib/clerk/rack_middleware_v2.rb +++ /dev/null @@ -1,80 +0,0 @@ -require 'clerk' -require_relative 'authenticate_context' -require_relative 'authenticate_request' -require_relative 'proxy' - -module Clerk - class RackMiddlewareV2 - def initialize(app) - @app = app - @excluded_routes = {} - @excluded_routes_wildcards = [] - - Clerk.configuration.excluded_routes.each do |route| - route = route.strip - - if route.ends_with?('/*') - @excluded_routes_wildcards << route[0..-2] - else - @excluded_routes[route] = true - end - end - - @excluded_routes_wildcards.uniq! - end - - def call(env) - env = env - req = Rack::Request.new(env) - - return @app.call(env) if @excluded_routes[req.path] - - @excluded_routes_wildcards.each do |route| - return @app.call(env) if req.path.starts_with?(route) - end - - env['clerk'] = Clerk::ProxyV2.new - - auth_context = AuthenticateContext.new(req, Clerk.configuration) - auth_request = AuthenticateRequest.new(auth_context) - - status, auth_request_headers, body = auth_request.resolve(env) - return [status, auth_request_headers, body] if status - - status, headers, body = @app.call(env) - - unless auth_request_headers.empty? - # Remove them to avoid overriding existing cookies set in headers by other middlewares - auth_request_cookies = auth_request_headers.delete(COOKIE_HEADER) - # merge non-cookie related headers into response headers - headers.merge!(auth_request_headers) - - set_cookie_headers!(headers, auth_request_cookies) if auth_request_cookies - end - - [status, headers, body] - end - - private - - def set_cookie_headers!(headers, cookie_headers) - cookie_headers.each do |cookie_header| - cookie_key = cookie_header.split(';')[0].split('=')[0] - cookie = Rack::Utils.parse_cookies_header(cookie_header) - cookie_params = convert_http_cookie_to_cookie_setter_params(cookie, cookie_key) - Rack::Utils.set_cookie_header!(headers, cookie_key, cookie_params) - end - end - - def convert_http_cookie_to_cookie_setter_params(cookie, cookie_key) - # convert cookie to to match cookie setter method params (lowercase symbolized keys with `:value` key) - cookie_params = cookie.transform_keys { |k| k.downcase.to_sym } - # drop the current cookie name key to avoid polluting the expected cookie params - cookie_params[:value] = cookie.delete(cookie_key) - # fix issue with cookie expiration expected to be Date type - cookie_params[:expires] = Date.parse(cookie_params[:expires]) if cookie_params[:expires] - - cookie_params - end - end -end diff --git a/lib/clerk/rails.rb b/lib/clerk/rails.rb new file mode 100644 index 0000000..c6024c2 --- /dev/null +++ b/lib/clerk/rails.rb @@ -0,0 +1,3 @@ +require "clerk" +require "clerk/authenticatable" +require "clerk/railtie" diff --git a/lib/clerk/railtie.rb b/lib/clerk/railtie.rb index 0314400..7c0030f 100644 --- a/lib/clerk/railtie.rb +++ b/lib/clerk/railtie.rb @@ -1,12 +1,13 @@ # frozen_string_literal: true -# -require_relative "rack_middleware" -require_relative "rack_middleware_v2" + +require "clerk/rack_middleware" module Clerk - class Railtie < ::Rails::Railtie - initializer "clerk_railtie.configure_rails_initialization" do |app| - app.middleware.use Clerk::RackMiddlewareV2 + module Rails + class Railtie < ::Rails::Railtie + initializer "clerk.configure_rails_initialization" do |app| + app.middleware.use Clerk::Rack::Middleware + end end end end diff --git a/lib/clerk/resources.rb b/lib/clerk/resources.rb deleted file mode 100644 index 1fd3802..0000000 --- a/lib/clerk/resources.rb +++ /dev/null @@ -1,10 +0,0 @@ -require_relative "resources/allowlist_identifiers" -require_relative "resources/allowlist" -require_relative "resources/clients" -require_relative "resources/email_addresses" -require_relative "resources/emails" -require_relative "resources/organizations" -require_relative "resources/phone_numbers" -require_relative "resources/sessions" -require_relative "resources/users" -require_relative "resources/jwks" diff --git a/lib/clerk/resources/allowlist.rb b/lib/clerk/resources/allowlist.rb deleted file mode 100644 index 33f20f4..0000000 --- a/lib/clerk/resources/allowlist.rb +++ /dev/null @@ -1,16 +0,0 @@ -require "forwardable" -require_relative "singular_resource" - -module Clerk - module Resources - class Allowlist - extend Forwardable - - def initialize(client) - @resource = SingularResource.new(client, "beta_features/allowlist") - end - - def_delegators :@resource, :update - end - end -end diff --git a/lib/clerk/resources/allowlist_identifiers.rb b/lib/clerk/resources/allowlist_identifiers.rb deleted file mode 100644 index 915d9ee..0000000 --- a/lib/clerk/resources/allowlist_identifiers.rb +++ /dev/null @@ -1,16 +0,0 @@ -require "forwardable" -require_relative "plural_resource" - -module Clerk - module Resources - class AllowlistIdentifiers - extend Forwardable - - def initialize(client) - @resource = PluralResource.new(client, "allowlist_identifiers") - end - - def_delegators :@resource, :all, :create, :delete - end - end -end diff --git a/lib/clerk/resources/clients.rb b/lib/clerk/resources/clients.rb deleted file mode 100644 index 5509540..0000000 --- a/lib/clerk/resources/clients.rb +++ /dev/null @@ -1,23 +0,0 @@ -require "forwardable" -require_relative "plural_resource" - -module Clerk - module Resources - class Clients - extend Forwardable - - def initialize(client) - @client = client - @resource = PluralResource.new(client, "clients") - end - - def verify_token(token) - @client.request(:post, "#{@resource.collection_path}/verify", - body: {token: token}) - end - - def_delegators :@resource, :all, :find - end - end -end - diff --git a/lib/clerk/resources/email_addresses.rb b/lib/clerk/resources/email_addresses.rb deleted file mode 100644 index b311b95..0000000 --- a/lib/clerk/resources/email_addresses.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "forwardable" -require_relative "plural_resource" - -module Clerk - module Resources - class EmailAddresses - extend Forwardable - - def initialize(client) - @client = client - @resource = PluralResource.new(client, "email_addresses") - end - - def_delegators :@resource, :find, :create, :update, :delete - end - end -end diff --git a/lib/clerk/resources/emails.rb b/lib/clerk/resources/emails.rb deleted file mode 100644 index 5a532a5..0000000 --- a/lib/clerk/resources/emails.rb +++ /dev/null @@ -1,16 +0,0 @@ -require "forwardable" -require_relative "plural_resource" - -module Clerk - module Resources - class Emails - extend Forwardable - - def initialize(client) - @resource = PluralResource.new(client, "emails") - end - - def_delegators :@resource, :create - end - end -end diff --git a/lib/clerk/resources/jwks.rb b/lib/clerk/resources/jwks.rb deleted file mode 100644 index c446d23..0000000 --- a/lib/clerk/resources/jwks.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "forwardable" - -module Clerk - module Resources - class JWKS - extend Forwardable - - def initialize(client) - @client = client - end - - def all(timeout: 5) - @client.request(:get, "jwks", timeout: timeout) - end - end - end -end diff --git a/lib/clerk/resources/organizations.rb b/lib/clerk/resources/organizations.rb deleted file mode 100644 index 0df2967..0000000 --- a/lib/clerk/resources/organizations.rb +++ /dev/null @@ -1,73 +0,0 @@ -require "forwardable" -require_relative "plural_resource" - -module Clerk - module Resources - class Organizations - extend Forwardable - - def initialize(client) - @client = client - @resource = PluralResource.new(client, "organizations") - end - - def_delegators :@resource, :all, :find, :create, :update, :delete - - def update_metadata(org_id, private_metadata: {}, public_metadata: {}) - data = {} - data["private_metadata"] = private_metadata.to_json if !private_metadata.empty? - data["public_metadata"] = public_metadata.to_json if !public_metadata.empty? - - @client.request(:patch, "#{@resource.resource_path(org_id)}/metadata", body: data) - end - - # - # Invitations - # - def pending_invitations(org_id, query_params = {}) - @client.request(:get, "#{invitations_path(org_id)}/pending", query: query_params) - end - - def create_invitation(org_id, data) - @client.request(:post, invitations_path(org_id), body: data) - end - - def revoke_invitation(org_id, invitation_id, data) - @client.request(:post, "#{invitations_path(org_id, invitation_id)}/revoke", body: data) - end - - # - # Memberships - # - def memberships(org_id, query_params = {}) - @client.request(:get, memberships_path(org_id), query: query_params) - end - - def create_membership(org_id, data) - @client.request(:post, memberships_path(org_id), body: data) - end - - def update_membership(org_id, user_id, data) - @client.request(:patch, memberships_path(org_id, user_id), body: data) - end - - def delete_membership(org_id, user_id) - @client.request(:delete, memberships_path(org_id, user_id)) - end - - private - - def invitations_path(org_id, invitation_id=nil) - path = "#{@resource.resource_path(org_id)}/invitations" - path << "/#{invitation_id}" if invitation_id - path - end - - def memberships_path(org_id, user_id=nil) - path = "#{@resource.resource_path(org_id)}/memberships" - path << "/#{user_id}" if user_id - path - end - end - end -end diff --git a/lib/clerk/resources/phone_numbers.rb b/lib/clerk/resources/phone_numbers.rb deleted file mode 100644 index 55d53e6..0000000 --- a/lib/clerk/resources/phone_numbers.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "forwardable" -require_relative "plural_resource" - -module Clerk - module Resources - class PhoneNumbers - extend Forwardable - - def initialize(client) - @client = client - @resource = PluralResource.new(client, "phone_numbers") - end - - def_delegators :@resource, :find, :create, :update, :delete - end - end -end diff --git a/lib/clerk/resources/plural_resource.rb b/lib/clerk/resources/plural_resource.rb deleted file mode 100644 index 9439fc0..0000000 --- a/lib/clerk/resources/plural_resource.rb +++ /dev/null @@ -1,38 +0,0 @@ -module Clerk - module Resources - class PluralResource - def initialize(client, path_prefix) - @client = client - @path_prefix = path_prefix - end - - def all(query_params = {}) - @client.request(:get, collection_path, query: query_params) - end - - def find(id) - @client.request(:get, resource_path(id)) - end - - def create(data = nil) - @client.request(:post, collection_path, body: data) - end - - def update(id, changes = nil) - @client.request(:patch, resource_path(id), body: changes) - end - - def delete(id) - @client.request(:delete, resource_path(id)) - end - - def collection_path - @path_prefix - end - - def resource_path(id) - "#{@path_prefix}/#{id}" - end - end - end -end diff --git a/lib/clerk/resources/sessions.rb b/lib/clerk/resources/sessions.rb deleted file mode 100644 index 42b9097..0000000 --- a/lib/clerk/resources/sessions.rb +++ /dev/null @@ -1,26 +0,0 @@ -require "forwardable" -require_relative "plural_resource" - -module Clerk - module Resources - class Sessions - extend Forwardable - - def initialize(client) - @client = client - @resource = PluralResource.new(client, "sessions") - end - - def revoke(id) - @client.request(:post, "#{@resource.resource_path(id)}/revoke") - end - - def verify_token(id, token) - @client.request(:post, "#{@resource.resource_path(id)}/verify", - body: {token: token}) - end - - def_delegators :@resource, :all, :find - end - end -end diff --git a/lib/clerk/resources/singular_resource.rb b/lib/clerk/resources/singular_resource.rb deleted file mode 100644 index 6bea2f5..0000000 --- a/lib/clerk/resources/singular_resource.rb +++ /dev/null @@ -1,14 +0,0 @@ -module Clerk - module Resources - class SingularResource - def initialize(client, resource_path) - @client = client - @resource_path = resource_path - end - - def update(changes = {}) - @client.request(:patch, @resource_path, body: changes) - end - end - end -end diff --git a/lib/clerk/resources/testing_tokens.rb b/lib/clerk/resources/testing_tokens.rb deleted file mode 100644 index 00a2fd0..0000000 --- a/lib/clerk/resources/testing_tokens.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "forwardable" -require_relative "plural_resource" - -module Clerk - module Resources - class TestingTokens - extend Forwardable - - def initialize(client) - @client = client - @resource = PluralResource.new(client, "testing_tokens") - end - - def_delegators :@resource, :create - end - end -end diff --git a/lib/clerk/resources/users.rb b/lib/clerk/resources/users.rb deleted file mode 100644 index 2ce02b1..0000000 --- a/lib/clerk/resources/users.rb +++ /dev/null @@ -1,37 +0,0 @@ -require "forwardable" -require_relative "plural_resource" - -module Clerk - module Resources - class Users - extend Forwardable - - def initialize(client) - @client = client - @resource = PluralResource.new(client, "users") - end - - def_delegators :@resource, :all, :find, :create, :update, :delete - - def oauth_access_token(user_id, provider) - @client.request(:get, "#{@resource.resource_path(user_id)}/oauth_access_tokens/#{provider}") - end - - def verify_password(user_id, password) - @client.request(:post, "#{@resource.resource_path(user_id)}/verify_password", body: { password: password }) - end - - def verify_totp(user_id, totp_or_backup_code) - @client.request(:post, "#{@resource.resource_path(user_id)}/verify_totp", body: { code: totp_or_backup_code }) - end - - def disable_mfa(user_id) - @client.request(:delete, "#{@resource.resource_path(user_id)}/mfa") - end - - def organization_memberships(user_id, query_params = {}) - @client.request(:get, "#{@resource.resource_path(user_id)}/organization_memberships", query: query_params) - end - end - end -end diff --git a/lib/clerk/sdk.rb b/lib/clerk/sdk.rb index ca53aa9..e78d1c5 100644 --- a/lib/clerk/sdk.rb +++ b/lib/clerk/sdk.rb @@ -1,35 +1,18 @@ -# frozen_string_literal: true - -require "faraday" -require "logger" -require "net/http" -require "json" +require "clerk-http-client" +require "clerk/jwks_cache" +require "clerk/version" require "jwt" -require "concurrent-ruby" - -require_relative "resources/allowlist_identifiers" -require_relative "resources/allowlist" -require_relative "resources/clients" -require_relative "resources/email_addresses" -require_relative "resources/emails" -require_relative "resources/organizations" -require_relative "resources/phone_numbers" -require_relative "resources/sessions" -require_relative "resources/testing_tokens" -require_relative "resources/users" -require_relative "resources/jwks" -require_relative "errors" -require_relative "jwks_cache" module Clerk - class SDK + class SDK < ClerkHttpClient::SDK + # TODO: Move to constants? DEFAULT_HEADERS = { - "User-Agent" => "Clerk/#{Clerk::VERSION}; Faraday/#{Faraday::VERSION}; Ruby/#{RUBY_VERSION}", - "X-Clerk-SDK" => "ruby/#{Clerk::VERSION}" + "User-Agent": "Clerk/#{Clerk::VERSION}; Faraday/#{Faraday::VERSION}; Ruby/#{RUBY_VERSION}", + "X-Clerk-SDK": "ruby/#{Clerk::VERSION}" # TODO: Add framework identifier } # How often (in seconds) should JWKs be refreshed - JWKS_CACHE_LIFETIME = 3600 # 1 hour + JWKS_CACHE_LIFETIME = 3600 # 1 hour / TODO: Move to constants? @@jwks_cache = JWKSCache.new(JWKS_CACHE_LIFETIME) @@ -37,155 +20,57 @@ def self.jwks_cache @@jwks_cache end - def initialize(api_key: nil, base_url: nil, logger: nil, ssl_verify: true, - connection: nil) - if connection - # Inject a Faraday::Connection for testing or full control over Faraday - @conn = connection - return - else - base_url = base_url || Clerk.configuration.base_url - base_uri = if !base_url.end_with?("/") - URI("#{base_url}/") - else - URI(base_url) - end - - api_key ||= Clerk.configuration.api_key - - if Faraday::VERSION.to_i >= 2 && api_key.nil? - api_key = -> { raise ArgumentError, "Clerk secret key is not set" } - end - - logger = logger || Clerk.configuration.logger - @conn = Faraday.new( - url: base_uri, headers: DEFAULT_HEADERS, ssl: {verify: ssl_verify} - ) do |f| - f.request :url_encoded - f.request :authorization, "Bearer", api_key - if logger - f.response :logger, logger do |l| - l.filter(/(Authorization: "Bearer) (\w+)/, '\1 [SECRET]') - end - end - end - end - end - - def request(method, path, query: [], body: nil, timeout: nil) - response = case method - when :get - @conn.get(path, query) do |req| - req.options.timeout = timeout if timeout - end - when :post - @conn.post(path, body) do |req| - req.body = body.to_json - req.headers[:content_type] = "application/json" - req.options.timeout = timeout if timeout - end - when :patch - @conn.patch(path, body) do |req| - req.body = body.to_json - req.headers[:content_type] = "application/json" - req.options.timeout = timeout if timeout - end - when :delete - @conn.delete(path) do |req| - req.options.timeout = timeout if timeout - end - end - - body = if response[CONTENT_TYPE_HEADER] == "application/json" - JSON.parse(response.body) - else - response.body - end - - if response.success? - body - else - klass = case body.dig("errors", 0, "code") - when "cookie_invalid", "client_not_found", "resource_not_found" - Errors::Authentication - else - Errors::Fatal - end - raise klass.new(body, status: response.status) - end - end - - def allowlist_identifiers - Resources::AllowlistIdentifiers.new(self) - end - - def allowlist - Resources::Allowlist.new(self) - end - - def clients - Resources::Clients.new(self) - end - - def email_addresses - Resources::EmailAddresses.new(self) - end - - def emails - Resources::Emails.new(self) - end - - def organizations - Resources::Organizations.new(self) - end - - def phone_numbers - Resources::PhoneNumbers.new(self) - end - - def sessions - Resources::Sessions.new(self) - end - - def testing_tokens - Resources::TestingTokens.new(self) - end - - def users - Resources::Users.new(self) - end - - def jwks - Resources::JWKS.new(self) - end - - # Returns the decoded JWT payload without verifying if the signature is - # valid. + # Returns the decoded JWT payload without verifying if the signature is valid. # - # WARNING: This will not verify whether the signature is valid. You - # should not use this for untrusted messages! You most likely want to use - # verify_token. + # WARNING: This will not verify whether the signature is valid. You should not + # use this for untrusted messages! You most likely want to use `verify_token`. def decode_token(token) JWT.decode(token, nil, false).first end - # Decode the JWT and verify it's valid (verify claims, signature etc.) using - # the provided algorithms. + # Decode the JWT and verify it's valid (verify claims, signature etc.) using the provided algorithms. # - # JWKS are cached for JWKS_CACHE_LIFETIME seconds, in order to avoid - # unecessary roundtrips. In order to invalidate the cache, pass - # `force_refresh_jwks: true`. + # JWKS are cached for JWKS_CACHE_LIFETIME seconds, in order to avoid unecessary roundtrips. + # In order to invalidate the cache, pass `force_refresh_jwks: true`. # - # A timeout for the request to the JWKs endpoint can be set with the - # `timeout` argument. - def verify_token(token, force_refresh_jwks: false, algorithms: ['RS256'], timeout: 5) + # A timeout for the request to the JWKs endpoint can be set with the `timeout` argument. + def verify_token(token, force_refresh_jwks: false, algorithms: ["RS256"], timeout: 5) jwk_loader = ->(options) do # JWT.decode requires that the 'keys' key in the Hash is a symbol (as # opposed to a string which our SDK returns by default) - { keys: SDK.jwks_cache.fetch(self, kid_not_found: (options[:invalidate] || options[:kid_not_found]), force_refresh: force_refresh_jwks) } + {keys: SDK.jwks_cache.fetch(self, kid_not_found: options[:invalidate] || options[:kid_not_found], force_refresh: force_refresh_jwks)} end JWT.decode(token, nil, true, algorithms: algorithms, exp_leeway: timeout, jwks: jwk_loader).first end + + private + + # TODO: Temporary solution until generators are improved + HTTP_CLIENT_CUSTOM_MAPPING = { + allowlist: "AllowListBlockList", + blocklist: "AllowListBlockList", + email_sms_templates: "EmailSMSTemplates", + oauth_applications: "OAuthApplications", + jwt_templates: "JWTTemplates", + redirect_urls: "RedirectURLs", + saml_connections: "SAMLConnections" + } + + def generate_const_name(method_name) + "#{HTTP_CLIENT_CUSTOM_MAPPING[method_name] || Utils.camel_case(method_name)}Api" + end + + def respond_to_missing?(method_name, include_private = false) + ClerkHttpClient.const_get(generate_const_name(method_name)).respond_to?(:new) + rescue NameError + false + end + + def method_missing(method_name, *arguments) + ClerkHttpClient.const_get(generate_const_name(method_name)).new + rescue NameError + raise NoMethodError, "undefined method `#{method_name}` for #{self.class.name}" + end end end diff --git a/lib/clerk/sinatra.rb b/lib/clerk/sinatra.rb new file mode 100644 index 0000000..ae69f4c --- /dev/null +++ b/lib/clerk/sinatra.rb @@ -0,0 +1,52 @@ +require "sinatra/base" +require "clerk/rack" + +module Sinatra + module Clerk + module Helpers + def clerk + env["clerk"] + end + + def require_reverification!(preset = ::Clerk::StepUp::Preset::STRICT, &block) + clerk.user_require_reverification!(preset) do + return yield(preset) if block_given? + render_reverification!(preset) + end + end + + def render_reverification!(preset = nil) + halt 403, ::Clerk::StepUp::Reverification.error_payload(preset).to_json + end + + def clerk_sdk + @@sdk ||= ::Clerk::SDK.new + end + end + + def self.registered(app) + app.helpers Clerk::Helpers + app.use ::Clerk::Rack::Middleware + + app.set(:auth) do |active| + condition do + redirect clerk.sign_in_url if active && !clerk.session + end + end + + app.set(:reverify) do |preset| + condition do + if preset === true + preset = ::Clerk::StepUp::Preset::STRICT + end + + if preset + require_reverification!(preset) + end + end + end + end + end + + register Clerk +end diff --git a/lib/clerk/utils.rb b/lib/clerk/utils.rb index 63633fa..99c1a50 100644 --- a/lib/clerk/utils.rb +++ b/lib/clerk/utils.rb @@ -1,11 +1,57 @@ +# frozen_string_literal: true + +require "base64" + module Clerk module Utils - module_function - def camelize(term) - string = term.to_s - string = string.sub(/^[a-z\d]*/) { match.capitalize } - string.gsub!(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" } - string + class << self + def camel_case(str) + str = str.to_s + return str if str !~ /_/ && str =~ /[A-Z]+.*/ + str.split("_").map { |s| s.capitalize }.join + end + + def decode_publishable_key(publishable_key) + Base64.decode64(publishable_key.split("_")[2].to_s) + end + + def filter_routes(routes) + filtered_routes = {} + filtered_wildcard_routes = [] + + routes.each do |route| + route = route.strip + + if route.end_with?("/*") + filtered_wildcard_routes << route[0..-2] + else + filtered_routes[route] = true + end + end + + filtered_wildcard_routes.uniq! + + [filtered_routes, filtered_wildcard_routes] + end + + def retrieve_from_query_string(url, key) + ::Rack::Utils.parse_query(url.query)[key] + end + + def valid_publishable_key?(publishable_key) + raise ArgumentError, "publishable_key must be a string" unless publishable_key.is_a?(String) + + key = publishable_key.to_s + valid_publishable_key_prefix?(key) && valid_publishable_key_postfix?(key) + end + + def valid_publishable_key_postfix?(publishable_key) + decode_publishable_key(publishable_key).end_with?("$") + end + + def valid_publishable_key_prefix?(publishable_key) + publishable_key.start_with?("pk_live_", "pk_test_") + end end end end diff --git a/lib/clerk/version.rb b/lib/clerk/version.rb index 169e5a8..577d3a2 100644 --- a/lib/clerk/version.rb +++ b/lib/clerk/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Clerk - VERSION = "4.0.0.beta3" + VERSION = "4.0.0.beta4" end diff --git a/spec/clerk/authenticatable_spec.rb b/spec/clerk/authenticatable_spec.rb new file mode 100644 index 0000000..48f2f86 --- /dev/null +++ b/spec/clerk/authenticatable_spec.rb @@ -0,0 +1,87 @@ +# frozen_string_literal: true + +require "spec_helper" +require "clerk/authenticatable" + +RSpec.describe Clerk::Authenticatable do + let(:klass) do + Class.new do + include Clerk::Authenticatable + + attr_reader :request + + def initialize(request) + @request = request + end + + def render(options = {}) + @render_options = options + end + + attr_reader :render_options + end + end + + let(:clerk_client) { instance_double("ClerkClient") } + let(:request) { double("Request", env: {"clerk" => clerk_client}) } + let(:controller) { klass.new(request) } + + describe "#clerk" do + it "returns the clerk client from request.env" do + expect(controller.send(:clerk)).to eq(clerk_client) + end + end + + describe "#require_reverification!" do + let(:preset) { Clerk::StepUp::Preset::STRICT } + + context "when block is given" do + it "yields to the block when reverification is required" do + expect(clerk_client).to receive(:user_require_reverification!).with(preset).and_yield + + block_called = false + controller.send(:require_reverification!, preset) { block_called = true } + + expect(block_called).to be true + end + end + + context "when no block is given" do + it "renders reverification error" do + expect(clerk_client).to receive(:user_require_reverification!).with(preset).and_yield + + controller.send(:require_reverification!, preset) + + expect(controller.render_options).to eq({ + status: 403, + json: Clerk::StepUp::Reverification.error_payload(preset) + }) + end + end + end + + describe "#render_reverification!" do + let(:preset) { Clerk::StepUp::Preset::STRICT } + let(:error_payload) { Clerk::StepUp::Reverification.error_payload(preset) } + + before do + allow(Clerk::StepUp::Reverification).to receive(:error_payload).with(preset).and_return(error_payload) + end + + it "renders error payload with 403 status" do + controller.send(:render_reverification!, preset) + + expect(controller.render_options).to eq({ + status: 403, + json: error_payload + }) + end + end + + describe "helper_method registration" do + it "registers clerk helper methods" do + expect(klass.class).to receive(:helper_method).with(:clerk, :require_reverification!, :render_reverification!) + klass.class.send(:include, described_class) + end + end +end diff --git a/spec/clerk/authenticate_context_spec.rb b/spec/clerk/authenticate_context_spec.rb new file mode 100644 index 0000000..b04b6bb --- /dev/null +++ b/spec/clerk/authenticate_context_spec.rb @@ -0,0 +1,375 @@ +# frozen_string_literal: true + +require "spec_helper" +require "clerk/authenticate_context" + +RSpec.describe Clerk::AuthenticateContext do + let(:cookies) { {} } + let(:env) { {} } + let(:host) { "example.com" } + let(:port) { 443 } + let(:url) { "https://example.com/path" } + + let(:request) do + double( + cookies: cookies, + env: env, + host: host, + port: port, + url: url + ) + end + + let(:publishable_key) { "pk_test_key123" } + let(:secret_key) { "sk_test_key123" } + + let(:config) do + double( + publishable_key: publishable_key, + secret_key: secret_key + ) + end + + subject(:context) { described_class.new(request, config) } + + describe "#initialize" do + it "creates a new context with empty cookies and headers" do + expect(context.session_token_in_cookie).to be_nil + expect(context.session_token_in_header).to be_empty + end + end + + describe "key validations" do + context "when secret key is missing" do + let(:secret_key) { "" } + + it "raises ConfigurationError" do + expect { context.secret_key }.to raise_error(Clerk::ConfigurationError, "Clerk secret key is not set") + end + end + + context "when publishable key is missing" do + let(:publishable_key) { "" } + + it "raises ConfigurationError" do + expect { context.publishable_key }.to raise_error(Clerk::ConfigurationError, "Clerk publishable key is not set") + end + end + end + + describe "#publishable_key" do + context "when publishable key is present" do + it "returns the publishable key" do + expect(context.publishable_key).to eq("pk_test_key123") + end + end + + context "when publishable key is missing" do + let(:publishable_key) { nil } + + it "raises ConfigurationError" do + expect { context.publishable_key }.to raise_error(Clerk::ConfigurationError, "Clerk publishable key is not set") + end + end + end + + describe "#development_instance?" do + it "returns true for test secret key" do + expect(context.development_instance?).to be true + end + + context "with live secret key" do + let(:secret_key) { "sk_live_key123" } + + it "returns false" do + expect(context.development_instance?).to be false + end + end + end + + describe "#production_instance?" do + it "returns false for test secret key" do + expect(context.production_instance?).to be false + end + + context "with live secret key" do + let(:secret_key) { "sk_live_key123" } + + it "returns true" do + expect(context.production_instance?).to be true + end + end + end + + describe "#cross_origin_request?" do + context "when origin matches host" do + let(:env) { {Clerk::ORIGIN_HEADER => "https://example.com"} } + + it "returns false" do + expect(context.cross_origin_request?).to be false + end + end + + context "when origin differs from host" do + let(:env) { {Clerk::ORIGIN_HEADER => "https://different.com"} } + + it "returns true" do + expect(context.cross_origin_request?).to be true + end + end + end + + describe "#active_client?" do + context "when client_uat is positive" do + let(:cookies) { {Clerk::CLIENT_UAT_COOKIE => "1"} } + + it "returns true" do + expect(context.active_client?).to be true + end + end + + context "when client_uat is zero or missing" do + it "returns false" do + expect(context.active_client?).to be false + end + end + end + + describe "#accepts_html?" do + context "when accept header includes text/html" do + let(:env) { {Clerk::ACCEPT_HEADER => "text/html,application/xhtml+xml"} } + + it "returns true" do + expect(context.accepts_html?).to be true + end + end + + context "when accept header doesn't include text/html" do + let(:env) { {Clerk::ACCEPT_HEADER => "application/json"} } + + it "returns false" do + expect(context.accepts_html?).to be false + end + end + end + + describe "#dev_browser" do + context "when the #{Clerk::DEV_BROWSER_COOKIE} cookie is present" do + let(:cookies) { {Clerk::DEV_BROWSER_COOKIE => "foo"} } + + it "returns the dev_browser cookie value" do + expect(context.dev_browser).to eq("foo") + end + end + + context "when the #{Clerk::DEV_BROWSER_COOKIE} query param is present" do + let(:url) { "https://example.com/path?#{Clerk::DEV_BROWSER_COOKIE}=foo" } + + it "returns the dev_browser query param value" do + expect(context.dev_browser).to eq("foo") + end + end + + context "when the #{Clerk::DEV_BROWSER_COOKIE} cookie is not present" do + it "returns an empty string" do + expect(context.dev_browser).to eq("") + end + end + end + + describe "#dev_browser?" do + context "when the #dev_browser is present" do + it "returns true" do + allow(context).to receive(:dev_browser).and_return("foo") + expect(context.dev_browser?).to be true + end + end + + context "when the #dev_browser is not present" do + it "returns false" do + allow(context).to receive(:dev_browser).and_return("") + expect(context.dev_browser?).to be false + end + end + end + + describe "#handshake_token" do + context "when the handshake token is present in the query string" do + let(:url) { "https://example.com/path?#{Clerk::HANDSHAKE_COOKIE}=foo" } + + it "returns the handshake token as a string" do + expect(context.handshake_token).to eq("foo") + end + end + + context "when the handshake token is present in the cookies" do + let(:cookies) { {Clerk::HANDSHAKE_COOKIE => "bar"} } + + it "returns the handshake token as a string" do + expect(context.handshake_token).to eq("bar") + end + end + + context "when the handshake token is not present in the query string or cookies" do + it "returns an empty string" do + expect(context.handshake_token).to eq("") + end + end + end + + describe "#handshake_token?" do + context "when the handshake token is present" do + it "returns true" do + allow(context).to receive(:handshake_token).and_return("foo") + expect(context.handshake_token?).to be true + end + end + + context "when the handshake token is empty" do + it "returns true" do + allow(context).to receive(:handshake_token).and_return("") + expect(context.handshake_token?).to be false + end + end + + context "when the handshake token is not present" do + it "returns false" do + allow(context).to receive(:handshake_token).and_return(nil) + expect(context.handshake_token?).to be false + end + end + end + + describe "#session_token_in_cookie?" do + context "when session token is present in cookies" do + let(:cookies) { {Clerk::SESSION_COOKIE => "foo"} } + + it "returns true" do + expect(context.session_token_in_cookie?).to be true + end + end + + context "when session token is not present in cookies" do + it "returns false" do + expect(context.session_token_in_cookie?).to be false + end + end + end + + describe "#session_token_in_header?" do + context "when session token is present in headers" do + let(:env) { {Clerk::AUTHORIZATION_HEADER => "Bearer foo"} } + + it "returns true" do + expect(context.session_token_in_header?).to be true + end + end + + context "when session token is not present in headers" do + it "returns false" do + expect(context.session_token_in_header?).to be false + end + end + end + + describe "#document_request?" do + context "when #{Clerk::SEC_FETCH_DEST_HEADER} is document" do + let(:env) { {Clerk::SEC_FETCH_DEST_HEADER => "document"} } + + it "returns true" do + expect(context.document_request?).to be true + end + end + + context "when #{Clerk::SEC_FETCH_DEST_HEADER} is not document" do + it "returns false" do + expect(context.document_request?).to be false + end + end + end + + describe "#dev_browser_in_url" do + context "when #{Clerk::DEV_BROWSER_COOKIE} is present in url" do + let(:url) { "https://example.com/path?#{Clerk::DEV_BROWSER_COOKIE}=bar" } + + it "returns value" do + expect(context.dev_browser_in_url).to eq("bar") + end + end + + context "when #{Clerk::DEV_BROWSER_COOKIE} is not present in url" do + it "returns nil" do + expect(context.dev_browser_in_url).to be_nil + end + end + end + + describe "#dev_browser_in_url?" do + context "when #{Clerk::DEV_BROWSER_COOKIE} is present in url" do + let(:url) { "https://example.com/path?#{Clerk::DEV_BROWSER_COOKIE}=bar" } + + it "returns true" do + expect(context.dev_browser_in_url?).to be true + end + end + + context "when #{Clerk::DEV_BROWSER_COOKIE} is not present in url" do + it "returns false" do + expect(context.dev_browser_in_url?).to be false + end + end + end + + describe "#frontend_api" do + context "when publishable key is not valid" do + before do + allow(Clerk::Utils).to receive(:valid_publishable_key?).and_return(false) + end + + it "returns an empty string" do + expect(context.frontend_api).to eq("") + end + end + + context "when the publishable key is valid" do + before do + allow(Clerk::Utils).to receive(:valid_publishable_key?).and_return(true) + end + + context "when proxy_url is present" do + it "returns the proxy_url" do + allow(context).to receive(:proxy_url).and_return("https://proxy.example.com") + expect(context.frontend_api).to eq("https://proxy.example.com") + end + end + + context "when development instance and domain is present" do + it "returns the `clerk.*` frontend api" do + allow(context).to receive(:development_instance?).and_return(true) + allow(context).to receive(:domain).and_return("example.com") + + expect(context.frontend_api).to eq("clerk.example.com") + end + end + + context "when production instance" do + it "returns the frontend api from the publishable key" do + allow(context).to receive(:development_instance?).and_return(false) + allow(context).to receive(:publishable_key).and_return("pk_live_Y2xlcmsuY2xlcmstcnVieS1zZGsuZGV2JA") + + expect(context.frontend_api).to eq("clerk.clerk-ruby-sdk.dev") + end + end + end + end + + # describe "#eligible_for_multi_domain?" do + # context "when the #{Clerk::DEV_BROWSER_COOKIE} cookie is present" do + # let(:cookies) { {Clerk::DEV_BROWSER_COOKIE => "foo"} } + + # it "returns true" do + # expect(context.eligible_for_multi_domain?).to be true + # end + # end + # end +end diff --git a/spec/clerk/authenticate_request_spec.rb b/spec/clerk/authenticate_request_spec.rb new file mode 100644 index 0000000..f7297d8 --- /dev/null +++ b/spec/clerk/authenticate_request_spec.rb @@ -0,0 +1,608 @@ +# frozen_string_literal: true + +require "spec_helper" +require "clerk/authenticate_context" +require "clerk/authenticate_request" + +RSpec.describe Clerk::AuthenticateRequest do + let(:session_token_in_header) { nil } + let(:session_token_in_cookie) { nil } + let(:auth_context) do + instance_double( + Clerk::AuthenticateContext, + session_token_in_header: session_token_in_header, + session_token_in_cookie: session_token_in_cookie + ) + end + let(:sdk) { instance_double(Clerk::SDK) } + let(:env) { {} } + let(:instance) { described_class.new(auth_context) } + + before do + allow(Clerk::SDK).to receive(:new).and_return(sdk) + end + + describe "#initialize" do + it "initializes with an auth_context" do + expect(instance.auth_context).to eq(auth_context) + end + end + + describe "#resolve" do + context "when using header token based authentication" do + it "should resolve the header token" do + allow(auth_context).to receive(:session_token_in_header?).and_return(true) + expect(instance).to receive(:resolve_header_token).with(env) + + instance.resolve(env) + end + end + + context "when using cookie token based authentication" do + it "should resolve the cookie token" do + allow(auth_context).to receive(:session_token_in_header?).and_return(false) + expect(instance).to receive(:resolve_cookie_token).with(env) + + instance.resolve(env) + end + end + end + + describe "#resolve_header_token" do + before { allow(sdk).to receive(:decode_token).and_return(true) } + after { instance.send(:resolve_header_token, env) } + + context "signed in" do + context "valid token" do + let(:claims) { {"sub" => "user_123"} } + let(:session_token_in_header) { "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" } + + context "has claims" do + it "should return signed in" do + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_header).and_return(claims) + expect(instance).to receive(:signed_in).with(env, claims, auth_context.session_token_in_header) + end + end + + context "no claims" do + it "should return signed out" do + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_header).and_return(nil) + expect(instance).to receive(:signed_out).with(enforce_auth: true) + end + end + end + end + + context "signed out" do + context "malformed token" do + let(:session_token_in_header) { "invalid_token" } + + it "should return signed out with #{Clerk::TokenVerificationErrorReason::TOKEN_INVALID}" do + expect(sdk).to receive(:decode_token).with(auth_context.session_token_in_header).and_return(false) + expect(instance).to receive(:signed_out).with(reason: Clerk::TokenVerificationErrorReason::TOKEN_INVALID) + end + end + + context "expired token" do + let(:session_token_in_header) { "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTYyMjkwMjJ9.dWa-WdWJPb1x16REqjSQVLX9Po8DiJNHGr7NhCW62kk" } + + it "should return signed out with `#{Clerk::TokenVerificationErrorReason::TOKEN_EXPIRED}`" do + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_header).and_raise(JWT::ExpiredSignature) + expect(instance).to receive(:signed_out).with(enforce_auth: true, reason: Clerk::TokenVerificationErrorReason::TOKEN_EXPIRED) + end + end + + context "token not active yet" do + let(:session_token_in_header) { "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0Ijo1NTE2MjM5MDIyfQ.KA4waP1mBe_P6kS9inaGZTxOLNV64KQOMQSTkpVYRF8" } + + it "should return signed out with `#{Clerk::TokenVerificationErrorReason::TOKEN_NOT_ACTIVE_YET}`" do + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_header).and_raise(JWT::InvalidIatError) + expect(instance).to receive(:signed_out).with(enforce_auth: true, reason: Clerk::TokenVerificationErrorReason::TOKEN_NOT_ACTIVE_YET) + end + end + + context "decoding error" do + let(:session_token_in_header) { "invalid_token" } + + it "should return signed out with `#{Clerk::TokenVerificationErrorReason::TOKEN_INVALID}`" do + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_header).and_raise(JWT::DecodeError) + expect(instance).to receive(:signed_out).with(reason: Clerk::TokenVerificationErrorReason::TOKEN_INVALID) + end + end + end + end + + describe "#resolve_cookie_token" do + context "cross origin request" do + it "should return signed out" do + allow(auth_context).to receive(:cross_origin_request?).and_return(true) + expect(instance).to receive(:signed_out) + instance.send(:resolve_cookie_token, env) + end + end + + context "handshake token present" do + let(:auth_context) do + instance_double( + Clerk::AuthenticateContext, + cross_origin_request?: false, + handshake_token?: true + ) + end + + it "should attempt to resolve the handshake token" do + expect(instance).to receive(:resolve_handshake).with(env) + instance.send(:resolve_cookie_token, env) + end + end + + context "development instance" do + let(:auth_context) do + instance_double( + Clerk::AuthenticateContext, + cross_origin_request?: false, + development_instance?: true, + dev_browser_in_url?: true, + dev_browser?: false, + handshake_token?: false + ) + end + + it "should handle the handshake maybe status (dev browser in url)" do + expect(instance).to receive(:handle_handshake_maybe_status).with(env, reason: Clerk::AuthErrorReason::DEV_BROWSER_SYNC) + instance.send(:resolve_cookie_token, env) + end + + it "should handle the handshake maybe status (dev browser)" do + allow(auth_context).to receive(:dev_browser_in_url?).and_return(false) + expect(instance).to receive(:handle_handshake_maybe_status).with(env, reason: Clerk::AuthErrorReason::DEV_BROWSER_MISSING) + instance.send(:resolve_cookie_token, env) + end + end + + context "active/inactive clients" do + let(:auth_context) do + instance_double( + Clerk::AuthenticateContext, + active_client?: false, + cross_origin_request?: false, + development_instance?: true, + dev_browser_in_url?: false, + dev_browser?: true, + handshake_token?: false + ) + end + + it "should return signed out if inactive client and session token is missing" do + allow(auth_context).to receive(:session_token_in_cookie?).and_return(false) + + expect(instance).to receive(:signed_out).with(reason: Clerk::AuthErrorReason::SESSION_TOKEN_AND_UAT_MISSING) + instance.send(:resolve_cookie_token, env) + end + + it "should handle the handshake maybe status if inactive client and session token is present" do + allow(auth_context).to receive(:session_token_in_cookie?).and_return(true) + + expect(instance).to receive(:handle_handshake_maybe_status).with(env, reason: Clerk::AuthErrorReason::SESSION_TOKEN_WITHOUT_CLIENT_UAT) + instance.send(:resolve_cookie_token, env) + end + + it "should handle the handshake maybe status if active client and session token is missing" do + allow(auth_context).to receive(:active_client?).and_return(true) + allow(auth_context).to receive(:session_token_in_cookie?).and_return(false) + + expect(instance).to receive(:handle_handshake_maybe_status).with(env, reason: Clerk::AuthErrorReason::CLIENT_UAT_WITHOUT_SESSION_TOKEN) + instance.send(:resolve_cookie_token, env) + end + end + + context "active client & session token is present" do + let(:auth_context) do + instance_double( + Clerk::AuthenticateContext, + active_client?: true, + client_uat: 1733967555, + cross_origin_request?: false, + development_instance?: true, + dev_browser_in_url?: false, + dev_browser?: true, + handshake_token?: false, + session_token_in_cookie: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", + session_token_in_cookie?: true + ) + end + + it "should return signed out if token could not be verified" do + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_cookie).and_return(false) + expect(instance).to receive(:signed_out) + + instance.send(:resolve_cookie_token, env) + end + + it "should handle the handshake maybe status if token iat is less than client uat" do + claims = {"sub" => "user_123", "iat" => 1733967554} + + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_cookie).and_return(claims) + expect(instance).to receive(:handle_handshake_maybe_status).with(env, reason: Clerk::AuthErrorReason::SESSION_TOKEN_OUTDATED) + + instance.send(:resolve_cookie_token, env) + end + + it "should return signed in" do + claims = {"sub" => "user_123", "iat" => 1733967556} + + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_cookie).and_return(claims) + expect(instance).to receive(:signed_in).with(env, claims, auth_context.session_token_in_cookie) + + instance.send(:resolve_cookie_token, env) + end + + context "verification error" do + it "should run handshake for expired tokens" do + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_cookie).and_raise(JWT::ExpiredSignature) + expect(instance).to receive(:handshake).with(env, reason: Clerk::TokenVerificationErrorReason::TOKEN_EXPIRED) + + instance.send(:resolve_cookie_token, env) + end + + it "should run handshake for inactive tokens" do + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_cookie).and_raise(JWT::InvalidIatError) + expect(instance).to receive(:handshake).with(env, reason: Clerk::TokenVerificationErrorReason::TOKEN_NOT_ACTIVE_YET) + + instance.send(:resolve_cookie_token, env) + end + + it "should run handshake for inactive tokens" do + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_cookie).and_raise(JWT::InvalidIatError) + expect(instance).to receive(:handshake).with(env, reason: Clerk::TokenVerificationErrorReason::TOKEN_NOT_ACTIVE_YET) + + instance.send(:resolve_cookie_token, env) + end + + it "should return signed out for malformed tokens" do + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_cookie).and_raise(JWT::DecodeError) + expect(instance).to receive(:signed_out).with(reason: Clerk::TokenVerificationErrorReason::TOKEN_INVALID) + instance.send(:resolve_cookie_token, env) + end + + it "should return signed out if token is invalid in any other way" do + expect(instance).to receive(:verify_token).with(auth_context.session_token_in_cookie).and_raise + expect(instance).to receive(:signed_out) + + instance.send(:resolve_cookie_token, env) + end + end + end + end + + describe "#handle_handshake_maybe_status" do + it "should return signed out if not eligible for handshake" do + expect(instance).to receive(:eligible_for_handshake?).and_return(false) + expect(instance).to receive(:signed_out) + expect(instance).to_not receive(:handshake) + + instance.send(:handle_handshake_maybe_status, env) + end + + it "should return handshake if eligible for handshake" do + expect(instance).to receive(:eligible_for_handshake?).and_return(true) + expect(instance).to_not receive(:signed_out) + expect(instance).to receive(:handshake).with(env) + + instance.send(:handle_handshake_maybe_status, env) + end + + it "should pass through options" do + opts = {reason: "reason", message: "message", status: "status"} + + expect(instance).to receive(:eligible_for_handshake?).and_return(true) + expect(instance).to_not receive(:signed_out) + expect(instance).to receive(:handshake).with(env, **opts) + + instance.send(:handle_handshake_maybe_status, env, **opts) + end + end + + describe "#handshake" do + it "should return a redirect response" do + expect(instance).to receive(:redirect_to_handshake).and_return("https://example.com") + + status, headers = instance.send(:handshake, env, reason: "reason", message: "message", status: "status") + expect(status).to eq 307 + expect(headers).to eq( + Clerk::LOCATION_HEADER => "https://example.com", + Clerk::AUTH_REASON_HEADER => "reason", + Clerk::AUTH_MESSAGE_HEADER => "message", + Clerk::AUTH_STATUS_HEADER => "status" + ) + end + end + + describe "#signed_out" do + context "when `enforce_auth` is true" do + it "should return 401" do + status, headers = instance.send(:signed_out, reason: "reason", message: "message", status: "status", enforce_auth: true) + + expect(status).to eq(401) + expect(headers).to eq({ + Clerk::AUTH_REASON_HEADER => "reason", + Clerk::AUTH_MESSAGE_HEADER => "message", + Clerk::AUTH_STATUS_HEADER => "status" + }) + end + end + + context "when `enforce_auth` is false" do + it "should return nil status" do + status, headers = instance.send(:signed_out, reason: "reason", message: "message", status: "status") + + expect(status).to be_nil + expect(headers).to eq({ + Clerk::AUTH_REASON_HEADER => "reason", + Clerk::AUTH_MESSAGE_HEADER => "message", + Clerk::AUTH_STATUS_HEADER => "status" + }) + end + end + + context "debug auth headers" do + it "should return debug auth headers" do + status, headers = instance.send(:signed_out, reason: "reason", message: "message", status: "status") + + expect(status).to be_nil + expect(headers).to eq({ + Clerk::AUTH_REASON_HEADER => "reason", + Clerk::AUTH_MESSAGE_HEADER => "message", + Clerk::AUTH_STATUS_HEADER => "status" + }) + end + + it "should merge existing headers" do + input_headers = {"foo" => "bar"} + status, headers = instance.send(:signed_out, reason: "reason", message: "message", status: "status", headers: input_headers) + + expect(status).to be_nil + expect(headers).to eq({ + Clerk::AUTH_REASON_HEADER => "reason", + Clerk::AUTH_MESSAGE_HEADER => "message", + Clerk::AUTH_STATUS_HEADER => "status", + "foo" => "bar" + }) + end + end + end + + describe "#signed_in" do + let(:claims) { {"sub" => "user_123"} } + let(:token) { "valid_token" } + + it "should set the clerk env" do + _, headers = instance.send(:signed_in, env, claims, token) + + expect(headers).to eq({}) + + expect(env["clerk"]).to be_a(Clerk::Proxy) + expect(env["clerk"].session_claims).to eq(claims) + expect(env["clerk"].session_token).to eq(token) + end + + it "should pass through headers" do + input_headers = {"foo" => "bar"} + + _, headers = instance.send(:signed_in, env, claims, token, **input_headers) + + expect(headers).to eq(input_headers) + end + end + + describe "#eligible_for_handshake?" do + it "should be true if it's a document request" do + allow(auth_context).to receive(:document_request?).and_return(true) + expect(instance.send(:eligible_for_handshake?)).to be true + end + + it "should be true if it's not a document request and accepts html" do + allow(auth_context).to receive(:document_request?).twice.and_return(false) + allow(auth_context).to receive(:accepts_html?).and_return(true) + expect(instance.send(:eligible_for_handshake?)).to be true + end + + it "should be false if it's not a document request and does not accept html" do + allow(auth_context).to receive(:document_request?).twice.and_return(false) + allow(auth_context).to receive(:accepts_html?).and_return(false) + expect(instance.send(:eligible_for_handshake?)).to be false + end + end + + describe "#verify_token" do + it "should be truthy if the token is valid" do + output = {"sub" => "user_123"} + expect(sdk).to receive(:verify_token).and_return(output) + expect(instance.send(:verify_token, "valid_token")).to eq output + end + + it "should return false if the token is nil" do + expect(sdk).to_not receive(:verify_token) + expect(instance.send(:verify_token, nil)).to be false + end + + it "should return false if the token is empty" do + expect(sdk).to_not receive(:verify_token) + expect(instance.send(:verify_token, "")).to be false + end + + it "should return false if the token has a decoding error" do + expect(sdk).to receive(:verify_token).and_raise(JWT::DecodeError) + expect(instance.send(:verify_token, "invalid_token")).to be false + end + + it "should return false if the token has a required dependency error" do + expect(sdk).to receive(:verify_token).and_raise(JWT::RequiredDependencyError) + expect(instance.send(:verify_token, "invalid_token")).to be false + end + + it "should re-raise the error if the token is expired" do + expect(sdk).to receive(:verify_token).and_raise(JWT::ExpiredSignature) + expect { instance.send(:verify_token, "invalid_token") }.to raise_error(JWT::ExpiredSignature) + end + + it "should re-raise the error if the token is invalid" do + expect(sdk).to receive(:verify_token).and_raise(JWT::InvalidIatError) + expect { instance.send(:verify_token, "invalid_token") }.to raise_error(JWT::InvalidIatError) + end + end + + describe "#verify_token_with_retry" do + let(:token) { "valid_token" } + let(:claims) { {"sub" => "user_123"} } + + it "should return signed_in if the token is valid" do + expect(instance).to receive(:verify_token).with(token).and_return(claims) + expect(instance).to receive(:signed_in).with(env, claims, token).and_return("stubbed") + expect(instance.send(:verify_token_with_retry, env, token)).to eq "stubbed" + end + + context "production instance" do + before { expect(auth_context).to receive(:development_instance?).and_return(false) } + + it "should re-raise the error if the initial verification fails" do + expect(instance).to receive(:verify_token).and_raise(JWT::InvalidIatError) + expect { instance.send(:verify_token_with_retry, env, token) }.to raise_error(JWT::InvalidIatError) + end + end + + context "development instance" do + before { expect(auth_context).to receive(:development_instance?).and_return(true) } + + it "should retry the token verification" do + expect(instance).to receive(:verify_token).and_raise(JWT::InvalidIatError) + expect(instance).to receive(:verify_token).with(token, {timeout: 86_400}).and_return(claims) + expect(instance).to receive(:signed_in).with(env, claims, token).and_return("stubbed") + + expect(instance.send(:verify_token_with_retry, env, token)).to eq "stubbed" + end + + it "should retry the token verification and raise an error if it fails" do + expect(instance).to receive(:verify_token).and_raise(JWT::InvalidIatError) + expect(instance).to receive(:verify_token).with(token, {timeout: 86_400}).and_raise(JWT::InvalidIatError) + expect(instance).to_not receive(:signed_in) + + expect { instance.send(:verify_token_with_retry, env, token) }.to raise_error(JWT::InvalidIatError) + end + end + end + + describe "#remove_from_query_string" do + it "should remove the key from the query string" do + url = URI("http://example.com?foo=bar&baz=qux") + result = instance.send(:remove_from_query_string, url, "foo") + expect(url.query).to eq("baz=qux") + expect(result).to eq("baz=qux") + end + end + + describe "#debug_auth_headers" do + it "should format the headers" do + result = instance.send(:debug_auth_headers, reason: "reason", message: "message", status: "status") + + expect(result).to eq({ + Clerk::AUTH_REASON_HEADER => "reason", + Clerk::AUTH_MESSAGE_HEADER => "message", + Clerk::AUTH_STATUS_HEADER => "status" + }) + end + + it "should remove nil values from the headers" do + result = instance.send(:debug_auth_headers, reason: "reason") + expect(result).to eq({Clerk::AUTH_REASON_HEADER => "reason"}) + end + end + + describe "#redirect_to_handshake" do + before do + allow(auth_context).to receive(:clerk_url).and_return(URI.parse("http://localhost:3000?#{Clerk::DEV_BROWSER_COOKIE}=foobar")) + allow(auth_context).to receive(:frontend_api).and_return("clerk.foobar.dev") + allow(auth_context).to receive(:development_instance?).and_return(true) + end + + it "should return the handshake url" do + allow(auth_context).to receive(:dev_browser?).and_return(false) + expect(instance.send(:redirect_to_handshake)).to eq("https://clerk.foobar.dev/v1/client/handshake?redirect_url=http%3A%2F%2Flocalhost%3A3000%3F") + end + + it "should return the handshake url" do + allow(auth_context).to receive(:dev_browser?).and_return(true) + allow(auth_context).to receive(:dev_browser).and_return("DVB_TOKEN") + expect(instance.send(:redirect_to_handshake)).to eq("https://clerk.foobar.dev/v1/client/handshake?redirect_url=http%3A%2F%2Flocalhost%3A3000%3F&__clerk_db_jwt=DVB_TOKEN") + end + end + + describe "#resolve_handshake" do + context "failed handshake token verification" do + it "should return signed out" do + allow(auth_context).to receive(:handshake_token).and_return("") + + expect(instance).to receive(:verify_token).with(auth_context.handshake_token).and_return(false) + expect(instance).to receive(:signed_out).and_call_original + + status, headers = instance.send(:resolve_handshake, env) + + expect(status).to eq(401) + expect(headers).to eq({Clerk::AUTH_REASON_HEADER => Clerk::TokenVerificationErrorReason::JWK_FAILED_TO_RESOLVE}) + end + end + + context "sucessful handshake token verification" do + let(:cookie_directives) { [] } + + before do + allow(auth_context).to receive(:handshake_token).and_return("valid_token") + allow(instance).to receive(:verify_token).with(auth_context.handshake_token).and_return(false) + allow(instance).to receive(:signed_out).and_call_original + + expect(instance).to receive(:verify_token).with(auth_context.handshake_token).and_return({ + Clerk::HANDSHAKE_COOKIE_DIRECTIVES_KEY => cookie_directives + }) + + allow(auth_context).to receive(:development_instance?).and_return(true) + allow(auth_context).to receive(:clerk_url).and_return(URI.parse("http://localhost:3000/admin?#{Clerk::HANDSHAKE_COOKIE}=foobar")) + end + + context "without session token" do + let(:cookie_directives) do + [ + "__client_uat=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax", + "__client_uat=1733967555; Path=/; Domain=127.0.0.1; Max-Age=315360000; SameSite=Lax", + "__clerk_db_jwt=dvb_2p2djNDxepFC8K98VArq3efkHWw; Path=/; Expires=Fri, 12 Dec 2025 01:39:48 GMT; SameSite=Lax" + ] + end + + it "should set as signed out" do + expect(instance).to_not receive(:verify_token_with_retry) + + status, headers = instance.send(:resolve_handshake, env) + + expect(status).to be_nil + expect(headers).to eq({ + "Access-Control-Allow-Credentials" => "true", + "Access-Control-Allow-Origin" => "null", + Clerk::LOCATION_HEADER => "http://localhost:3000/admin?", + Clerk::SET_COOKIE_HEADER => cookie_directives, + Clerk::AUTH_REASON_HEADER => Clerk::AuthErrorReason::SESSION_TOKEN_MISSING + }) + end + end + + context "with session token" do + let(:cookie_directives) { ["__session=VALID_SESSION_TOKEN; Path=/; Expires=Fri, 12 Dec 2025 01:39:48 GMT; SameSite=Lax"] } + + it "should attempt to verify the session token" do + expect(instance).to_not receive(:signed_out) + expect(instance).to receive(:verify_token_with_retry) + + instance.send(:resolve_handshake, env) + end + end + end + end +end diff --git a/spec/clerk/configuration_spec.rb b/spec/clerk/configuration_spec.rb new file mode 100644 index 0000000..a5a64f3 --- /dev/null +++ b/spec/clerk/configuration_spec.rb @@ -0,0 +1,182 @@ +# frozen_string_literal: true + +require "spec_helper" + +RSpec.describe Clerk::Configuration do + let(:valid_pk) { "pk_test_key" } + let(:valid_sk) { "sk_test_key" } + + describe "#initialize" do + it "initializes with default values" do + with_modified_env(CLERK_PUBLISHABLE_KEY: valid_pk, CLERK_SECRET_KEY: valid_sk) do + config = described_class.new + + expect(config.excluded_routes).to eq([]) + expect(config.publishable_key).to eq(ENV["CLERK_PUBLISHABLE_KEY"]) + expect(config.secret_key).to eq(ENV["CLERK_SECRET_KEY"]) + expect(config.cache_store).to be_nil + end + end + + it "initializes ClerkHttpClient with the secret key" do + with_modified_env(CLERK_SECRET_KEY: valid_sk) do + described_class.new + expect(ClerkHttpClient::Configuration.default.access_token).to eq(ENV["CLERK_SECRET_KEY"]) + end + end + + context "cache store defaults" do + context "when ::Rails is defined" do + before do + stub_const("Rails", Class.new) + allow(Rails).to receive(:cache) + end + + it "uses Rails.cache as the default cache store" do + expect(described_class.new.cache_store).to eq(Rails.cache) + end + end + + context "when ::ActiveSupport::Cache::MemoryStore is defined" do + before do + stub_const("ActiveSupport::Cache::MemoryStore", Class.new) + end + + it "uses ActiveSupport::Cache::MemoryStore as the default cache store" do + expect(described_class.new.cache_store).to be_an_instance_of(ActiveSupport::Cache::MemoryStore) + end + end + + context "when neither is defined" do + it "returns nil" do + expect(described_class.new.cache_store).to be_nil + end + end + end + end + + describe "#update" do + it "updates multiple configuration options" do + config = described_class.new + options = { + publishable_key: valid_pk, + secret_key: valid_sk, + excluded_routes: ["/health"] + } + + config.update(options) + + expect(config.publishable_key).to eq(valid_pk) + expect(config.secret_key).to eq(valid_sk) + expect(config.excluded_routes).to eq(["/health"]) + end + end + + describe "#cache_store=" do + let(:valid_cache) { double("cache_store", fetch: nil) } + + it "accepts a valid cache store" do + config = described_class.new + config.cache_store = valid_cache + expect(config.cache_store).to eq(valid_cache) + end + + it "allows setting to nil" do + config = described_class.new + config.cache_store = nil + expect(config.cache_store).to be_nil + end + + it "raises error when cache store doesn't respond to fetch" do + config = described_class.new + invalid_cache = double("invalid_cache") + + expect { config.cache_store = invalid_cache } + .to raise_error(ArgumentError, "cache_store must respond to :fetch") + end + end + + describe "#excluded_routes=" do + it "accepts an array of strings" do + config = described_class.new + routes = ["/health", "/status"] + + config.excluded_routes = routes + expect(config.excluded_routes).to eq(routes) + end + + it "raises error when input is not an array" do + config = described_class.new + + expect { config.excluded_routes = "not_an_array" } + .to raise_error(ArgumentError, "excluded_routes must be an array") + end + + it "raises error when array contains non-string elements" do + config = described_class.new + + expect { config.excluded_routes = ["/health", 123] } + .to raise_error(ArgumentError, "All elements in the excluded_routes array must be strings") + end + end + + describe "#publishable_key=" do + it "accepts a valid publishable key" do + config = described_class.new + config.publishable_key = valid_pk + expect(config.publishable_key).to eq(valid_pk) + end + + it "raises error when key doesn't start with 'pk_'" do + config = described_class.new + + expect { config.publishable_key = "invalid_key" } + .to raise_error(ArgumentError, "publishable_key must start with 'pk_'") + end + end + + describe "#secret_key=" do + it "accepts a valid secret key" do + config = described_class.new + config.secret_key = valid_sk + expect(config.secret_key).to eq(valid_sk) + end + + it "raises error when key doesn't start with 'sk_'" do + config = described_class.new + + expect { config.secret_key = "invalid_key" } + .to raise_error(ArgumentError, "secret_key must start with 'sk_'") + end + + it "updates ClerkHttpClient configuration" do + config = described_class.new + expect(ClerkHttpClient::Configuration.default) + .to receive(:access_token=) + .with(valid_sk) + + config.secret_key = valid_sk + end + end + + describe "#debug=" do + it "updates debug flag and ClerkHttpClient configuration" do + config = described_class.new + expect(ClerkHttpClient::Configuration.default) + .to receive(:debugging=) + .with(true) + + config.debug = true + expect(config.debug).to be true + end + end + + describe ".default" do + it "returns the same instance on multiple calls" do + instance1 = described_class.default + instance2 = described_class.default + + expect(instance1).to be(instance2) + end + end +end diff --git a/spec/clerk/error_spec.rb b/spec/clerk/error_spec.rb new file mode 100644 index 0000000..e793164 --- /dev/null +++ b/spec/clerk/error_spec.rb @@ -0,0 +1,36 @@ +require "spec_helper" + +RSpec.describe Clerk::Error do + describe "#initialize" do + let(:error_msg) { {"errors" => ["Invalid token"]} } + let(:status) { 401 } + + subject(:error) { described_class.new(error_msg, status: status) } + + it "sets the status" do + expect(error.status).to eq(status) + end + + it "includes status in the error message" do + expect(error.message).to include("status=>401") + end + end +end + +RSpec.describe Clerk::AuthenticationError do + it "inherits from Clerk::Error" do + expect(described_class.superclass).to eq(Clerk::Error) + end +end + +RSpec.describe Clerk::ConfigurationError do + it "inherits from StandardError" do + expect(described_class.superclass).to eq(StandardError) + end +end + +RSpec.describe Clerk::FatalError do + it "inherits from Clerk::Error" do + expect(described_class.superclass).to eq(Clerk::Error) + end +end diff --git a/spec/clerk/jwks_cache_spec.rb b/spec/clerk/jwks_cache_spec.rb new file mode 100644 index 0000000..1579253 --- /dev/null +++ b/spec/clerk/jwks_cache_spec.rb @@ -0,0 +1,66 @@ +require "spec_helper" + +RSpec.describe Clerk::JWKSCache do + let(:lifetime) { 3600 } # 1 hour cache lifetime + let(:cache) { described_class.new(lifetime) } + let(:sdk) { Clerk::SDK.new } + let(:jwks_api) { instance_double("ClerkHttpClient::JWKSApi") } + let(:mock_keys) { [double(to_hash: {kid: "key1"}), double(to_hash: {kid: "key2"})] } + let(:expected_result) { mock_keys.map(&:to_hash) } + + before do + allow(sdk).to receive(:jwks).and_return(jwks_api) + allow(jwks_api).to receive(:get).and_return(double(keys: mock_keys)) + end + + describe "#fetch" do + it "fetches and caches JWKS on first call" do + result = cache.fetch(sdk) + expect(result).to eq(expected_result) + end + + it "returns cached result on subsequent calls within lifetime" do + first_result = cache.fetch(sdk) + expect(jwks_api).to have_received(:get).once + + second_result = cache.fetch(sdk) + expect(second_result).to eq(first_result) + expect(jwks_api).to have_received(:get).once + end + + it "refreshes cache when force_refresh is true" do + cache.fetch(sdk) + expect(jwks_api).to have_received(:get).once + + cache.fetch(sdk, force_refresh: true) + expect(jwks_api).to have_received(:get).twice + end + + it "refreshes cache when lifetime has expired" do + cache.fetch(sdk) + expect(jwks_api).to have_received(:get).once + + allow(Time).to receive(:now).and_return(Time.now + lifetime + 1) + + cache.fetch(sdk) + expect(jwks_api).to have_received(:get).twice + end + + it "refreshes cache when kid_not_found is true and last update was over 5 minutes ago" do + cache.fetch(sdk) + expect(jwks_api).to have_received(:get).once + + allow(Time).to receive(:now).and_return(Time.now + 301) # 5 minutes + 1 second + + cache.fetch(sdk, kid_not_found: true) + expect(jwks_api).to have_received(:get).twice + end + + it "returns nil when API call fails" do + allow(jwks_api).to receive(:get).and_raise(ClerkHttpClient::ApiError) + + result = cache.fetch(sdk) + expect(result).to be_nil + end + end +end diff --git a/spec/clerk/proxy_spec.rb b/spec/clerk/proxy_spec.rb new file mode 100644 index 0000000..9e253a4 --- /dev/null +++ b/spec/clerk/proxy_spec.rb @@ -0,0 +1,184 @@ +require "spec_helper" + +RSpec.describe Clerk::Proxy do + let(:user_id) { "user_123" } + let(:org_id) { "org_456" } + let(:session_claims) do + { + "sub" => user_id, + "org_id" => org_id, + "org_role" => "admin", + "org_permissions" => ["read", "write"], + "fva" => [10, 5] + } + end + let(:session_token) { "test_token" } + let(:proxy) { described_class.new(session_claims: session_claims, session_token: session_token) } + let(:sdk_double) { instance_double(Clerk::SDK) } + + before do + allow(Clerk::SDK).to receive(:new).and_return(sdk_double) + end + + describe "#user?" do + it "returns true when session_claims exists" do + expect(proxy.user?).to be true + end + + it "returns false when session_claims is nil" do + proxy = described_class.new + expect(proxy.user?).to be false + end + end + + describe "#user" do + let(:user_object) { double("User") } + + before do + allow(sdk_double).to receive_message_chain(:users, :find).with(user_id).and_return(user_object) + end + + it "returns nil when not authenticated" do + proxy = described_class.new + expect(proxy.user).to be_nil + end + + it "fetches and returns user when authenticated" do + expect(proxy.user).to eq(user_object) + end + + context "with caching" do + let(:cache_store) { double("CacheStore") } + + before do + allow(Clerk.configuration).to receive(:cache_store).and_return(cache_store) + end + + it "uses cache when available" do + expect(cache_store).to receive(:fetch).with( + "clerk:user:#{user_id}", + expires_in: described_class::CACHE_TTL + ).and_return(user_object) + + expect(proxy.user).to eq(user_object) + end + end + end + + describe "#organization?" do + it "returns true when org_id exists" do + expect(proxy.organization?).to be true + end + + it "returns false when org_id is nil" do + proxy = described_class.new(session_claims: {"sub" => user_id}) + expect(proxy.organization?).to be false + end + end + + describe "#organization" do + let(:org_object) { double("Organization") } + + before do + allow(sdk_double).to receive_message_chain(:organizations, :find).with(org_id).and_return(org_object) + end + + it "returns nil when no organization" do + proxy = described_class.new + expect(proxy.organization).to be_nil + end + + it "fetches and returns organization when present" do + expect(proxy.organization).to eq(org_object) + end + end + + describe "#organization_role" do + it "returns nil when no session_claims" do + proxy = described_class.new + expect(proxy.organization_role).to be_nil + end + + it "fetches and returns organization role when present" do + expect(proxy.organization_role).to eq(session_claims["org_role"]) + end + end + + describe "#organization_permissions" do + it "returns nil when no session_claims" do + proxy = described_class.new + expect(proxy.organization_permissions).to be_nil + end + + it "fetches and returns organization permissions when present" do + expect(proxy.organization_permissions).to eq(session_claims["org_permissions"]) + end + end + + describe "#user_reverified?" do + context "with first factor verification" do + it "returns true when first factor is valid" do + params = {level: :first_factor, after_minutes: 15} + expect(proxy.user_reverified?(params)).to be true + end + + it "returns false when first factor is invalid" do + params = {level: :first_factor, after_minutes: 5} + expect(proxy.user_reverified?(params)).to be false + end + end + + context "with second factor verification" do + it "returns true when second factor is valid" do + params = {level: :second_factor, after_minutes: 10} + expect(proxy.user_reverified?(params)).to be true + end + + it "returns false when second factor is invalid" do + params = {level: :second_factor, after_minutes: 3} + expect(proxy.user_reverified?(params)).to be false + end + end + + context "with multi factor verification" do + it "returns true when both factors are valid" do + params = {level: :multi_factor, after_minutes: 15} + expect(proxy.user_reverified?(params)).to be true + end + + it "returns false when either factor is invalid" do + params = {level: :multi_factor, after_minutes: 7} + expect(proxy.user_reverified?(params)).to be false + end + end + end + + describe "#user_require_reverification!" do + let(:preset) { {level: :first_factor, after_minutes: 5} } + + it "yields block when reverification is needed" do + expect { |b| proxy.user_require_reverification!(preset, &b) }.to yield_with_args(preset) + end + + it "doesn't yield when reverification is not needed" do + allow(proxy).to receive(:user_needs_reverification?).and_return(false) + expect { |b| proxy.user_require_reverification!(preset, &b) }.not_to yield_control + end + end + + describe "#user_reverification_rack_response" do + it "returns a rack response array" do + config = {some: "config"} + response = proxy.user_reverification_rack_response(config) + + expect(response).to be_an(Array) + expect(response[0]).to eq(403) + expect(response[1]).to include("Content-Type" => "application/json") + expect(response[2]).to be_an(Array) + end + + it "raises ArgumentError when config is missing" do + expect { proxy.user_reverification_rack_response(nil) }.to raise_error(ArgumentError) + end + end +end diff --git a/spec/clerk/rack_middleware_spec.rb b/spec/clerk/rack_middleware_spec.rb new file mode 100644 index 0000000..ef8cd19 --- /dev/null +++ b/spec/clerk/rack_middleware_spec.rb @@ -0,0 +1,256 @@ +require "spec_helper" +require "rack/test" +require "clerk/rack_middleware" + +RSpec.describe Clerk::Rack::Middleware do + include Rack::Test::Methods + + let(:env) { Rack::MockRequest.env_for } + let(:output) { [200, {}, "OK"] } + let(:app) { ->(env) { output } } + + let(:auth_request_double) { instance_double(Clerk::AuthenticateRequest) } + let(:auth_context_double) { instance_double(Clerk::AuthenticateContext) } + + subject { described_class.new(app) } + + describe "#initialize" do + it "processes excluded routes correctly" do + skipped_middleware = described_class.new(app, {excluded_routes: ["/health", "/api/*", "/status"]}) + + expect(skipped_middleware.instance_variable_get(:@excluded_routes)).to eq("/health" => true, "/status" => true) + expect(skipped_middleware.instance_variable_get(:@excluded_routes_wildcards)).to eq(["/api/"]) + end + end + + describe "#call" do + before do + allow(Clerk::AuthenticateContext).to receive(:new).and_return(auth_context_double) + allow(Clerk::AuthenticateRequest).to receive(:new).and_return(auth_request_double) + allow(auth_request_double).to receive(:resolve).and_return([nil, {}, nil]) + end + + it "sets clerk proxy and initialized to true in env" do + expect(subject.call(env)).to eq(output) + expect(env["clerk"]).to be_a(Clerk::Proxy) + expect(env["clerk.initialized"]).to be(true) + end + + context "when route is excluded" do + it "skips authentication for excluded routes" do + env["PATH_INFO"] = "/health" + + expect(subject.call(env)).to eq(output) + expect(Clerk::AuthenticateRequest).not_to receive(:new) + expect(env["clerk"]).to be_nil + expect(env["clerk.excluded_route"]).to be(true) + end + + it "skips authentication for wildcard excluded routes" do + env["PATH_INFO"] = "/api/users" + + expect(subject.call(env)).to eq(output) + expect(Clerk::AuthenticateRequest).not_to receive(:new) + expect(env["clerk"]).to be_nil + expect(env["clerk.excluded_route"]).to be(true) + end + end + + context "when status is present" do + it "should pass-through the response" do + response = [401, {}, "Unauthorized"] + + expect(auth_request_double).to receive(:resolve).and_return(response) + expect(subject.call(env)).to eq(response) + end + end + + context "when status is nil" do + it "should call the app" do + expect(app).to receive(:call).with(env) + subject.call(env) + end + + context "when auth_request_headers are present" do + let(:auth_request_response) { [nil, {Clerk::SET_COOKIE_HEADER => ["session=bar; path=/; expires=Fri, 15 Jan 2024 00:00:00 GMT; httponly; secure"], "Content-Type" => "application/json"}, nil] } + let(:app_response) { [200, {Clerk::SET_COOKIE_HEADER => ["session=foo; path=/; expires=Wed, 13 Jan 2024 00:00:00 GMT; httponly; secure"]}, "OK"] } + + it "should remove the `set-cookie` header to avoid overriding existing cookies set by other middleware" do + allow(auth_request_double).to receive(:resolve).and_return(auth_request_response) + allow(app).to receive(:call).with(env).and_return(app_response) + + expect(subject).to receive(:set_cookie_headers!).with(app_response[1], ["session=bar; path=/; expires=Fri, 15 Jan 2024 00:00:00 GMT; httponly; secure"]).and_call_original + + status, headers, body = subject.call(env) + + expect(status).to eq(200) + expect(headers).to eq({ + "Content-Type" => "application/json", + Clerk::SET_COOKIE_HEADER => [ + "session=foo; path=/; expires=Wed, 13 Jan 2024 00:00:00 GMT; httponly; secure", + "session=bar; path=/; expires=Mon, 15 Jan 2024 00:00:00 GMT; secure; httponly" + ] + }) + expect(body).to eq("OK") + end + end + + context "when auth_request_headers are missing" do + let(:auth_request_response) { [nil, {}, nil] } + let(:app_response) { [200, {Clerk::SET_COOKIE_HEADER => "session=bar; path=/; expires=Wed, 13 Jan 2024 00:00:00 GMT; httponly; secure"}, "OK"] } + + it "returns the authenticated headers" do + allow(auth_request_double).to receive(:resolve).and_return(auth_request_response) + allow(app).to receive(:call).with(env).and_return(app_response) + expect(subject).to_not receive(:set_cookie_headers!) + expect(subject.call(env)).to eq(app_response) + end + end + end + end + + describe "#set_cookie_headers!" do + let(:cookies) do + [ + "session=abc123; Path=/; Expires=Wed, 13 Jan 2024 00:00:00 GMT; HttpOnly; Secure", + "client=xyz789; Path=/; Expires=Fri, 15 Jan 2024 00:00:00 GMT; HttpOnly; Secure" + ] + end + + it "sets cookies in response headers" do + headers = {} + + subject.send(:set_cookie_headers!, headers, cookies) + + expect(headers["set-cookie"]).to include(/session=abc123/) + expect(headers["set-cookie"]).to include(/client=xyz789/) + end + end + + describe "#convert_http_cookie_to_cookie_setter_params" do + let(:cookie) { {"session" => "abc123", "Expires" => "Wed, 13 Jan 2024 00:00:00 GMT", "Path" => "/", "HttpOnly" => true, "Secure" => true} } + let(:cookie_key) { "session" } + let(:result) { subject.send(:convert_http_cookie_to_cookie_setter_params, cookie_key, cookie) } + + it "should convert the cookie key to :value" do + expect(result[:value]).to eq("abc123") + end + + it "should downcase cookie keys" do + expect(result.keys).to all(be_a(Symbol)) + + expect(result).to have_key(:expires) + expect(result).to have_key(:httponly) + expect(result).to have_key(:path) + expect(result).to have_key(:secure) + expect(result).to have_key(:value) + end + + it "should fix issue with cookie expiration expected to be Date type" do + expect(result[:expires]).to be_a(Date) + end + end +end + +RSpec.describe Clerk::Rack::Reverification do + let(:app) { ->(env) { [200, env, "app"] } } + let(:middleware) { described_class.new(app) } + let(:clerk_instance) { instance_double("Clerk::Instance") } + + let(:default_env) do + { + "clerk.initialized" => true, + "clerk" => clerk_instance, + "PATH_INFO" => "/test" + } + end + + describe "#call" do + context "when clerk is not initialized" do + it "raises ConfigurationError" do + env = default_env.merge("clerk.initialized" => false) + + expect { middleware.call(env) }.to raise_error( + Clerk::ConfigurationError, + "`Clerk::Rack::Reverification` must be initialized after `Clerk::Rack::Middleware`" + ) + end + end + + context "when route is excluded" do + it "passes through to the app" do + env = default_env.merge("clerk.excluded_route" => true) + + expect(app).to receive(:call).with(env) + middleware.call(env) + end + end + + context "with route matching" do + let(:middleware) { described_class.new(app, routes: ["/protected/*", "/admin"]) } + + it "checks reverification for matching exact route" do + env = default_env.merge("PATH_INFO" => "/admin") + allow(clerk_instance).to receive(:user_needs_reverification?).and_return(true) + allow(clerk_instance).to receive(:user_reverification_rack_response) + + middleware.call(env) + + expect(clerk_instance).to have_received(:user_needs_reverification?) + end + + it "checks reverification for matching wildcard route" do + env = default_env.merge("PATH_INFO" => "/protected/resource") + allow(clerk_instance).to receive(:user_needs_reverification?).and_return(true) + allow(clerk_instance).to receive(:user_reverification_rack_response) + + middleware.call(env) + + expect(clerk_instance).to have_received(:user_needs_reverification?) + end + + it "skips reverification for non-matching route" do + env = default_env.merge("PATH_INFO" => "/public") + allow(clerk_instance).to receive(:user_needs_reverification?) + + middleware.call(env) + + expect(clerk_instance).not_to have_received(:user_needs_reverification?) + end + end + + context "when reverification is needed" do + let(:reverification_response) { [302, {"Location" => "/reverify"}, []] } + + it "returns reverification response" do + allow(clerk_instance).to receive(:user_needs_reverification?).and_return(true) + allow(clerk_instance).to receive(:user_reverification_rack_response).and_return(reverification_response) + + response = middleware.call(default_env) + + expect(response).to eq(reverification_response) + end + end + + context "when reverification is not needed" do + it "passes through to the app" do + allow(clerk_instance).to receive(:user_needs_reverification?).and_return(false) + + expect(app).to receive(:call).with(default_env) + middleware.call(default_env) + end + end + + context "with custom preset" do + let(:middleware) { described_class.new(app, preset: Clerk::StepUp::Preset::LAX) } + + it "uses the custom preset for reverification check" do + allow(clerk_instance).to receive(:user_needs_reverification?).with(Clerk::StepUp::Preset::LAX).and_return(false) + + middleware.call(default_env) + + expect(clerk_instance).to have_received(:user_needs_reverification?).with(Clerk::StepUp::Preset::LAX) + end + end + end +end diff --git a/spec/clerk/sdk_spec.rb b/spec/clerk/sdk_spec.rb new file mode 100644 index 0000000..d5332b1 --- /dev/null +++ b/spec/clerk/sdk_spec.rb @@ -0,0 +1,155 @@ +require "spec_helper" + +RSpec.describe Clerk::SDK do + let(:secret_key) { OpenSSL::PKey::RSA.new(2048) } + let(:public_key) { secret_key.public_key } + + let(:kid) { "test-key-id" } + let(:sk) { "sk_test_123" } + let(:sub) { "user_123" } + + let(:valid_payload) do + { + sub: sub, + exp: Time.now.to_i + 3600, + iat: Time.now.to_i + } + end + + let(:valid_token) do + JWT.encode(valid_payload, secret_key, "RS256", {kid: kid}) + end + + let(:expired_payload) do + { + sub: sub, + exp: Time.now.to_i - 3600, + iat: Time.now.to_i - 7200 + } + end + + let(:expired_token) do + JWT.encode(expired_payload, secret_key, "RS256", {kid: kid}) + end + + let(:jwk) do + JWT::JWK.new(public_key, kid: kid).export + end + + let(:clerk_client) { described_class.new(sk) } + + describe "#decode_token" do + it "decodes a valid token without verification" do + result = clerk_client.decode_token(valid_token) + expect(result["sub"]).to eq(sub) + end + + it "decodes an expired token without verification" do + result = clerk_client.decode_token(expired_token) + expect(result["sub"]).to eq(sub) + end + + it "raises error for invalid JWT format" do + expect { + clerk_client.decode_token("invalid.token.format") + }.to raise_error(JWT::DecodeError) + end + end + + describe "#verify_token" do + before do + allow(described_class.jwks_cache).to receive(:fetch).and_return([jwk]) + end + + it "verifies and decodes a valid token" do + result = clerk_client.verify_token(valid_token) + expect(result["sub"]).to eq(sub) + end + + it "raises error for expired token" do + expect { + clerk_client.verify_token(expired_token) + }.to raise_error(JWT::ExpiredSignature) + end + + it "raises error for invalid signature" do + different_key = OpenSSL::PKey::RSA.new(2048) + invalid_token = JWT.encode(valid_payload, different_key, "RS256", {kid: kid}) + + expect { + clerk_client.verify_token(invalid_token) + }.to raise_error(JWT::VerificationError) + end + + context "when forcing JWKS refresh" do + it "forces cache refresh when flag is set" do + expect(described_class.jwks_cache).to receive(:fetch).with( + clerk_client, + kid_not_found: nil, + force_refresh: true + ) + + clerk_client.verify_token(valid_token, force_refresh_jwks: true) + end + end + + context "with different algorithms" do + it "accepts specified algorithms" do + result = clerk_client.verify_token(valid_token, algorithms: ["RS256"]) + expect(result["sub"]).to eq(sub) + end + + it "raises error for unaccepted algorithms" do + expect { + clerk_client.verify_token(valid_token, algorithms: ["HS256"]) + }.to raise_error(JWT::IncorrectAlgorithm) + end + end + end + + describe "SDK helpers" do + { + actor_tokens: ClerkHttpClient::ActorTokensApi, + allowlist: ClerkHttpClient::AllowListBlockListApi, + beta_features: ClerkHttpClient::BetaFeaturesApi, + blocklist: ClerkHttpClient::AllowListBlockListApi, + clients: ClerkHttpClient::ClientsApi, + domains: ClerkHttpClient::DomainsApi, + email_addresses: ClerkHttpClient::EmailAddressesApi, + email_sms_templates: ClerkHttpClient::EmailSMSTemplatesApi, + instance_settings: ClerkHttpClient::InstanceSettingsApi, + invitations: ClerkHttpClient::InvitationsApi, + jwks: ClerkHttpClient::JWKSApi, + jwt_templates: ClerkHttpClient::JWTTemplatesApi, + miscellaneous: ClerkHttpClient::MiscellaneousApi, + oauth_applications: ClerkHttpClient::OAuthApplicationsApi, + organization_domain: ClerkHttpClient::OrganizationDomainApi, + organization_domains: ClerkHttpClient::OrganizationDomainsApi, + organization_invitations: ClerkHttpClient::OrganizationInvitationsApi, + organization_memberships: ClerkHttpClient::OrganizationMembershipsApi, + organizations: ClerkHttpClient::OrganizationsApi, + phone_numbers: ClerkHttpClient::PhoneNumbersApi, + proxy_checks: ClerkHttpClient::ProxyChecksApi, + redirect_urls: ClerkHttpClient::RedirectURLsApi, + saml_connections: ClerkHttpClient::SAMLConnectionsApi, + sessions: ClerkHttpClient::SessionsApi, + sign_in_tokens: ClerkHttpClient::SignInTokensApi, + sign_ups: ClerkHttpClient::SignUpsApi, + testing_tokens: ClerkHttpClient::TestingTokensApi, + users: ClerkHttpClient::UsersApi, + webhooks: ClerkHttpClient::WebhooksApi + }.each do |method, instance_class| + it "##{method} returns an instance of #{instance_class}" do + expect(clerk_client.send(:respond_to?, method)).to be true + expect(clerk_client.send(method)).to be_an_instance_of(instance_class) + end + end + + it "should appropriately report on methods that are not implemented" do + expect(clerk_client.respond_to?(:foo)).to be false + expect { + clerk_client.foo + }.to raise_error(NoMethodError, "undefined method `foo` for #{clerk_client.class.name}") + end + end +end diff --git a/spec/clerk/utils_spec.rb b/spec/clerk/utils_spec.rb new file mode 100644 index 0000000..2fe270e --- /dev/null +++ b/spec/clerk/utils_spec.rb @@ -0,0 +1,139 @@ +require "spec_helper" +require "clerk/utils" + +RSpec.describe Clerk::Utils do + describe ".filter_routes" do + it "converts regular routes into a hash with true values" do + routes = ["/api/v1/users", "/api/v1/posts"] + filtered_routes, wildcard_routes = described_class.filter_routes(routes) + + expect(filtered_routes).to eq({ + "/api/v1/users" => true, + "/api/v1/posts" => true + }) + expect(wildcard_routes).to be_empty + end + + it "handles wildcard routes correctly" do + routes = ["/api/v1/*", "/admin/*"] + filtered_routes, wildcard_routes = described_class.filter_routes(routes) + + expect(filtered_routes).to be_empty + expect(wildcard_routes).to eq(["/api/v1/", "/admin/"]) + end + + it "handles mixed regular and wildcard routes" do + routes = ["/api/v1/users", "/api/v1/*", "/admin/dashboard", "/admin/*"] + filtered_routes, wildcard_routes = described_class.filter_routes(routes) + + expect(filtered_routes).to eq({ + "/api/v1/users" => true, + "/admin/dashboard" => true + }) + expect(wildcard_routes).to eq(["/api/v1/", "/admin/"]) + end + + it "removes duplicate wildcard routes" do + routes = ["/api/v1/*", "/api/v1/*", "/admin/*"] + filtered_routes, wildcard_routes = described_class.filter_routes(routes) + + expect(filtered_routes).to be_empty + expect(wildcard_routes).to eq(["/api/v1/", "/admin/"]) + end + + it "handles routes with whitespace" do + routes = [" /api/v1/users ", " /api/v1/* "] + filtered_routes, wildcard_routes = described_class.filter_routes(routes) + + expect(filtered_routes).to eq({ + "/api/v1/users" => true + }) + expect(wildcard_routes).to eq(["/api/v1/"]) + end + end + + describe "#valid_publishable_key?" do + it "returns true for valid live publishable key" do + valid_key = "pk_live_#{Base64.encode64("test$")}" + expect(described_class.valid_publishable_key?(valid_key)).to be true + end + + it "returns true for valid test publishable key" do + valid_key = "pk_test_#{Base64.encode64("test$")}" + expect(described_class.valid_publishable_key?(valid_key)).to be true + end + + it "returns false for invalid prefix" do + invalid_key = "invalid_#{Base64.encode64("test$")}" + expect(described_class.valid_publishable_key?(invalid_key)).to be false + end + + it "returns false for invalid postfix" do + invalid_key = "pk_test_#{Base64.encode64("test")}" + expect(described_class.valid_publishable_key?(invalid_key)).to be false + end + + it "raises ArgumentError when key cannot be converted to string" do + expect { + described_class.valid_publishable_key?(Object.new) + }.to raise_error(ArgumentError, "publishable_key must be a string") + end + end + + describe "#valid_publishable_key_prefix?" do + it "returns true for pk_live_ prefix" do + expect(described_class.valid_publishable_key_prefix?("pk_live_abc")).to be true + end + + it "returns true for pk_test_ prefix" do + expect(described_class.valid_publishable_key_prefix?("pk_test_abc")).to be true + end + + it "returns false for invalid prefix" do + expect(described_class.valid_publishable_key_prefix?("invalid_abc")).to be false + end + end + + describe "#valid_publishable_key_postfix?" do + it "returns true when decoded key ends with $" do + key = "pk_test_#{Base64.encode64("test$")}" + expect(described_class.valid_publishable_key_postfix?(key)).to be true + end + + it "returns false when decoded key does not end with $" do + key = "pk_test_#{Base64.encode64("test")}" + expect(described_class.valid_publishable_key_postfix?(key)).to be false + end + end + + describe "#decode_publishable_key" do + it "correctly decodes the third part of the key" do + encoded = Base64.encode64("test") + key = "pk_test_#{encoded}" + expect(described_class.decode_publishable_key(key)).to eq "test" + end + + it "handles invalid key format gracefully" do + expect(described_class.decode_publishable_key("invalid")).to eq "" + end + end + + describe "#retrieve_from_query_string" do + let(:host) { "http://example.com" } + + it "retrieves value from query string" do + url = URI("#{host}?key=value") + expect(described_class.retrieve_from_query_string(url, "key")).to eq "value" + end + + it "returns nil when key is not present" do + url = URI("#{host}?other=value") + expect(described_class.retrieve_from_query_string(url, "key")).to be_nil + end + + it "handles empty query string" do + url = URI(host) + expect(described_class.retrieve_from_query_string(url, "key")).to be_nil + end + end +end diff --git a/spec/clerk_spec.rb b/spec/clerk_spec.rb new file mode 100644 index 0000000..d42cf17 --- /dev/null +++ b/spec/clerk_spec.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true + +RSpec.describe Clerk do + it "has a version number" do + expect(Clerk::VERSION).not_to be nil + end + + describe ".configure" do + let(:publishable_key) { "pk_test_key" } + + context "when a block is given" do + it "yields the configuration object" do + expect { |b| Clerk.configure(&b) }.to yield_with_args(Clerk::Configuration) + end + + it "allows configuration to be set" do + Clerk.configure do |config| + config.publishable_key = publishable_key + end + + expect(Clerk.configuration.publishable_key).to eq(publishable_key) + end + end + + context "when no block is given" do + it "returns the configuration object" do + expect(Clerk.configure).to be_an_instance_of(Clerk::Configuration) + end + end + end + + describe ".configuration" do + it "returns a Configuration instance" do + expect(Clerk.configuration).to be_an_instance_of(Clerk::Configuration) + end + + it "memoizes the configuration" do + config = Clerk.configuration + expect(Clerk.configuration).to be(config) + end + + it "returns the default configuration initially" do + allow(Clerk::Configuration).to receive(:default).and_return(double("default_config")) + + # Reset the memoized configuration + Clerk.instance_variable_set(:@configuration, nil) + + expect(Clerk::Configuration).to receive(:default) + Clerk.configuration + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..0991ea4 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +require "simplecov" +SimpleCov.start +SimpleCov.add_filter "spec" + +require "clerk" +require "climate_control" + +def with_modified_env(options = {}, &block) + ClimateControl.modify(options, &block) +end + +RSpec.configure do |config| + # Enable flags like --only-failures and --next-failure + config.example_status_persistence_file_path = ".rspec_status" + + # Disable RSpec exposing methods globally on `Module` and `main` + config.disable_monkey_patching! + + # Allow for focused tests + config.filter_run_when_matching :focus + + config.expect_with :rspec do |c| + c.syntax = :expect + end +end diff --git a/test/fixtures/all_allowlist_identifiers.json b/test/fixtures/all_allowlist_identifiers.json deleted file mode 100644 index 24f1e12..0000000 --- a/test/fixtures/all_allowlist_identifiers.json +++ /dev/null @@ -1,9 +0,0 @@ -[ - { - "object": "allowlist_identifier", - "id": "alid_1", - "identifier": "+1655559004", - "created_at": 1620370000, - "updated_at": 1620370000 - } -] diff --git a/test/fixtures/all_clients.json b/test/fixtures/all_clients.json deleted file mode 100644 index 2c1b919..0000000 --- a/test/fixtures/all_clients.json +++ /dev/null @@ -1,14 +0,0 @@ -[ - { - "object": "client", - "id": "client_1", - "session_ids": [ - "sess_1q8u7QQhKOGRitdFGreHB00443j" - ], - "sign_in_attempt_id": null, - "sign_up_attempt_id": null, - "last_active_session_id": "sess_1q8u7QQhKOGRitdFGreHB00443j", - "created_at": 1616473358, - "updated_at": 1616473358 - } -] diff --git a/test/fixtures/all_sessions.json b/test/fixtures/all_sessions.json deleted file mode 100644 index 8a100b0..0000000 --- a/test/fixtures/all_sessions.json +++ /dev/null @@ -1,12 +0,0 @@ -[ - { - "object": "session", - "id": "sess_1", - "client_id": "client_1q8sn8pLHjqTU2g1UheJwJ7YWU6", - "user_id": "user_1n5BS00ns3t21GWIXiPJ0KcSe02", - "status": "active", - "last_active_at": 1616473411, - "expire_at": 1617078211, - "abandon_at": 1619065411 - } -] diff --git a/test/fixtures/all_users.json b/test/fixtures/all_users.json deleted file mode 100644 index 00c8479..0000000 --- a/test/fixtures/all_users.json +++ /dev/null @@ -1,88 +0,0 @@ -[ - { - "id": "user_1skey1AXIL5UvH5B6XdMWawkEsj", - "object": "user", - "username": null, - "first_name": "test", - "last_name": "test", - "gender": "", - "birthday": "", - "profile_image_url": "https://picsum.photos/id/237/400/300", - "primary_email_address_id": "idn_1skew1iRLggWHfguGccJ0JUOKwi", - "primary_phone_number_id": null, - "password_enabled": true, - "two_factor_enabled": false, - "email_addresses": [ - { - "id": "idn_1skew1iRLggWHfguGccJ0JUOKwi", - "object": "email_address", - "email_address": "developer@clerk.dev", - "verification": { - "status": "verified", - "strategy": "email_code", - "attempts": 1, - "expire_at": 1621421849 - }, - "linked_to": [] - } - ], - "phone_numbers": [ - { - "id": "idn_1skf5mpYloqE4DDzTCtQTpJ5k5L", - "object": "phone_number", - "phone_number": "+31600000000", - "reserved_for_second_factor": false, - "verification": { - "status": "verified", - "strategy": "phone_code", - "attempts": 1, - "expire_at": 1621421926 - }, - "linked_to": [] - } - ], - "external_accounts": [], - "public_metadata": {}, - "private_metadata": {}, - "created_at": 1621421265000, - "updated_at": 1621421326000, - "last_sign_in_at": null, - "last_active_at": 1700690400000 - }, - { - "id": "user_1skey1AXIL5UvH5B6XdMWawkEsX", - "object": "user", - "username": null, - "first_name": "test", - "last_name": "test", - "gender": "", - "birthday": "", - "profile_image_url": "https://picsum.photos/id/234/400/300", - "primary_email_address_id": "idn_1skew1iRLggWHfguGccJ0JUOKwJ", - "primary_phone_number_id": null, - "password_enabled": true, - "two_factor_enabled": false, - "email_addresses": [ - { - "id": "idn_1skew1iRLggWHfguGccJ0JUOKwi", - "object": "email_address", - "email_address": "developer2@clerk.dev", - "verification": { - "status": "verified", - "strategy": "email_code", - "attempts": 1, - "expire_at": 1621421849 - }, - "linked_to": [] - } - ], - "phone_numbers": [], - "external_accounts": [], - "public_metadata": {}, - "private_metadata": {}, - "created_at": 1621421265123, - "updated_at": 1621421326678, - "last_sign_in_at": 1701677564411, - "last_active_at": 1701734400000 - } -] diff --git a/test/fixtures/allowlist_identifier_1.json b/test/fixtures/allowlist_identifier_1.json deleted file mode 100644 index 1ce1b58..0000000 --- a/test/fixtures/allowlist_identifier_1.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "object": "allowlist_identifier", - "id": "alid_1sOWqxBnLKkD7Alxv5EymdOKjue", - "identifier": "+1655559004", - "created_at": 1620370000, - "updated_at": 1620370000 -} diff --git a/test/fixtures/allowlist_identifier_1_deleted.json b/test/fixtures/allowlist_identifier_1_deleted.json deleted file mode 100644 index 43b139e..0000000 --- a/test/fixtures/allowlist_identifier_1_deleted.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "alid_1", - "object": "allowlist_identifier", - "deleted": true -} diff --git a/test/fixtures/allowlist_toggle.json b/test/fixtures/allowlist_toggle.json deleted file mode 100644 index 5e19440..0000000 --- a/test/fixtures/allowlist_toggle.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "object": "instance", - "id": "ins_1rWjY3fNHDn5dYHmeJGyFB9ftlh", - "restricted_to_allowlist": true -} diff --git a/test/fixtures/client_1.json b/test/fixtures/client_1.json deleted file mode 100644 index 4223fda..0000000 --- a/test/fixtures/client_1.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "object": "client", - "id": "client_1", - "session_ids": [ - "sess_1q8u7QQhKOGRitdFGreHB00443j" - ], - "sign_in_attempt_id": null, - "sign_up_attempt_id": null, - "last_active_session_id": "sess_1q8u7QQhKOGRitdFGreHB00443j", - "created_at": 1616473358, - "updated_at": 1616473358 -} diff --git a/test/fixtures/email_address_1.json b/test/fixtures/email_address_1.json deleted file mode 100644 index 6dcee61..0000000 --- a/test/fixtures/email_address_1.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "id": "idn_email", - "object": "email_address", - "email_address": "john@doe.com", - "reserved": true, - "linked_to": [] -} diff --git a/test/fixtures/email_address_1_deleted.json b/test/fixtures/email_address_1_deleted.json deleted file mode 100644 index ec8880e..0000000 --- a/test/fixtures/email_address_1_deleted.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "object": "email_address", - "id": "idn_email", - "deleted": true -} diff --git a/test/fixtures/email_address_1_updated.json b/test/fixtures/email_address_1_updated.json deleted file mode 100644 index 3c21399..0000000 --- a/test/fixtures/email_address_1_updated.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "id": "idn_email", - "object": "email_address", - "email_address": "john@doe.com", - "reserved": true, - "verification": { - "status": "verified", - "strategy": "admin", - "attempts": null, - "expire_at": null - }, - "linked_to": [] -} diff --git a/test/fixtures/email_created.json b/test/fixtures/email_created.json deleted file mode 100644 index 639ca40..0000000 --- a/test/fixtures/email_created.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "id": "ema_1", - "object": "email", - "from_email_name": "support", - "to_email_address": "boss@clerk.dev", - "email_address_id": "idn_1n5AVtYAHNQY73d6dY6GVJt8gmD", - "subject": "green test", - "body": "this is a green test", - "status": "queued" -} diff --git a/test/fixtures/jwks.json b/test/fixtures/jwks.json deleted file mode 100644 index 9a79a4d..0000000 --- a/test/fixtures/jwks.json +++ /dev/null @@ -1 +0,0 @@ -{"keys":[{"use":"sig","kty":"RSA","kid":"ins_1v4uxFUhQHMqWyPdlihWSdGkKab","alg":"RS256","n":"7qFa2bcz6DvV893VawGXjvNjVp0S6uJqyL58DYPpRePVO8PxTvrAB_o7EHTCPO9Z3lgZgW-gMFsi4zc6wzv_1dSO6eiQixNo4Z0J9PJOSB5FLnuoDY0U3QwPb81I_J3eNjmt3WEcnHFkN4WlFrqbi_oY0-QKWSWI7R_jIECkTVhZTOpF6C4avDmL_XjP-RUtBnKsQbVzwm8OGOvjNucI9xTJrf3YFpan5P8Ix8R87IRZcYioaXsuWLYrHJamsP6coAbYaI3-xahJ6pWnAo3NT_PudWFq85ULhYHEThcU9sH-7Qbc0nuLB2z0vyUQgE3vXIVImONGFwxdYh9LbMCRhw","e":"AQAB"}]} diff --git a/test/fixtures/jwt_valid.json b/test/fixtures/jwt_valid.json deleted file mode 100644 index 7014264..0000000 --- a/test/fixtures/jwt_valid.json +++ /dev/null @@ -1 +0,0 @@ -eyJhbGciOiJSUzI1NiIsImtpZCI6Imluc18xdjR1eEZVaFFITXFXeVBkbGloV1NkR2tLYWIiLCJ0eXAiOiJKV1QifQ.eyJhdWQiOiJjbGVyayIsImVtYWlsIjoiZm9vQGJhci5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZXhwIjoxNjI3NTU0NzIyLCJmYW1pbHlfbmFtZSI6IkRvZSIsImdpdmVuX25hbWUiOiJKb2huIiwiaWF0IjoxNjI3NTU0NjU3LCJpc3MiOiJodHRwczovL2NsZXJrLmV4YW1wbGUuY29tIiwibmFtZSI6IkpvaG4iLCJwaWN0dXJlIjoiaHR0cHM6Ly9pbWFnZXMuZXhhbXBsZS5jb20vYXZhdGFyLnBuZyIsInN1YiI6InVzZXJfMXZDbXFkQXN5d25XbmhFeWY1MzBxY3pydElpIiwidXBkYXRlZF9hdCI6MTYyNzQ4MTAyM30.FQ-hTl8sJaquKmJPDEegP1_r7-yY4YLZAWTs40RKtaybzqJPll_tmiioxjDGyrUMtjwMls8N-C_WV2BB2XWAubsX2UhZXMz6wnWpVb76OUeoGXhQYH9f64MwvSoMlfTZUqtE5b_6-OBgtzmw8cJHjzxR9D6tjfC89o4e1_MtEV9h6ESy8pSTTF344xi4KjG-9TfPqiwUES5qrd5ho7z3ollu84hB05voEbToqkRFQrHEL-Loft1FlZVG9YTAkc3LOHqF21ofAgSL9ZVr7zxkPsGOfGb2kWyyfX6eFxk_NHvrUIEn9e_zR7mEspniJE4-DfQPOWeKMdYi1fU8BW-Eaw \ No newline at end of file diff --git a/test/fixtures/phone_number_1.json b/test/fixtures/phone_number_1.json deleted file mode 100644 index b0afbdf..0000000 --- a/test/fixtures/phone_number_1.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "id": "idn_phone", - "object": "phone_number", - "phone_number": "+15555555555", - "reserved_for_second_factor": false, - "default_second_factor": false, - "reserved": false, - "linked_to": [], - "backup_codes": null -} diff --git a/test/fixtures/phone_number_1_deleted.json b/test/fixtures/phone_number_1_deleted.json deleted file mode 100644 index 24f1cc6..0000000 --- a/test/fixtures/phone_number_1_deleted.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "object": "phone_number", - "id": "idn_phone", - "deleted": true -} diff --git a/test/fixtures/phone_number_1_updated.json b/test/fixtures/phone_number_1_updated.json deleted file mode 100644 index 58c6248..0000000 --- a/test/fixtures/phone_number_1_updated.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "id": "idn_phone", - "object": "phone_number", - "phone_number": "+15555555555", - "reserved_for_second_factor": false, - "default_second_factor": false, - "reserved": false, - "verification": { - "status": "verified", - "strategy": "admin", - "attempts": null, - "expire_at": null - }, - "linked_to": [], - "backup_codes": null -} diff --git a/test/fixtures/session_1.json b/test/fixtures/session_1.json deleted file mode 100644 index 7ed65d1..0000000 --- a/test/fixtures/session_1.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "object": "session", - "id": "sess_1", - "client_id": "client_1q8sn8pLHjqTU2g1UheJwJ7YWU6", - "user_id": "user_1n5BS00ns3t21GWIXiPJ0KcSe02", - "status": "active", - "last_active_at": 1616473411, - "expire_at": 1617078211, - "abandon_at": 1619065411 -} diff --git a/test/fixtures/testing_token_1.json b/test/fixtures/testing_token_1.json deleted file mode 100644 index ff7e0ac..0000000 --- a/test/fixtures/testing_token_1.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "object": "testing_token", - "token": "1713877310-c_3n2MvPu9PnXcuhBPZNao0LOXqK9A7YrnBn0HmIWyy", - "expires_at": 1713966600 -} diff --git a/test/fixtures/user_1.json b/test/fixtures/user_1.json deleted file mode 100644 index f173406..0000000 --- a/test/fixtures/user_1.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "id": "user_1", - "object": "user", - "username": null, - "first_name": "test", - "last_name": "test", - "gender": "", - "birthday": "", - "profile_image_url": "https://picsum.photos/id/237/400/300", - "primary_email_address_id": "idn_1skew1iRLggWHfguGccJ0JUOKwi", - "primary_phone_number_id": null, - "password_enabled": true, - "two_factor_enabled": false, - "email_addresses": [ - { - "id": "idn_1skew1iRLggWHfguGccJ0JUOKwi", - "object": "email_address", - "email_address": "developer@clerk.dev", - "verification": { - "status": "verified", - "strategy": "email_code", - "attempts": 1, - "expire_at": 1621421849 - }, - "linked_to": [] - } - ], - "phone_numbers": [ - { - "id": "idn_1skf5mpYloqE4DDzTCtQTpJ5k5L", - "object": "phone_number", - "phone_number": "+31600000000", - "reserved_for_second_factor": false, - "verification": { - "status": "verified", - "strategy": "phone_code", - "attempts": 1, - "expire_at": 1621421926 - }, - "linked_to": [] - } - ], - "external_accounts": [], - "public_metadata": {}, - "private_metadata": {}, - "created_at": 1621421265, - "updated_at": 1621421326 -} diff --git a/test/fixtures/user_1_deleted.json b/test/fixtures/user_1_deleted.json deleted file mode 100644 index fc9f224..0000000 --- a/test/fixtures/user_1_deleted.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "user_1", - "object": "user", - "deleted": true -} diff --git a/test/fixtures/user_1_updated.json b/test/fixtures/user_1_updated.json deleted file mode 100644 index e69f277..0000000 --- a/test/fixtures/user_1_updated.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "id": "user_1", - "object": "user", - "username": null, - "first_name": "Mary", - "last_name": "test", - "gender": "", - "birthday": "", - "profile_image_url": "https://picsum.photos/id/237/400/300", - "primary_email_address_id": "idn_1skew1iRLggWHfguGccJ0JUOKwi", - "primary_phone_number_id": null, - "password_enabled": true, - "two_factor_enabled": false, - "email_addresses": [ - { - "id": "idn_1skew1iRLggWHfguGccJ0JUOKwi", - "object": "email_address", - "email_address": "developer@clerk.dev", - "verification": { - "status": "verified", - "strategy": "email_code", - "attempts": 1, - "expire_at": 1621421849 - }, - "linked_to": [] - } - ], - "phone_numbers": [ - { - "id": "idn_1skf5mpYloqE4DDzTCtQTpJ5k5L", - "object": "phone_number", - "phone_number": "+31600000000", - "reserved_for_second_factor": false, - "verification": { - "status": "verified", - "strategy": "phone_code", - "attempts": 1, - "expire_at": 1621421926 - }, - "linked_to": [] - } - ], - "external_accounts": [], - "public_metadata": {}, - "private_metadata": {}, - "created_at": 1621421265, - "updated_at": 1621421326 -} diff --git a/test/fixtures/users_oauth_access_token.json b/test/fixtures/users_oauth_access_token.json deleted file mode 100644 index 7d82b5c..0000000 --- a/test/fixtures/users_oauth_access_token.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "token": "xxxx", - "provider": "hubspot", - "scopes": [ - "oauth", - "contacts" - ] -} diff --git a/test/resources/allowlist_identifiers_test.rb b/test/resources/allowlist_identifiers_test.rb deleted file mode 100644 index 4ce1464..0000000 --- a/test/resources/allowlist_identifiers_test.rb +++ /dev/null @@ -1,29 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" - -class Clerk::Resources::AllowlistIdentifierTest < Minitest::Test - def mock_sdk - faraday = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.get("/allowlist_identifiers") { json_ok("all_allowlist_identifiers") } - stub.post("/allowlist_identifiers") { json_ok("allowlist_identifier_1") } - stub.delete("/allowlist_identifiers/alid_1") { json_ok("allowlist_identifier_1_deleted") } - end - end - - ::Clerk::SDK.new(connection: faraday) - end - - def test_all_allowlist_identifiers - allowlist_identifiers = mock_sdk.allowlist_identifiers.all - assert_equal ["allowlist_identifier"], allowlist_identifiers.map { |h| h.dig("object") } - end - - def test_delete_allowlist_identifier - user = mock_sdk.allowlist_identifiers.delete("alid_1") - assert_equal true, user["deleted"] - assert_equal "allowlist_identifier", user["object"] - assert_equal "alid_1", user["id"] - end -end diff --git a/test/resources/allowlist_test.rb b/test/resources/allowlist_test.rb deleted file mode 100644 index 5d71340..0000000 --- a/test/resources/allowlist_test.rb +++ /dev/null @@ -1,20 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" - -class Clerk::Resources::AllowlistTest < Minitest::Test - def mock_sdk - faraday = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.patch("/beta_features/allowlist") { json_ok("allowlist_toggle") } - end - end - - ::Clerk::SDK.new(connection: faraday) - end - - def test_toggle_allowlist - resp = mock_sdk.allowlist.update({restricted_to_allowlist: true}) - assert_equal true, resp["restricted_to_allowlist"] - end -end diff --git a/test/resources/clients_test.rb b/test/resources/clients_test.rb deleted file mode 100644 index 57c1ae8..0000000 --- a/test/resources/clients_test.rb +++ /dev/null @@ -1,34 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" - -class Clerk::Resources::ClientsTest < Minitest::Test - def mock_sdk - faraday = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.get("/clients") { json_ok("all_clients") } - stub.get("/clients/client_1") { json_ok("client_1") } - stub.post("/clients/verify") { json_ok("client_1") } - end - end - - ::Clerk::SDK.new(connection: faraday) - end - - def test_all_clients - sess = mock_sdk.clients.all - assert_equal ["client"], sess.map { |h| h.dig("object") } - end - - def test_find_client - sess = mock_sdk.clients.find("client_1") - assert_equal "client", sess["object"] - assert_equal "client_1", sess["id"] - end - - def test_verify_client - sess = mock_sdk.clients.verify_token("token_1") - assert_equal "client", sess["object"] - assert_equal "client_1", sess["id"] - end -end diff --git a/test/resources/email_addresses_test.rb b/test/resources/email_addresses_test.rb deleted file mode 100644 index ec6bad5..0000000 --- a/test/resources/email_addresses_test.rb +++ /dev/null @@ -1,53 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" - -class Clerk::Resources::EmailAddressTest < Minitest::Test - - def mock_sdk - faraday = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.get("/email_addresses/idn_email") { json_ok("email_address_1") } - stub.post("/email_addresses") { json_ok("email_address_1") } - stub.patch("/email_addresses/idn_email") { json_ok("email_address_1_updated") } - stub.delete("/email_addresses/idn_email") { json_ok("email_address_1_deleted") } - end - end - - ::Clerk::SDK.new(connection: faraday) - end - - def test_find_email_address - email_address_id = "idn_email" - email_address = mock_sdk.email_addresses.find(email_address_id) - assert_equal "email_address", email_address["object"] - assert_equal email_address_id, email_address["id"] - assert_equal "john@doe.com", email_address["email_address"] - assert_nil email_address["verification"] - end - - def test_create_email_address - email_address = mock_sdk.email_addresses.create(user_id: "user_abcdefg", email_address: "") - assert_equal "email_address", email_address["object"] - assert_equal "john@doe.com", email_address["email_address"] - assert_nil email_address["verification"] - end - - def test_update_email_address - email_address_id = "idn_email" - email_address = mock_sdk.email_addresses.update(email_address_id, verified: true) - assert_equal "email_address", email_address["object"] - assert_equal email_address_id, email_address["id"] - assert_equal "john@doe.com", email_address["email_address"] - refute_nil email_address["verification"] - end - - def test_delete_email_address - email_address_id = "idn_email" - deleted_object = mock_sdk.email_addresses.delete(email_address_id) - assert_equal "email_address", deleted_object["object"] - assert_equal email_address_id, deleted_object["id"] - assert deleted_object["deleted"] - end - -end diff --git a/test/resources/emails_test.rb b/test/resources/emails_test.rb deleted file mode 100644 index 3ba7077..0000000 --- a/test/resources/emails_test.rb +++ /dev/null @@ -1,25 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" - -class Clerk::Resources::EmailsTest < Minitest::Test - def mock_sdk - faraday = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.post("/emails") { json_ok("email_created") } - end - end - - ::Clerk::SDK.new(connection: faraday) - end - - def test_create_email - resp = mock_sdk.emails.create({ - email_address_id: "idn_xxx", - from_email_name: "noreply", - subject: "hi", - body: "hello", - }) - assert_equal "email", resp["object"] - end -end diff --git a/test/resources/phone_numbers_test.rb b/test/resources/phone_numbers_test.rb deleted file mode 100644 index fe5039c..0000000 --- a/test/resources/phone_numbers_test.rb +++ /dev/null @@ -1,53 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" - -class Clerk::Resources::PhoneNumbersTest < Minitest::Test - - def mock_sdk - faraday = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.get("/phone_numbers/idn_phone") { json_ok("phone_number_1") } - stub.post("/phone_numbers") { json_ok("phone_number_1") } - stub.patch("/phone_numbers/idn_phone") { json_ok("phone_number_1_updated") } - stub.delete("/phone_numbers/idn_phone") { json_ok("phone_number_1_deleted") } - end - end - - ::Clerk::SDK.new(connection: faraday) - end - - def test_find_phone_number - phone_number_id = "idn_phone" - phone_number = mock_sdk.phone_numbers.find(phone_number_id) - assert_equal "phone_number", phone_number["object"] - assert_equal phone_number_id, phone_number["id"] - assert_equal "+15555555555", phone_number["phone_number"] - assert_nil phone_number["verification"] - end - - def test_create_phone_number - phone_number = mock_sdk.phone_numbers.create(user_id: "user_abcdefg", phone_number: "+15555555555") - assert_equal "phone_number", phone_number["object"] - assert_equal "+15555555555", phone_number["phone_number"] - assert_nil phone_number["verification"] - end - - def test_update_phone_number - phone_number_id = "idn_phone" - phone_number = mock_sdk.phone_numbers.update(phone_number_id, verified: true) - assert_equal "phone_number", phone_number["object"] - assert_equal phone_number_id, phone_number["id"] - assert_equal "+15555555555", phone_number["phone_number"] - refute_nil phone_number["verification"] - end - - def test_delete_phone_number - phone_number_id = "idn_phone" - deleted_object = mock_sdk.phone_numbers.delete(phone_number_id) - assert_equal "phone_number", deleted_object["object"] - assert_equal phone_number_id, deleted_object["id"] - assert deleted_object["deleted"] - end - -end diff --git a/test/resources/sessions_test.rb b/test/resources/sessions_test.rb deleted file mode 100644 index 6460f98..0000000 --- a/test/resources/sessions_test.rb +++ /dev/null @@ -1,41 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" - -class Clerk::Resources::SessionsTest < Minitest::Test - def mock_sdk - faraday = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.get("/sessions") { json_ok("all_sessions") } - stub.get("/sessions/sess_1") { json_ok("session_1") } - stub.post("/sessions/sess_1/revoke") { json_ok("session_1") } - stub.post("/sessions/sess_1/verify") { json_ok("session_1") } - end - end - - ::Clerk::SDK.new(connection: faraday) - end - - def test_all_sessions - sess = mock_sdk.sessions.all - assert_equal ["session"], sess.map { |h| h.dig("object") } - end - - def test_find_session - sess = mock_sdk.sessions.find("sess_1") - assert_equal "session", sess["object"] - assert_equal "sess_1", sess["id"] - end - - def test_revoke_session - sess = mock_sdk.sessions.revoke("sess_1") - assert_equal "session", sess["object"] - assert_equal "sess_1", sess["id"] - end - - def test_verify_session - sess = mock_sdk.sessions.verify_token("sess_1", "token_1") - assert_equal "session", sess["object"] - assert_equal "sess_1", sess["id"] - end -end diff --git a/test/resources/testing_tokens_test.rb b/test/resources/testing_tokens_test.rb deleted file mode 100644 index e7f241b..0000000 --- a/test/resources/testing_tokens_test.rb +++ /dev/null @@ -1,25 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" - -class Clerk::Resources::TestingTokensTest < Minitest::Test - def mock_sdk - faraday = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.post("/testing_tokens") { json_ok("testing_token_1") } - end - end - - ::Clerk::SDK.new(connection: faraday) - end - - def test_create_testing_token - response = mock_sdk.testing_tokens.create - - assert_equal "testing_token", response["object"] - assert_equal "1713877310-c_3n2MvPu9PnXcuhBPZNao0LOXqK9A7YrnBn0HmIWyy", - response["token"] - assert_equal 1713966600, response["expires_at"] - - end -end diff --git a/test/resources/users_test.rb b/test/resources/users_test.rb deleted file mode 100644 index 7c66a36..0000000 --- a/test/resources/users_test.rb +++ /dev/null @@ -1,63 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" - -class Clerk::Resources::UsersTest < Minitest::Test - def mock_sdk - faraday = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.get("/users") { json_ok("all_users") } - stub.get("/users?limit=10") { json_ok("all_users") } - stub.get("/users/user_1") { json_ok("user_1") } - stub.patch("/users/user_1") { json_ok("user_1_updated") } - stub.delete("/users/user_1") { json_ok("user_1_deleted") } - stub.get("/users/unknown_id") { json_404 } - stub.get("/users/user_1/oauth_access_tokens/hubspot") { json_ok("users_oauth_access_token") } - end - end - - ::Clerk::SDK.new(connection: faraday) - end - - def test_all_users - users = mock_sdk.users.all - assert_equal ["user", "user"], users.map { |h| h.dig("object") } - end - - def test_all_users_query_params - users = mock_sdk.users.all(limit: 1) - assert_equal ["user", "user"], users.map { |h| h.dig("object") } - end - - def test_find_user - user = mock_sdk.users.find("user_1") - assert_equal "user", user["object"] - assert_equal "user_1", user["id"] - end - - def test_update_user - user = mock_sdk.users.update("user_1", {first_name: "Mary"}) - assert_equal "Mary", user["first_name"] - assert_equal "user_1", user["id"] - end - - def test_delete_user - user = mock_sdk.users.delete("user_1") - assert_equal true, user["deleted"] - assert_equal "user", user["object"] - assert_equal "user_1", user["id"] - end - - def test_find_user_404 - assert_raises Clerk::Errors::Fatal do - mock_sdk.users.find("unknown_id") - end - end - - def test_oauth_access_token - response = mock_sdk.users.oauth_access_token("user_1", "hubspot") - assert_equal "xxxx", response["token"] - assert_equal "hubspot", response["provider"] - assert_equal ["oauth", "contacts"], response["scopes"] - end -end diff --git a/test/sdk_test.rb b/test/sdk_test.rb deleted file mode 100644 index 01c8d98..0000000 --- a/test/sdk_test.rb +++ /dev/null @@ -1,137 +0,0 @@ -# frozen_string_literal: true -# -require "test_helper" - -class Clerk::SdkTest < Minitest::Test - TIME_WHEN_JWT_IS_VALID = Time.new(2021, 7, 29, 13, 31, 30, "+03:00") - TIME_WHEN_JWT_HAS_EXPIRED = Time.new(2021, 7, 29, 13, 33, 00, "+03:00") - - def test_sdk_init_without_config - sdk = ::Clerk::SDK.new - assert sdk - end - - def test_application_json_encoding - unparsed_payload = { a: "b", c: ["d"], d: { e: 3 } } - json_payload = '{"a":"b","c":["d"],"d":{"e":3}}' - - conn = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.patch("/users/user_1", json_payload, { "Content-Type" => "application/json" } ) do |env| - parsed = JSON.parse(env.request_body) - parsed["a"] = "b" - parsed["c"] = ["d"] - parsed["d"] = { "e" => 3 } - - json_ok("user_1_updated") - end - end - end - - sdk = ::Clerk::SDK.new(connection: conn) - user = sdk.users.update("user_1", unparsed_payload) - - assert_equal "Mary", user["first_name"] - assert_equal "user_1", user["id"] - end - - def test_no_api_key_raises_on_api_call - sdk = ::Clerk::SDK.new - assert_raises ArgumentError do - sdk.users.find("x") - end - end - - def test_verify_token - conn = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.get("/jwks") { json_ok("jwks") } - end - end - - sdk = ::Clerk::SDK.new(connection: conn) - valid_jwt = json_fixture("jwt_valid") - - Timecop.freeze(TIME_WHEN_JWT_HAS_EXPIRED) do - assert_raises JWT::ExpiredSignature do - sdk.verify_token(valid_jwt) - end - end - - Timecop.freeze(TIME_WHEN_JWT_IS_VALID) do - assert sdk.verify_token(valid_jwt) - - assert_raises JWT::IncorrectAlgorithm do - sdk.verify_token(valid_jwt, algorithms: ["RS512"]) - end - - assert_raises JWT::VerificationError do - malformed_token = json_fixture("jwt_valid")[0..-2] - sdk.verify_token(malformed_token) - end - end - end - - def test_verify_token_jwks_cache - jwks_endpoint_hits = 0 - - conn = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.get("/jwks") do - jwks_endpoint_hits += 1 - json_ok("jwks") - end - end - end - - sdk = ::Clerk::SDK.new(connection: conn) - - Timecop.freeze(TIME_WHEN_JWT_IS_VALID) do - sdk.verify_token(json_fixture("jwt_valid"), force_refresh_jwks: true) - assert_equal 1, jwks_endpoint_hits - - sdk.verify_token(json_fixture("jwt_valid")) - assert_equal 1, jwks_endpoint_hits - - sdk.verify_token(json_fixture("jwt_valid"), force_refresh_jwks: true) - assert_equal 2, jwks_endpoint_hits - - sdk.verify_token(json_fixture("jwt_valid")) - assert_equal 2, jwks_endpoint_hits - end - - # cache expired - Timecop.freeze(TIME_WHEN_JWT_IS_VALID+Clerk::SDK::JWKS_CACHE_LIFETIME+1) do - begin - sdk.verify_token(json_fixture("jwt_valid")) - rescue JWT::ExpiredSignature - # we know the token is going to be expired in this travelled to time - end - - assert_equal 3, jwks_endpoint_hits - end - - # assert that if the server (BAPI) returns an error to the JWKS request - # (i.e. BAPI was down momentarily) and therefore the received token couldn't - # be verified, then we're going to try one more time - jwks_endpoint_hits = 0 - conn = Faraday.new do |faraday| - faraday.adapter :test do |stub| - stub.get("/jwks") do - jwks_endpoint_hits += 1 - jwks_endpoint_hits < 2 ? json_404 : json_ok("jwks") - end - end - end - - sdk = ::Clerk::SDK.new(connection: conn) - Timecop.freeze(TIME_WHEN_JWT_IS_VALID) do - claims = sdk.verify_token(json_fixture("jwt_valid"), force_refresh_jwks: true) - assert_equal 2, jwks_endpoint_hits - assert_equal "foo@bar.com", claims["email"] - - sdk.verify_token(json_fixture("jwt_valid")) - assert_equal 2, jwks_endpoint_hits # cached response - end - end -end diff --git a/test/test_helper.rb b/test/test_helper.rb deleted file mode 100644 index 5fff820..0000000 --- a/test/test_helper.rb +++ /dev/null @@ -1,25 +0,0 @@ -# frozen_string_literal: true - -$LOAD_PATH.unshift File.expand_path("../lib", __dir__) -require "clerk" -require "timecop" - -require "minitest/autorun" - -FIXTURE_BASE = File.expand_path("fixtures", __dir__) - -def json_fixture(file) - File.read(File.join(FIXTURE_BASE, "#{file}.json")) -end - -def json_ok(file) - [200, {"Content-Type" => "application/json"}, json_fixture(file)] -end - -def json_404 - [404, {"Content-Type" => "application/json"}, JSON.dump( - {"errors" => [ - {"message" => "not found"} - ]} - )] -end