From ac4da93aaf5b731c4987a8517ba8b2c1da53b28b Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Sat, 7 Nov 2026 08:38:25 -0500 Subject: [PATCH] Security hardening and OpenID Connect single sign-on MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - SSO via OmniAuth OpenID Connect (Authentik, Keycloak, …): link by stable subject, by verified email, or from the profile; optional auto-create, admin-group sync, and turning password sign-in off - Current password required to change email or password; password changes and resets sign out other sessions; idle sessions expire after 30 days; "sign out everywhere else"; session reset on sign-in - Rate-limit password resets; scope squawk components to the aircraft - Strict Content Security Policy with nonces (inline handlers removed), Permissions-Policy and COOP headers; file links expire after an hour Co-Authored-By: Claude Opus 5.5 --- Gemfile | 4 + Gemfile.lock | 96 ++++++++++++- README.md | 18 ++- app/controllers/admin/users_controller.rb | 1 + app/controllers/concerns/authentication.rb | 13 +- app/controllers/passwords_controller.rb | 10 +- app/controllers/profiles_controller.rb | 19 ++- app/controllers/sessions_controller.rb | 6 +- app/controllers/squawks_controller.rb | 1 + app/controllers/sso_controller.rb | 100 +++++++++++++ app/javascript/application.js | 14 ++ app/models/sso.rb | 45 ++++++ app/views/admin/users/index.html.erb | 2 +- app/views/aircraft_roles/index.html.erb | 4 +- app/views/airport_codes/show.html.erb | 2 +- app/views/events/index.html.erb | 2 +- app/views/profiles/edit.html.erb | 35 ++++- app/views/sessions/new.html.erb | 26 ++-- app/views/shared/_theme_script.html.erb | 2 +- config/application.rb | 9 ++ .../initializers/content_security_policy.rb | 54 ++++--- config/initializers/omniauth.rb | 29 ++++ config/routes.rb | 5 + .../20261107150000_add_sso_uid_to_users.rb | 6 + db/schema.rb | 4 +- test/integration/security_hardening_test.rb | 115 +++++++++++++++ test/integration/sso_test.rb | 133 ++++++++++++++++++ 27 files changed, 708 insertions(+), 47 deletions(-) create mode 100644 app/controllers/sso_controller.rb create mode 100644 app/models/sso.rb create mode 100644 config/initializers/omniauth.rb create mode 100644 db/migrate/20261107150000_add_sso_uid_to_users.rb create mode 100644 test/integration/security_hardening_test.rb create mode 100644 test/integration/sso_test.rb diff --git a/Gemfile b/Gemfile index e1b7c07..1e78e09 100644 --- a/Gemfile +++ b/Gemfile @@ -78,3 +78,7 @@ gem "pdf-reader", "~> 2.16" gem "rubyzip", ">= 2.4", "< 3" # aircraft archives (.sam.zip) gem "anthropic", "~> 2.6" # AI logbook transcription (Claude) gem "commonmarker", "~> 2.10" # Markdown in notes + +gem "omniauth", "~> 2.1" # single sign-on (OpenID Connect) +gem "omniauth_openid_connect", "~> 0.8" +gem "omniauth-rails_csrf_protection", "~> 2.0" diff --git a/Gemfile.lock b/Gemfile.lock index a6f5366..bbbb0a4 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -78,6 +78,7 @@ GEM uri (>= 0.13.1) addressable (2.9.2) public_suffix (>= 2.0.2, < 8.0) + aes_key_wrap (1.1.0) afm (1.0.1) anthropic (2.6.0) base64 (~> 0.1) @@ -85,12 +86,14 @@ GEM opentelemetry-api (>= 1.2.4, < 2) standardwebhooks (~> 1.0) ast (2.4.3) + attr_required (1.0.2) base64 (0.3.0) bcrypt (3.1.22) bcrypt_pbkdf (1.1.2) bcrypt_pbkdf (1.1.2-arm64-darwin) bcrypt_pbkdf (1.1.2-x86_64-darwin) bigdecimal (4.1.3) + bindata (3.0.1) bindex (0.8.1) bootsnap (1.26.1) msgpack (~> 1.5) @@ -138,6 +141,14 @@ GEM erubi (1.13.1) et-orbi (1.4.2) tzinfo + faraday (2.15.1) + faraday-net_http (>= 2.0, < 3.6) + json + logger + faraday-follow_redirects (0.5.0) + faraday (>= 1, < 3) + faraday-net_http (3.5.0) + net-http (~> 0.5) fugit (1.14.0) et-orbi (~> 1.4) raabro (~> 1.4) @@ -145,6 +156,8 @@ GEM activesupport (>= 6.1) hashdiff (1.2.1) hashery (2.1.2) + hashie (5.2.0) + logger htmlentities (4.4.2) i18n (1.15.2) concurrent-ruby (~> 1.0) @@ -159,6 +172,13 @@ GEM rdoc (>= 4.0.0) reline (>= 0.4.2) json (2.21.2) + json-jwt (1.17.2) + activesupport (>= 4.2) + aes_key_wrap + base64 + bindata + faraday (~> 2.0) + faraday-follow_redirects kamal (2.12.0) activesupport (>= 7.0) base64 (~> 0.2) @@ -185,10 +205,13 @@ GEM marcel (1.2.1) matrix (0.4.3) mini_mime (1.1.5) - minitest (6.0.6) + minitest (6.1.0) drb (~> 2.0) - prism (~> 1.5) + prism (>= 1.5, < 3) msgpack (1.8.7) + net-http (0.10.0) + net-protocol (>= 0.3.0) + uri (>= 0.11.1) net-imap (0.6.8) date net-protocol @@ -221,6 +244,29 @@ GEM racc (~> 1.4) nokogiri (1.19.7-x86_64-linux-musl) racc (~> 1.4) + omniauth (2.3.1) + hashie (>= 3.5.2) + logger + rack (>= 2.2.8) + rack-protection (>= 2.2.0) + omniauth-rails_csrf_protection (2.0.1) + actionpack (>= 4.2) + omniauth (~> 2.0) + omniauth_openid_connect (0.8.0) + omniauth (>= 1.9, < 3) + openid_connect (~> 2.2) + openid_connect (2.5.0) + activemodel + attr_required (>= 1.0.0) + faraday (~> 2.0) + faraday-follow_redirects + json-jwt (>= 1.16) + mail + rack-oauth2 (~> 2.2) + swd (~> 2.0) + tzinfo + validate_url + webfinger (~> 2.0) opentelemetry-api (1.8.0) logger ostruct (0.6.3) @@ -247,6 +293,17 @@ GEM raabro (1.5.0) racc (1.8.1) rack (3.2.8) + rack-oauth2 (2.3.0) + activesupport + attr_required + faraday (~> 2.0) + faraday-follow_redirects + json-jwt (>= 1.11.0) + rack (>= 2.1.0) + rack-protection (4.2.1) + base64 (>= 0.1.0) + logger (>= 1.6.0) + rack (>= 3.0.0, < 4) rack-session (2.1.2) base64 (>= 0.1.0) rack (>= 3.0.0) @@ -373,6 +430,11 @@ GEM standardwebhooks (1.0.1) stimulus-rails (1.3.4) railties (>= 6.0.0) + swd (2.0.3) + activesupport (>= 3) + attr_required (>= 0.0.5) + faraday (~> 2.0) + faraday-follow_redirects tailwindcss-rails (4.7.0) railties (>= 7.0.0) tailwindcss-ruby (~> 4.0) @@ -402,10 +464,17 @@ GEM unicode-emoji (4.3.0) uri (1.1.2) useragent (0.16.11) + validate_url (1.0.15) + activemodel (>= 3.0.0) + public_suffix web-console (4.3.0) actionview (>= 8.0.0) bindex (>= 0.4.0) railties (>= 8.0.0) + webfinger (2.1.3) + activesupport + faraday (~> 2.0) + faraday-follow_redirects webmock (3.34.0) addressable (>= 2.8.0) crack (>= 0.3.2) @@ -444,6 +513,9 @@ DEPENDENCIES importmap-rails json (~> 2.10) kamal + omniauth (~> 2.1) + omniauth-rails_csrf_protection (~> 2.0) + omniauth_openid_connect (~> 0.8) pdf-reader (~> 2.16) propshaft puma (>= 5.0) @@ -479,15 +551,18 @@ CHECKSUMS activestorage (8.1.4.1) sha256=0f4e2f114f3584723a80a2c089aacc6170e765a0b2c385c9782e26ed78f05c66 activesupport (8.1.4.1) sha256=16ac4f341ca65c85a1fcdb8ac73f68891aae9e3c4a6f9c3a27daed8b00017ed7 addressable (2.9.2) sha256=9117c7e7d6ee07230e75ce41fb9401ae55354dc654fcd0e862ba41d539e9a610 + aes_key_wrap (1.1.0) sha256=b935f4756b37375895db45669e79dfcdc0f7901e12d4e08974d5540c8e0776a5 afm (1.0.1) sha256=4fc98c6ea9cad60c25ae12bad517513b0d6fdbedc099e25be88bf47977b7d879 anthropic (2.6.0) sha256=0bbc1cf9b71c82dc72b552ccd0d5e253b76a55fd2d80f8ea4666a9d836a492cb ast (2.4.3) sha256=954615157c1d6a382bc27d690d973195e79db7f55e9765ac7c481c60bdb4d383 + attr_required (1.0.2) sha256=f0ebfc56b35e874f4d0ae799066dbc1f81efefe2364ca3803dc9ea6a4de6cb99 base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b bcrypt (3.1.22) sha256=1f0072e88c2d705d94aff7f2c5cb02eb3f1ec4b8368671e19112527489f29032 bcrypt_pbkdf (1.1.2) sha256=c2414c23ce66869b3eb9f643d6a3374d8322dfb5078125c82792304c10b94cf6 bcrypt_pbkdf (1.1.2-arm64-darwin) sha256=afdd6feb6ed5a97b8e44caacb3f2d641b98af78e6a516d4a3520b69af5cf9fea bcrypt_pbkdf (1.1.2-x86_64-darwin) sha256=35f5639d0058e6c2cc2f856f9c0b14080543268d3047abe6bc81c513093caa0e bigdecimal (4.1.3) sha256=61ebe1e5e559bdc3cc6f2c0ee7f427321fc838f59611c294356eb04d6e21cf66 + bindata (3.0.1) sha256=e97a826a12f6e7c5847e983e5826f277d61035317d352ec339b079537f2fa466 bindex (0.8.1) sha256=7b1ecc9dc539ed8bccfc8cb4d2732046227b09d6f37582ff12e50a5047ceb17e bootsnap (1.26.1) sha256=5b5bd90f8f13ea338627c1d56ffbe2ea25e743ac48c2afec1a9bea3a06a264e2 brakeman (8.1.0) sha256=cfa9e5214e4925842f4bc849a64f8a7e6c5d0425fe98eac8d7b7bc60fdc17e07 @@ -516,16 +591,21 @@ CHECKSUMS erb (6.0.7) sha256=c5ca6dc25b0ef974a44dc8f59fe847577122483b1968a38dec305c60bf91ee92 erubi (1.13.1) sha256=a082103b0885dbc5ecf1172fede897f9ebdb745a4b97a5e8dc63953db1ee4ad9 et-orbi (1.4.2) sha256=bb555dae668419cb24caa2a293a170e58be6d4df1e017c51f5030bdc133cd20c + faraday (2.15.1) sha256=8708154deda739c5e86cc42b74960e23e8491fce0eba9e11639a6a34b1ac288f + faraday-follow_redirects (0.5.0) sha256=5cde93c894b30943a5d2b93c2fe9284216a6b756f7af406a1e55f211d97d10ad + faraday-net_http (3.5.0) sha256=2e7094c34e38754ee048cc3df47376f8657005d9375f8473bce1c3b526a22e36 fugit (1.14.0) sha256=e311a9cc85a54bb67649df45060e721282a1e2c8ebad40e41874a3a7d576f37e globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427 hashdiff (1.2.1) sha256=9c079dbc513dfc8833ab59c0c2d8f230fa28499cc5efb4b8dd276cf931457cd1 hashery (2.1.2) sha256=d239cc2310401903f6b79d458c2bbef5bf74c46f3f974ae9c1061fb74a404862 + hashie (5.2.0) sha256=357a22635195c2e3911fbbc3de9a7d528843d1f42ab0aae02171048f16332d72 htmlentities (4.4.2) sha256=bbafbdf69f2eca9262be4efef7e43e6a1de54c95eb600f26984f71d2fe96c5c3 i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5 importmap-rails (2.2.3) sha256=7101be2a4dc97cf1558fb8f573a718404c5f6bcfe94f304bf1f39e444feeb16a io-console (0.9.5) sha256=83dd9bbf4c4680416629245b39cd4212eb5f4d9a4ea91804870c1f6b846414d5 irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3 json (2.21.2) sha256=1f1d3b7cf2b3ba1a69beca0bb6db13d5438b80bff3cd54cdaaa620b9b07c1c6a + json-jwt (1.17.2) sha256=97e37c1c3e22e9e1d74a1c0d77319c5cdc8a636226e5dbb1664b0b34eddcf1c9 kamal (2.12.0) sha256=c51d1ab085e515470f98d0c0f043637122b5ebf76e8b610cb1fbbed0b7f9b8fa language_server-protocol (3.17.0.6) sha256=5ef2c0c138f8267e1bc631d3328347d354f96724b0af22f2c79516120443b7f0 lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87 @@ -535,8 +615,9 @@ CHECKSUMS marcel (1.2.1) sha256=1678e9360e32f9eafa917c80029e2f6d10b2715c66a4b87b6d0da9b9cd1f859f matrix (0.4.3) sha256=a0d5ab7ddcc1973ff690ab361b67f359acbb16958d1dc072b8b956a286564c5b mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef - minitest (6.0.6) sha256=153ea36d1d987a62942382b61075745042a2b3123b1cd48f4c3675af9cc7d6f1 + minitest (6.1.0) sha256=ff373595aa8888631e8a5463986a76b3845346ae6d7fa46e139c1633d418076e msgpack (1.8.7) sha256=dfefec761b5f9047e6e8d95d2c7f8af4b3725d984a01942adc533aa819a2df33 + net-http (0.10.0) sha256=1a2ff6e37a05724973c43f2bf7bf105f59c36a4cd0a7e9b1c021a0a566987c27 net-imap (0.6.8) sha256=eb30bb62227b64a3af6b518b04b2375113d69f68f15de59b0193b07d98acf6d9 net-pop (0.1.2) sha256=848b4e982013c15b2f0382792268763b748cce91c9e91e36b0f27ed26420dff3 net-protocol (0.4.0) sha256=f9f90c8c6f64794a45160bf422177a336db12809de3beeeaa26b88fcd2e8c853 @@ -553,6 +634,10 @@ CHECKSUMS nokogiri (1.19.7-x86_64-darwin) sha256=508e81e8c5f84aaa240dce981bf1c43faae60808726f0ce7024ee92effc5cafe nokogiri (1.19.7-x86_64-linux-gnu) sha256=25865ccb462f714e712fdf8906fde07849cb6704a808e3d629d75baa5af5dd3b nokogiri (1.19.7-x86_64-linux-musl) sha256=464d1f3dfb0d53cf54c0c6a7e23e8e91cf68ec3cafc2b27dc4a7682f2d9bf546 + omniauth (2.3.1) sha256=bb47bfcd5614b00cd89de4b45b0687123d09143dfeb5dbaf1bb57ff190bc2d2e + omniauth-rails_csrf_protection (2.0.1) sha256=c6e3204d7e3925bb537cb52d50fdfc9f05293f1a9d87c5d4ab4ca3a39ba8c32d + omniauth_openid_connect (0.8.0) sha256=1f2f3890386e2a742221cee0d2e903b78d874e6fab9ea3bfa31c1462f4793d25 + openid_connect (2.5.0) sha256=659aff8edce0907798e3f6837e5f27ae2937ae8735216f3e900ab8daa29e39c4 opentelemetry-api (1.8.0) sha256=3af51183daf0f56a164bc1579782245be70a40678566b9a393cbe5af28ea87c6 ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912 parallel (1.28.0) sha256=33e6de1484baf2524792d178b0913fc8eb94c628d6cfe45599ad4458c638c970 @@ -567,6 +652,8 @@ CHECKSUMS raabro (1.5.0) sha256=3f998a7bc84f9c84df3ab580634d2e0a5bda4f0841168d56035f529c9877440a racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f rack (3.2.8) sha256=1fecc85e463ebc7a2a945fff829ffcd549babeb1556384796fad946c28dc4ec7 + rack-oauth2 (2.3.0) sha256=43e02cf73f13886a0a06499603caeec58aeba6eae1fefc4977c9678b7652c632 + rack-protection (4.2.1) sha256=cf6e2842df8c55f5e4d1a4be015e603e19e9bc3a7178bae58949ccbb58558bac rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8 rack-test (2.3.0) sha256=b118d177cc002c572fc1b6fd8d19c9ed5881a36e8d6f689f9e618f9f861241e8 rackup (2.3.1) sha256=6c79c26753778e90983761d677a48937ee3192b3ffef6bc963c0950f94688868 @@ -605,6 +692,7 @@ CHECKSUMS sshkit (1.25.1) sha256=be3f10b9d6eb0b44d5eaba3f7cbe41bc6bb894bce4339688ac20124391455b78 standardwebhooks (1.0.1) sha256=35db391599d9318747e1e75e77b96236b3fc25241b92387c9a8d31bd974f3d7d stimulus-rails (1.3.4) sha256=765676ffa1f33af64ce026d26b48e8ffb2e0b94e0f50e9119e11d6107d67cb06 + swd (2.0.3) sha256=4cdbe2a4246c19f093fce22e967ec3ebdd4657d37673672e621bf0c7eb770655 tailwindcss-rails (4.7.0) sha256=9b09bd677d7cd226fc8ff3f7d2d91c6dc6c3da75dd74dc4cab5f94711f69ba41 tailwindcss-ruby (4.3.3) sha256=ee0a64030749862deb501acab4c4aaf5adbee13865746a33299d46d7b5d0952a tailwindcss-ruby (4.3.3-aarch64-linux-gnu) sha256=c86d6dd3eccc85fe0d792a832b06f2bf3c0a7a83b399308aeb9d8f5725f42a6a @@ -628,7 +716,9 @@ CHECKSUMS unicode-emoji (4.3.0) sha256=11c02fa73290378c066bb0562cd4c87d8e1b706fbbe0059ca12746a4244de8ce uri (1.1.2) sha256=89292e98eabbef6248b0a0ed5e7e398e152f83f17560023a6d94a7f492b169fb useragent (0.16.11) sha256=700e6413ad4bb954bb63547fa098dddf7b0ebe75b40cc6f93b8d54255b173844 + validate_url (1.0.15) sha256=72fe164c0713d63a9970bd6700bea948babbfbdcec392f2342b6704042f57451 web-console (4.3.0) sha256=e13b71301cdfc2093f155b5aa3a622db80b4672d1f2f713119cc7ec7ac6a6da4 + webfinger (2.1.3) sha256=567a52bde77fb38ca6b67e55db755f988766ec4651c1d24916a65aa70540695c webmock (3.34.0) sha256=72eed29dc8c00148d592acaedaaa6b869e2e397de57dfc8602b84aa834f46b33 websocket (1.2.11) sha256=b7e7a74e2410b5e85c25858b26b3322f29161e300935f70a0e0d3c35e0462737 websocket-driver (0.8.2) sha256=97c556b019bf3410b4961002ac501621e9322d3f8a7bc02161a09301cc4c4146 diff --git a/README.md b/README.md index f00e04f..7611bcd 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,22 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai | `SMTP_ADDRESS`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD`, `MAIL_FROM` | Optional. They enable password-reset emails. Without them an admin resets passwords from **Users**. | | `ANTHROPIC_API_KEY` | Optional. Lets Claude transcribe scanned logbook pages into entries (**Logbook → Import scans**). Without it, scans are only uploaded. | | `LOGBOOK_AI_MODEL`, `LOGBOOK_AI_EFFORT` | Optional. The Claude model and effort used for transcription (default `claude-opus-5-5`, `high`). | +| `APP_URL` | Optional public base URL, e.g. `https://aircraft.example.com` (default `https://APP_HOST`). Used for the SSO callback. | +| `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` | Optional. Turn on single sign-on with an OpenID Connect provider (see below). | +| `OIDC_PROVIDER_NAME` | Button label, e.g. `Authentik` (default `SSO`). | +| `OIDC_AUTO_CREATE_USERS` | `true` creates an account for anyone the provider lets in. New accounts start with no aircraft. Default off: an admin adds users first. | +| `OIDC_TRUST_EMAIL` | `true` links existing accounts by email even if the provider doesn't mark it verified. Only use it if users can't edit their own email at the provider. | +| `OIDC_ADMIN_GROUP` | Optional. Members of this provider group become admins and others lose admin, synced at each sign-in. | +| `PASSWORD_LOGIN` | `false` hides email/password sign-in and password resets once SSO works. It's ignored while SSO isn't configured, so you can't lock yourself out. | + +### Single sign-on (Authentik example) + +1. In Authentik, create an **OAuth2/OpenID Provider** (confidential client) with the redirect URI `https://YOUR-HOST/auth/oidc/callback` and the scopes `openid`, `email` and `profile`. Then create an **Application** that uses it. +2. Set `OIDC_ISSUER` to the provider's issuer URL (`https://auth.example.com/application/o//`), plus `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` and `OIDC_PROVIDER_NAME=Authentik`, then restart. +3. The sign-in page now shows **Sign in with Authentik**. The first SSO sign-in links an existing account with the same email if Authentik marks the email verified. Otherwise, sign in with your password and use **Profile → Link Authentik**. +4. Once everyone can sign in with SSO, optionally set `PASSWORD_LOGIN=false`. + +Other OIDC providers (Keycloak, Google, Entra ID…) work the same way. ### Backups @@ -65,7 +81,7 @@ SQLite runs in WAL mode, so a plain file copy taken while the app is running can ```bash mkdir -p backup for db in storage/production*.sqlite3; do sqlite3 "$db" ".backup 'backup/$(basename "$db")'"; done -rsync -a --exclude '*.sqlite3*' storage/ backup/ # uploaded files +rsync -aH --exclude '*.sqlite3*' storage/ backup/ # uploaded files (-H keeps the hard links that store duplicates once) ``` Alternatively, stop the container and copy the volume. diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index 8813fe2..fca96cc 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -30,6 +30,7 @@ class Admin::UsersController < ApplicationController end @user.admin = admin_flag if @user.update(attrs) + @user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password) # new password signs them out redirect_to admin_users_path, notice: "User updated." else render :edit, status: :unprocessable_entity diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb index 3538f48..e9f611f 100644 --- a/app/controllers/concerns/authentication.rb +++ b/app/controllers/concerns/authentication.rb @@ -1,6 +1,9 @@ module Authentication extend ActiveSupport::Concern + # A session unused for this long is signed out. + SESSION_IDLE_TIMEOUT = 30.days + included do before_action :require_authentication helper_method :authenticated? @@ -26,7 +29,15 @@ module Authentication end def find_session_by_cookie - Session.find_by(id: cookies.signed[:session_id]) if cookies.signed[:session_id] + session = Session.find_by(id: cookies.signed[:session_id]) if cookies.signed[:session_id] + return unless session + if session.updated_at < SESSION_IDLE_TIMEOUT.ago + session.destroy + cookies.delete(:session_id) + return + end + session.touch if session.updated_at < 1.hour.ago # last-active time, without a write per request + session end def request_authentication diff --git a/app/controllers/passwords_controller.rb b/app/controllers/passwords_controller.rb index 0c4b4a8..f60a895 100644 --- a/app/controllers/passwords_controller.rb +++ b/app/controllers/passwords_controller.rb @@ -1,6 +1,9 @@ class PasswordsController < ApplicationController allow_unauthenticated_access + before_action :require_password_login before_action :set_user_by_token, only: %i[ edit update ] + rate_limit to: 5, within: 15.minutes, only: :create, with: -> { redirect_to new_session_path, alert: "Try again later." } + rate_limit to: 10, within: 15.minutes, only: :update, with: -> { redirect_to new_session_path, alert: "Try again later." } def new end @@ -17,7 +20,8 @@ class PasswordsController < ApplicationController end def update - if @user.update(params.permit(:password, :password_confirmation)) + if params[:password].present? && @user.update(params.permit(:password, :password_confirmation)) + @user.sessions.destroy_all # a reset signs out every device redirect_to new_session_path, notice: "Password has been reset." else redirect_to edit_password_path(params[:token]), alert: "Passwords did not match." @@ -25,6 +29,10 @@ class PasswordsController < ApplicationController end private + def require_password_login + redirect_to new_session_path, alert: "Sign in with #{Sso.label}." unless Sso.password_login? + end + def set_user_by_token @user = User.find_by_password_reset_token!(params[:token]) rescue ActiveSupport::MessageVerifier::InvalidSignature diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb index 8ee40e9..16a6729 100644 --- a/app/controllers/profiles_controller.rb +++ b/app/controllers/profiles_controller.rb @@ -3,14 +3,31 @@ class ProfilesController < ApplicationController @user = current_user end + # Changing the email or password needs the current password, so a session + # left open somewhere can't be turned into a takeover of the account. def update @user = current_user attrs = params.require(:user).permit(:name, :email_address, :password, :password_confirmation) attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank? - if @user.update(attrs) + new_email = User.normalize_value_for(:email_address, attrs[:email_address].to_s) if attrs.key?(:email_address) + sensitive = (new_email && new_email != @user.email_address) || attrs.key?(:password) + # Checked before assigning: setting a new password replaces the digest at once. + if sensitive && !@user.authenticate_password(params.dig(:user, :current_password).to_s) + @user.assign_attributes(attrs.except(:password, :password_confirmation)) + @user.errors.add(:base, "Enter your current password to change your email or password") + return render :edit, status: :unprocessable_entity + end + @user.assign_attributes(attrs) + if @user.save + @user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password) redirect_to root_path, notice: "Profile updated." else render :edit, status: :unprocessable_entity end end + + def sign_out_others + count = current_user.sessions.where.not(id: Current.session.id).destroy_all.size + redirect_to edit_profile_path, notice: "Signed out #{helpers.pluralize(count, 'other session')}." + end end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 9785c92..c1d59de 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -6,9 +6,13 @@ class SessionsController < ApplicationController end def create + return redirect_to new_session_path, alert: "Sign in with #{Sso.label}." unless Sso.password_login? + if user = User.authenticate_by(params.permit(:email_address, :password)) + return_to = after_authentication_url + reset_session # fresh session id after signing in start_new_session_for user - redirect_to after_authentication_url + redirect_to return_to else redirect_to new_session_path, alert: "Try another email address or password." end diff --git a/app/controllers/squawks_controller.rb b/app/controllers/squawks_controller.rb index c53b5b9..06c7d85 100644 --- a/app/controllers/squawks_controller.rb +++ b/app/controllers/squawks_controller.rb @@ -70,5 +70,6 @@ class SquawksController < ApplicationController def squawk_params params.require(:squawk).permit(:priority, :issue_reported, :component_id, :notes, attachments: []) + .tap { |p| p[:component_id] = scoped_id(@aircraft.components, p[:component_id]) if p.key?(:component_id) } end end diff --git a/app/controllers/sso_controller.rb b/app/controllers/sso_controller.rb new file mode 100644 index 0000000..9f9002b --- /dev/null +++ b/app/controllers/sso_controller.rb @@ -0,0 +1,100 @@ +# Finishes an OpenID Connect sign-in (OmniAuth runs the redirect dance) and +# links or unlinks a signed-in user's account. See Sso for the settings. +# +# Accounts are matched by the provider's stable subject id. The first time, +# an existing account is linked by email only when the provider says the +# email is verified (or OIDC_TRUST_EMAIL is on), since some providers let +# users edit their email. Otherwise, sign in with a password once and link +# from the profile page. +class SsoController < ApplicationController + allow_unauthenticated_access only: %i[callback failure] + before_action :require_sso + rate_limit to: 20, within: 3.minutes, only: :callback, with: -> { redirect_to new_session_path, alert: "Try again later." } + + def callback + auth = request.env["omniauth.auth"] + return failure unless auth && auth.provider.to_s == Sso::PROVIDER.to_s && auth.uid.present? + return link(auth) if authenticated? + + user = User.find_by(sso_uid: auth.uid) || link_by_email(auth) || create_user(auth) + unless user + email = auth.info&.email.presence + return redirect_to new_session_path, alert: "There's no account for #{email || 'that sign-in'} here yet. " \ + "Ask an administrator to add you, or sign in with your password and link #{Sso.label} from your profile." + end + + sync_admin(user, auth) + return_to = session[:return_to_after_authenticating] + reset_session # fresh session id after signing in + start_new_session_for user + redirect_to return_to || root_url + end + + # OmniAuth's error codes; anything else (network errors…) is logged, not shown. + FAILURES = { "invalid_credentials" => "invalid credentials", "csrf_detected" => "the sign-in expired, try again", + "access_denied" => "access denied", "timeout" => "timed out" }.freeze + + def failure + reason = FAILURES[params[:message].to_s] + Rails.logger.warn("[sso] sign-in failed: #{params[:message].to_s.truncate(300)}") unless reason + redirect_to(authenticated? ? edit_profile_path : new_session_path, + alert: "#{Sso.label} sign-in failed (#{reason || "couldn't reach or verify #{Sso.label}; see the server log"}).") + end + + def destroy + unless Sso.password_login? + return redirect_to edit_profile_path, alert: "Password sign-in is off, so unlinking #{Sso.label} would lock you out." + end + current_user.update!(sso_uid: nil) + redirect_to edit_profile_path, notice: "#{Sso.label} unlinked. Sign in with your email and password from now on." + end + + private + + def require_sso + raise ActiveRecord::RecordNotFound unless Sso.enabled? + end + + def link(auth) + owner = User.find_by(sso_uid: auth.uid) + if owner && owner != current_user + redirect_to edit_profile_path, alert: "That #{Sso.label} account is already linked to another user." + else + current_user.update!(sso_uid: auth.uid) + redirect_to edit_profile_path, notice: "#{Sso.label} linked. You can now sign in with it." + end + end + + def link_by_email(auth) + email = auth.info&.email.to_s.strip.downcase + return if email.blank? || !(email_verified?(auth) || Sso.trust_email?) + user = User.find_by(email_address: email, sso_uid: nil) + user&.update!(sso_uid: auth.uid) + user + end + + def create_user(auth) + return unless Sso.auto_create_users? + email = auth.info&.email.to_s.strip.downcase + return if email.blank? || User.exists?(email_address: email) + # The random password is never shown; a password reset can set a real one. + User.create!(email_address: email, name: auth.info&.name.presence, sso_uid: auth.uid, password: SecureRandom.base58(40)) + rescue ActiveRecord::RecordInvalid + nil + end + + def email_verified?(auth) + [ true, "true" ].include?(raw_info(auth)["email_verified"]) + end + + # With OIDC_ADMIN_GROUP set, the provider decides who's an admin. Skipped + # when the token carries no groups claim, so a missing scope can't demote. + def sync_admin(user, auth) + return unless Sso.admin_group && raw_info(auth).key?("groups") + user.update!(admin: Array(raw_info(auth)["groups"]).map(&:to_s).include?(Sso.admin_group)) + end + + def raw_info(auth) + (auth.extra&.raw_info || {}).to_h.stringify_keys + end +end diff --git a/app/javascript/application.js b/app/javascript/application.js index 99df306..7dd46de 100644 --- a/app/javascript/application.js +++ b/app/javascript/application.js @@ -42,3 +42,17 @@ function labelTableCells(root = document) { } document.addEventListener("turbo:load", () => labelTableCells()) document.addEventListener("turbo:frame-load", (event) => labelTableCells(event.target)) + +// Small behaviours that used to be inline onclick handlers (blocked by the CSP). +document.addEventListener("click", (event) => { + const target = event.target + if (!(target instanceof HTMLInputElement)) return + if (target.matches("[data-select-on-click]")) target.select() + if (target.matches("[data-check-all]")) { + target.closest("table")?.querySelectorAll("tbody input[type=checkbox]").forEach((box) => { box.checked = target.checked }) + } +}) + +document.addEventListener("change", (event) => { + if (event.target.matches?.("[data-submit-on-change]")) event.target.form?.requestSubmit() +}) diff --git a/app/models/sso.rb b/app/models/sso.rb new file mode 100644 index 0000000..922afa5 --- /dev/null +++ b/app/models/sso.rb @@ -0,0 +1,45 @@ +# Single sign-on through an OpenID Connect provider (Authentik, Keycloak, +# Google…), configured with environment variables: +# +# OIDC_ISSUER issuer URL, e.g. https://auth.example.com/application/o/sam/ +# OIDC_CLIENT_ID client ID +# OIDC_CLIENT_SECRET client secret +# OIDC_PROVIDER_NAME button label (default "SSO") +# OIDC_AUTO_CREATE_USERS "true" to create an account for anyone the +# provider lets through (they start with no aircraft) +# OIDC_TRUST_EMAIL "true" to link existing accounts by email even when +# the provider doesn't mark the email verified. Only +# for providers where users can't change their email. +# OIDC_ADMIN_GROUP members of this group are admins, others aren't +# (synced at each sign-in; needs a "groups" claim) +# PASSWORD_LOGIN "false" to turn off email/password sign-in once SSO works +# APP_URL public base URL (default https://APP_HOST) +module Sso + PROVIDER = :oidc + + module_function + + def enabled? = ENV["OIDC_ISSUER"].present? && ENV["OIDC_CLIENT_ID"].present? + def label = ENV["OIDC_PROVIDER_NAME"].presence || "SSO" + def auto_create_users? = ENV["OIDC_AUTO_CREATE_USERS"] == "true" + def trust_email? = ENV["OIDC_TRUST_EMAIL"] == "true" + def admin_group = ENV["OIDC_ADMIN_GROUP"].presence + + # Password sign-in stays on unless SSO is set up and it's switched off, so + # a broken SSO setup can't lock everyone out. + def password_login? = !enabled? || ENV["PASSWORD_LOGIN"] != "false" + + def app_url + ENV["APP_URL"].presence&.chomp("/") || + "#{ENV.fetch('FORCE_SSL', 'true') == 'true' ? 'https' : 'http'}://#{ENV.fetch('APP_HOST', 'localhost:3000')}" + end + + # Origin of the provider, for the CSP form-action list (the sign-in POST + # redirects there). + def issuer_origin + uri = URI.parse(ENV["OIDC_ISSUER"].to_s) + uri.host && "#{uri.scheme}://#{uri.host}#{":#{uri.port}" unless uri.port == uri.default_port}" + rescue URI::InvalidURIError + nil + end +end diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb index b02b858..60c8842 100644 --- a/app/views/admin/users/index.html.erb +++ b/app/views/admin/users/index.html.erb @@ -3,7 +3,7 @@
<% @users.each do |u| %> - + diff --git a/app/views/aircraft_roles/index.html.erb b/app/views/aircraft_roles/index.html.erb index aaba293..2d40b38 100644 --- a/app/views/aircraft_roles/index.html.erb +++ b/app/views/aircraft_roles/index.html.erb @@ -10,7 +10,7 @@ @@ -40,7 +40,7 @@ <%= delete_button "Revoke", aircraft_share_token_path(@aircraft, t), confirm: "Revoke this link? Anyone using it will lose access." %> - +
Created <%= t.created_at.to_date %><%= " by #{t.created_by.display_name}" if t.created_by %> · <%= t.expires_at ? "expires #{l t.expires_at, format: :short}" : "never expires" %>
<% end %> diff --git a/app/views/airport_codes/show.html.erb b/app/views/airport_codes/show.html.erb index 089efd0..2bcde04 100644 --- a/app/views/airport_codes/show.html.erb +++ b/app/views/airport_codes/show.html.erb @@ -12,7 +12,7 @@ <% if changes.any? %>
NameEmailAircraft
<%= u.name %> <% if u.admin? %>Admin<% end %><%= u.name %> <% if u.admin? %>Admin<% end %><% if u.sso_uid? %> <%= Sso.label %><% end %> <%= u.email_address %> <%= u.aircraft_roles.map { "#{_1.aircraft.tail_number} (#{_1.role})" }.join(", ").presence || "—" %> <%= link_to "Edit", edit_admin_user_path(u), class: "btn-secondary btn-sm" %><%= r.user.display_name %>
<%= r.user.email_address %>
<%= form_with url: aircraft_aircraft_role_path(@aircraft, r), method: :patch do |f| %> - <%= f.select :role, AircraftRole::ROLES.invert, { selected: r.role }, class: "input w-28", onchange: "this.form.requestSubmit()" %> + <%= f.select :role, AircraftRole::ROLES.invert, { selected: r.role }, class: "input w-28", data: { submit_on_change: true } %> <% end %> <% unless r.user == current_user %><%= delete_button "Remove", aircraft_aircraft_role_path(@aircraft, r), confirm: "Remove #{r.user.display_name}'s access?" %><% end %>
- + <% changes.each do |c| %> diff --git a/app/views/events/index.html.erb b/app/views/events/index.html.erb index d399191..6d01254 100644 --- a/app/views/events/index.html.erb +++ b/app/views/events/index.html.erb @@ -4,7 +4,7 @@

Activity Log

<%= form_with url: aircraft_events_path(@aircraft), method: :get, class: "flex gap-2" do |f| %> - <%= f.select :category, AircraftEvent::CATEGORIES.invert, { include_blank: "All categories", selected: @category }, class: "input", onchange: "this.form.requestSubmit()" %> + <%= f.select :category, AircraftEvent::CATEGORIES.invert, { include_blank: "All categories", selected: @category }, class: "input", data: { submit_on_change: true } %> <% end %>
<%= render "events/list", events: @events, full: true %> diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb index abed270..cf5d723 100644 --- a/app/views/profiles/edit.html.erb +++ b/app/views/profiles/edit.html.erb @@ -4,10 +4,43 @@ <%= f.field :name %> <%= f.field :email_address, as: :email, label: "Email" %> <%= f.field :password, as: :password, label: "New password", hint: "Leave blank to keep your current password.", autocomplete: "new-password" %> - <%= f.field :password_confirmation, as: :password, label: "Confirm new password" %> + <%= f.field :password_confirmation, as: :password, label: "Confirm new password", autocomplete: "new-password" %> +
+ <%= label_tag "user[current_password]", "Current password", class: "label" %> + <%= password_field_tag "user[current_password]", nil, id: "user_current_password", class: "input", autocomplete: "current-password" %> +

Needed to change your email or password.<%= " Signed up with #{Sso.label} and never set one? Use “Forgot password?” on the sign-in page." if Sso.enabled? && @user.sso_uid? %>

+
<%= f.submit "Save" %> <% end %> +<% if Sso.enabled? %> +
+

Single sign-on

+ <% if @user.sso_uid? %> +

Your account is linked to <%= Sso.label %>; you can sign in with it.

+ <% if Sso.password_login? %> +
<%= button_to "Unlink #{Sso.label}", sso_link_path, method: :delete, class: "btn-secondary btn-sm", + form: { data: { turbo_confirm: "Unlink #{Sso.label}? You'll sign in with your email and password." } } %>
+ <% end %> + <% else %> +

Link your <%= Sso.label %> account to sign in with it.

+
<%= button_to "Link #{Sso.label}", "/auth/#{Sso::PROVIDER}", class: "btn-secondary btn-sm", data: { turbo: false } %>
+ <% end %> +
+<% end %> + +
+

Sessions

+ <% others = @user.sessions.where.not(id: Current.session.id).count %> +

+ You're signed in on <%= pluralize(others, "other device or browser", plural: "other devices or browsers") %>. + Sessions unused for <%= Authentication::SESSION_IDLE_TIMEOUT.inspect %> sign out on their own. +

+ <% if others.positive? %> +
<%= button_to "Sign out everywhere else", other_sessions_path, method: :delete, class: "btn-secondary btn-sm" %>
+ <% end %> +
+

Integrations

diff --git a/app/views/sessions/new.html.erb b/app/views/sessions/new.html.erb index ef430d9..49c84ae 100644 --- a/app/views/sessions/new.html.erb +++ b/app/views/sessions/new.html.erb @@ -1,12 +1,22 @@ <% content_for :title, "Sign in" %>

Sign in

- <%= form_with url: session_path, class: "card card-body space-y-4" do |form| %> -
<%= form.label :email_address, "Email", class: "label" %> - <%= form.email_field :email_address, required: true, autofocus: true, autocomplete: "username", value: params[:email_address], class: "input" %>
-
<%= form.label :password, class: "label" %> - <%= form.password_field :password, required: true, autocomplete: "current-password", maxlength: 72, class: "input" %>
- <%= form.submit "Sign in", class: "btn-primary w-full justify-center" %> -

<%= link_to "Forgot password?", new_password_path, class: "link" %>

- <% end %> +
+ <% if Sso.enabled? %> + <%= button_to "Sign in with #{Sso.label}", "/auth/#{Sso::PROVIDER}", class: "btn-primary w-full justify-center", data: { turbo: false } %> + <% end %> + <% if Sso.password_login? %> + <% if Sso.enabled? %> +
or
+ <% end %> + <%= form_with url: session_path, class: "space-y-4" do |form| %> +
<%= form.label :email_address, "Email", class: "label" %> + <%= form.email_field :email_address, required: true, autofocus: !Sso.enabled?, autocomplete: "username", value: params[:email_address], class: "input" %>
+
<%= form.label :password, class: "label" %> + <%= form.password_field :password, required: true, autocomplete: "current-password", maxlength: 72, class: "input" %>
+ <%= form.submit "Sign in", class: (Sso.enabled? ? "btn-secondary" : "btn-primary") + " w-full justify-center" %> +

<%= link_to "Forgot password?", new_password_path, class: "link" %>

+ <% end %> + <% end %> +
diff --git a/app/views/shared/_theme_script.html.erb b/app/views/shared/_theme_script.html.erb index ed64970..5cab7ef 100644 --- a/app/views/shared/_theme_script.html.erb +++ b/app/views/shared/_theme_script.html.erb @@ -1,6 +1,6 @@ <%# Applies the saved theme before the page paints (no light flash in dark mode). "system" (default) follows the OS setting. Set by theme_controller.js. %> -
LoggedStandardAirportEntries
LoggedStandardAirportEntries