kaui 4.0.31 → 4.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b8bd5073d201b723a1cb3ace16d0b405457c243592ab0fdf5bead28945853437
4
- data.tar.gz: cd7416b2d1e811dc57770beea370ff42c797d7ba94817d3a049ea9f957bc2bb9
3
+ metadata.gz: a5f4f08b6891d04bbe917a4d75db40c5b6b7174dcc30cdde298efd01f4bac01a
4
+ data.tar.gz: 5e5f19747ac0e25c708eea4e89cd554a68a3d300a087d5fe0d0a8dd27e08a9d6
5
5
  SHA512:
6
- metadata.gz: 11655f4cf7f9ca622fdec404b92a1788ad9df18bbe2be8fb9192460b4e4a6f58806fa797c3f694ea27f7bced9912dd223ed999157f15997fa824d48640cbd517
7
- data.tar.gz: dd08f65788df81b02c8f3f43cf0be801943f1dd3ebdceda6149e913d28dd25fa44ff09bf19d83d6486ea8e25cb1b0a1ae990c407ab1efbc966b58f6a35732693
6
+ metadata.gz: d986768e3248cab23e94ccf3794f87e9c5de7840803aacc499f6d20b3f115fd6efe94e5e509fd3cb5d1e29465baee0d6f8f421c58dacfa84ea1745531bec0d73
7
+ data.tar.gz: ecc10f9c3187f457152617dc04f86ef58056c42bde80b658674e59d46f08e5ee2be5b32df444f75bb9fdd95e10f32ce6bf2b28f325829124fcd8d313ef93358e
data/README.md CHANGED
@@ -138,9 +138,24 @@ A web application whose users sign in with AWS Cognito can open Kaui for them wi
138
138
  | `kaui.cognito.client_ids` (or `kaui.cognito.client_id`) | `KAUI_COGNITO_CLIENT_IDS` (or `KAUI_COGNITO_CLIENT_ID`) | Accepted Cognito app client ids (comma-separated) |
139
139
  | `kaui.cognito.login_url` | `KAUI_COGNITO_LOGIN_URL` | Optional. Login page of the application the users come from (http or https), where they are sent when their Kill Bill session expires |
140
140
 
141
- The client sends the Cognito ID token as `Authorization: Bearer <token>` and, optionally, `target` (a Kaui path such as `/accounts`). The response is `{"redirectUrl": "..."}` (including the context path Kaui is mounted at) and sets the Kaui session cookie. Two modes:
141
+ The client sends the Cognito ID token as `Authorization: Bearer <token>` and, optionally, `target`: `/`, or one of `/accounts`, `/invoices`, `/payments`, `/bundles`, `/subscriptions` (or a sub-path of these, e.g. `/accounts/new`, `/subscriptions/new?account_id=...`), the home page otherwise. The response is `{"redirectUrl": "..."}` (including the context path Kaui is mounted at) and sets the Kaui session cookie. Two modes:
142
142
 
143
143
  * **basic**: `kb_username` (defaults to the email of the token) and `kb_password`. Kaui logs into Kill Bill with Basic auth; the tenant comes from the `kaui_allowed_users` of that user (`tenant_name` disambiguates).
144
144
  * **bearer**: no `kb_password`, for users without Kill Bill credentials (requires the Cognito realm in Kill Bill). Kaui logs into Kill Bill with the Bearer token and the Kaui user is the principal reported by Kill Bill (e.g. `cognito:alice@acme.com`). The tenant comes from `tenant_api_key` and `tenant_api_secret`, which must match a tenant of `kaui_tenants` (`403` otherwise); the user is then allowed on that tenant. If Kill Bill has no Cognito realm, the answer is `401`.
145
145
 
146
146
  Users of the bearer mode have no password: when their Kill Bill session expires, Kaui sends them to `kaui.cognito.login_url` when it is set, and displays a "reopen Kaui from the application you came from" page otherwise, instead of the sign-in form (they have no Kill Bill password to type in it). The Tenants, Users and Roles settings screens are only listed for them (sidebar, home page), and only served if their Kill Bill permissions include `*:*`: otherwise they are sent back to the home page with a warning (403 for non-HTML requests).
147
+
148
+ ### Registering a tenant
149
+
150
+ A tenant created in Kill Bill by the web application (e.g. Aviate) has to be known by Kaui (`kaui_tenants`) before its users can use it: `POST /sso/cognito/tenants` (`POST /sso/aviate/tenants` is kept as an alias) registers it and allows the user on it. It is disabled (`404`) in the same way as the exchange.
151
+
152
+ The client sends the Cognito ID token as `Authorization: Bearer <token>`, the Kill Bill credentials of the user (`kb_username` and `kb_password` in basic mode, nothing in bearer mode, as for the exchange) and the tenant: `name`, `tenantKey`, `tenantSecret` and `kbTenantId` (the Kill Bill id of the tenant). Kaui checks with Kill Bill that the key and the secret are valid and belong to `kbTenantId`. Unlike the exchange, it does not create a session for the browser.
153
+
154
+ | Status | Meaning |
155
+ |---|---|
156
+ | `201` | The tenant was registered and the user is allowed on it. Body: `{"id": ..., "name": ..., "kbTenantId": ..., "tenantKey": ...}` |
157
+ | `200` | The tenant was already registered: the user is allowed on it (the call can be repeated safely) |
158
+ | `400` | A parameter is missing |
159
+ | `401` | Invalid or expired token, or invalid Kill Bill credentials |
160
+ | `403` | Kill Bill rejected `tenantKey`/`tenantSecret`, or the key is not the tenant `kbTenantId` |
161
+ | `409` | The name is already used by another tenant |
@@ -70,6 +70,19 @@ module Kaui
70
70
  user
71
71
  end
72
72
 
73
+ # Verifies the Cognito token and logs into Kill Bill (basic or bearer mode), like authenticate_kb_user!, but for the API
74
+ # calls that must not change the session of the browser, and that do not need a tenant yet (e.g. to register one).
75
+ # Returns the Kaui::User (saved, with the Kill Bill session id). No Warden session, no tenant check.
76
+ def authenticate_kb_user_without_session!
77
+ token = extract_bearer_token
78
+ claims = Kaui::CognitoJwtVerifier.verify!(token)
79
+
80
+ user, kb_session_id = kb_bearer_mode? ? login_to_kb_with_bearer!(token) : login_to_kb_with_password!(claims)
81
+ user.kb_session_id = kb_session_id
82
+ user.save!
83
+ user
84
+ end
85
+
73
86
  def login_to_kb_with_password!(claims)
74
87
  kb_username = params[:kb_username].presence || claims['email'].to_s.downcase.presence
75
88
  raise Error.new('kb_username is required when the token has no email claim', :bad_request) if kb_username.blank?
@@ -11,6 +11,9 @@ module Kaui
11
11
 
12
12
  # The sign-in flow eventually calls authenticate! from config/initializers/killbill_authenticatable.rb
13
13
 
14
+ # Before the sign out, which resets the session: remember if the session comes from the Cognito token exchange
15
+ prepend_before_action :remember_exchanged_session, only: :destroy # rubocop:disable Rails/LexicallyScopedActionFilter
16
+
14
17
  def new
15
18
  flash.delete(:alert) if flash[:alert] == I18n.t('devise.failure.unauthenticated') && (stored_location_for(:user).nil? || flash[:notice].present?)
16
19
  super
@@ -34,9 +37,16 @@ module Kaui
34
37
 
35
38
  def after_sign_out_path_for(_resource)
36
39
  cookies.delete(:jwt_token)
40
+ # Users who came through the Cognito token exchange sign in again in the application they came from (if configured)
41
+ return sso_cognito_session_expired_path if @exchanged_session && Kaui::CognitoJwtVerifier.login_url
42
+
37
43
  new_user_session_path
38
44
  end
39
45
 
46
+ def remember_exchanged_session
47
+ @exchanged_session = session[Kaui::KbCognitoAuthenticatable::SSO_SESSION_KEY] || current_user&.cognito_principal?
48
+ end
49
+
40
50
  def require_no_authentication
41
51
  super
42
52
  # Remove the somewhat confusing message "You are already signed in."
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kaui
4
+ module SsoCognito
5
+ # Common part of the endpoints called by a web application whose users signed in with AWS Cognito
6
+ # (see Kaui::SsoCognitoController and Kaui::SsoCognito::TenantsController).
7
+ #
8
+ # Not an ApplicationController: the host application's one may require a signed-in user.
9
+ # The endpoints are disabled (404) unless the Cognito issuer and client ids are configured
10
+ # (see Kaui::CognitoJwtVerifier and #ensure_cognito_configured).
11
+ class BaseController < ActionController::Base # rubocop:disable Rails/ApplicationController
12
+ include Kaui::KbCognitoAuthenticatable
13
+
14
+ # The calls are cross-site API calls authenticated by the Cognito token. The CSRF protection stays on for any
15
+ # request without a bearer token: a cross-site form cannot set the Authorization header.
16
+ protect_from_forgery with: :exception, unless: -> { request.headers['Authorization'].to_s.start_with?('Bearer ') }
17
+
18
+ # Declared from the most generic to the most specific (the last matching handler wins)
19
+ rescue_from StandardError do |e|
20
+ Rails.logger.error("#{sso_operation} failed: #{e.class} - #{e.message}")
21
+ Rails.logger.error(e.backtrace.join("\n")) if e.backtrace
22
+ render_error("#{sso_operation} failed", :internal_server_error)
23
+ end
24
+ rescue_from ActionController::InvalidAuthenticityToken do |e|
25
+ Rails.logger.warn("#{sso_operation} rejected: #{e.message}")
26
+ render_error('Missing or invalid Authorization header', :unauthorized)
27
+ end
28
+ rescue_from JWT::DecodeError do |e|
29
+ Rails.logger.error("SSO JWT verification failed: #{e.message}")
30
+ render_error('Invalid or expired token', :unauthorized)
31
+ end
32
+ rescue_from Kaui::KbCognitoAuthenticatable::Error do |e|
33
+ Rails.logger.warn("#{sso_operation} rejected: #{e.message}")
34
+ render_error(e.message, e.status)
35
+ end
36
+
37
+ private
38
+
39
+ # Name of the operation for the logs and the error messages
40
+ def sso_operation
41
+ 'SSO exchange'
42
+ end
43
+
44
+ def ensure_cognito_configured
45
+ return if Kaui::CognitoJwtVerifier.configured?
46
+
47
+ render_error("Cognito token #{sso_feature} is not enabled on this Kaui (kaui.cognito.issuer / kaui.cognito.client_ids)", :not_found)
48
+ end
49
+
50
+ def sso_feature
51
+ 'exchange'
52
+ end
53
+
54
+ def render_error(message, status)
55
+ render json: { error: message }, status:
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kaui
4
+ module SsoCognito
5
+ # Registers in Kaui a tenant that was created in Kill Bill by the web application (e.g. Aviate), and grants the user
6
+ # access to it.
7
+ #
8
+ # POST /sso/cognito/tenants (alias: POST /sso/aviate/tenants)
9
+ # Authorization: Bearer <Cognito ID token>
10
+ # body: kb_username/kb_password (basic mode, none in bearer mode), name, tenantKey, tenantSecret, kbTenantId
11
+ #
12
+ # 201 the tenant was registered, 200 it already was (the user is granted access to it),
13
+ # 400 missing parameter, 401 invalid token or Kill Bill credentials, 403 tenantKey/tenantSecret rejected by Kill Bill
14
+ # or not the tenant kbTenantId, 409 the name is already used by another tenant, 404 Cognito not configured.
15
+ #
16
+ # Unlike the exchange, it does not create a session for the browser: the user keeps the session they have (if any).
17
+ # Disabled (404) unless the Cognito issuer and client ids are configured (see Kaui::CognitoJwtVerifier).
18
+ class TenantsController < BaseController
19
+ REQUIRED_PARAMS = %i[name tenantKey tenantSecret kbTenantId].freeze
20
+
21
+ before_action :ensure_cognito_configured
22
+
23
+ def create
24
+ user = authenticate_kb_user_without_session!
25
+
26
+ missing = REQUIRED_PARAMS.select { |p| params[p].blank? }
27
+ raise Kaui::KbCognitoAuthenticatable::Error.new("Missing required parameter(s): #{missing.join(', ')}", :bad_request) unless missing.empty?
28
+
29
+ verify_tenant_credentials!(user)
30
+ tenant, created = register_tenant(user)
31
+ Rails.logger.info("Tenant registration: #{user.kb_username} #{created ? 'registered' : 'was granted access to'} tenant #{tenant.name}")
32
+
33
+ render json: { id: tenant.id, name: tenant.name, kbTenantId: tenant.kb_tenant_id, tenantKey: tenant.api_key }, status: created ? :created : :ok
34
+ end
35
+
36
+ private
37
+
38
+ def sso_operation
39
+ 'Tenant registration'
40
+ end
41
+
42
+ def sso_feature
43
+ 'registration'
44
+ end
45
+
46
+ # The tenant must exist in Kill Bill, with these credentials and this id: anyone with a valid Cognito token could
47
+ # otherwise register (and squat the name of) any tenant
48
+ def verify_tenant_credentials!(user)
49
+ options = { username: user.kb_username, session_id: user.kb_session_id, api_key: params[:tenantKey], api_secret: params[:tenantSecret] }
50
+ kb_tenant = Kaui::AdminTenant.find_by_api_key(params[:tenantKey], options)
51
+ return if kb_tenant.tenant_id.to_s == params[:kbTenantId].to_s
52
+
53
+ raise Kaui::KbCognitoAuthenticatable::Error.new('tenantKey is not the Kill Bill tenant kbTenantId', :forbidden)
54
+ rescue KillBillClient::API::Unauthorized, KillBillClient::API::Forbidden, KillBillClient::API::NotFound, KillBillClient::API::Conflict
55
+ raise rejected_credentials
56
+ rescue KillBillClient::API::InternalServerError => e
57
+ # Kill Bill answers with a 500 for an unknown api key
58
+ raise e unless e.message&.include?('TenantCacheLoader cannot find value')
59
+
60
+ raise rejected_credentials
61
+ end
62
+
63
+ def rejected_credentials
64
+ Kaui::KbCognitoAuthenticatable::Error.new('Kill Bill rejected the tenant credentials (tenantKey/tenantSecret)', :forbidden)
65
+ end
66
+
67
+ # Returns the Kaui tenant and whether it was created (false: it was already registered, with the same Kill Bill tenant)
68
+ def register_tenant(user)
69
+ tenant = Kaui::Tenant.find_by(kb_tenant_id: params[:kbTenantId]) || Kaui::Tenant.find_by(api_key: params[:tenantKey])
70
+ by_name = Kaui::Tenant.find_by(name: params[:name])
71
+ raise Kaui::KbCognitoAuthenticatable::Error.new('A tenant with this name already exists', :conflict) if by_name && by_name != tenant
72
+
73
+ created = tenant.nil?
74
+ tenant ||= Kaui::Tenant.create!(name: params[:name], api_key: params[:tenantKey], api_secret: params[:tenantSecret], kb_tenant_id: params[:kbTenantId])
75
+
76
+ allowed_user = Kaui::AllowedUser.where(kb_username: user.kb_username).first_or_create!
77
+ tenant.kaui_allowed_users << allowed_user unless tenant.kaui_allowed_users.include?(allowed_user)
78
+ [tenant, created]
79
+ end
80
+ end
81
+ end
82
+ end
@@ -10,38 +10,12 @@ module Kaui
10
10
  # tenant_name (basic mode) and target (path of the Kaui page to open)
11
11
  #
12
12
  # Disabled (404) unless the Cognito issuer and client ids are configured (see Kaui::CognitoJwtVerifier).
13
- # Not an ApplicationController: the host application's one may require a signed-in user
14
- class SsoCognitoController < ActionController::Base # rubocop:disable Rails/ApplicationController
15
- include Kaui::KbCognitoAuthenticatable
13
+ class SsoCognitoController < Kaui::SsoCognito::BaseController
14
+ ALLOWED_TARGETS = %w[/accounts /invoices /payments /bundles /subscriptions].freeze
16
15
 
17
- # The exchange is a cross-site API call authenticated by the Cognito token. The CSRF protection stays on for any
18
- # request without a bearer token: a cross-site form cannot set the Authorization header.
19
- protect_from_forgery with: :exception, unless: -> { request.headers['Authorization'].to_s.start_with?('Bearer ') }
20
-
21
- ALLOWED_TARGETS = %w[/accounts /invoices /payments /bundles].freeze
22
-
23
- # Declared from the most generic to the most specific (the last matching handler wins)
24
- rescue_from StandardError do |e|
25
- Rails.logger.error("SSO exchange failed: #{e.class} - #{e.message}")
26
- Rails.logger.error(e.backtrace.join("\n")) if e.backtrace
27
- render_error('SSO exchange failed', :internal_server_error)
28
- end
29
- rescue_from ActionController::InvalidAuthenticityToken do |e|
30
- Rails.logger.warn("SSO exchange rejected: #{e.message}")
31
- render_error('Missing or invalid Authorization header', :unauthorized)
32
- end
33
- rescue_from JWT::DecodeError do |e|
34
- Rails.logger.error("SSO JWT verification failed: #{e.message}")
35
- render_error('Invalid or expired token', :unauthorized)
36
- end
37
- rescue_from Kaui::KbCognitoAuthenticatable::Error do |e|
38
- Rails.logger.warn("SSO exchange rejected: #{e.message}")
39
- render_error(e.message, e.status)
40
- end
16
+ before_action :ensure_cognito_configured, only: :exchange
41
17
 
42
18
  def exchange
43
- return render_error('Cognito token exchange is not enabled on this Kaui (kaui.cognito.issuer / kaui.cognito.client_ids)', :not_found) unless Kaui::CognitoJwtVerifier.configured?
44
-
45
19
  # Verify the token, authenticate against Kill Bill, and establish the Warden session of the Kaui::User
46
20
  user = authenticate_kb_user!
47
21
  Rails.logger.info("SSO: Authenticated #{user.kb_username} (user ##{user.id})")
@@ -63,10 +37,6 @@ module Kaui
63
37
 
64
38
  private
65
39
 
66
- def render_error(message, status)
67
- render json: { error: message }, status:
68
- end
69
-
70
40
  def sso_target_url
71
41
  # Allow only known internal paths to avoid open redirect vulnerability
72
42
  path = params[:target].to_s.strip
@@ -76,9 +76,13 @@ Warden::Strategies.add(:killbill_jwt, Devise::Strategies::KillbillJWTAuthenticat
76
76
  Warden::Manager.after_set_user do |user, auth, opts|
77
77
  unless user.authenticated_with_killbill?
78
78
  scope = opts[:scope]
79
+ # Read before the logout, which resets the session: the session of a Cognito token exchange (basic or bearer mode) is flagged
80
+ exchanged = auth.env['rack.session']&.[](Kaui::KbCognitoAuthenticatable::SSO_SESSION_KEY)
79
81
  auth.logout(scope)
80
- # Users without Kill Bill credentials (Cognito token exchange) can't use the sign-in form: see Devise::FailureApp#scope_url
81
- throw(:warden, scope:, reason: user.cognito_principal? ? :cognito_session_expired : 'Kill Bill session expired')
82
+ # Users who signed in through the Cognito token exchange go back to the application they came from instead of the sign-in
83
+ # form: bearer users have no Kill Bill password, basic users usually don't know theirs (see Devise::FailureApp#scope_url)
84
+ back_to_login_app = user.cognito_principal? || (exchanged && Kaui::CognitoJwtVerifier.login_url)
85
+ throw(:warden, scope:, reason: back_to_login_app ? :cognito_session_expired : 'Kill Bill session expired')
82
86
  end
83
87
  end
84
88
 
data/config/routes.rb CHANGED
@@ -29,6 +29,9 @@ Kaui::Engine.routes.draw do
29
29
  post '/sso/cognito/exchange' => 'sso_cognito#exchange', :as => 'sso_cognito_exchange'
30
30
  post '/sso/aviate/exchange' => 'sso_cognito#exchange', :as => 'sso_aviate_exchange'
31
31
  get '/sso/cognito/session_expired' => 'sso_cognito#session_expired', :as => 'sso_cognito_session_expired'
32
+ # Registers in Kaui a tenant created in Kill Bill (/sso/aviate/tenants is kept as an alias for existing clients)
33
+ post '/sso/cognito/tenants' => 'sso_cognito/tenants#create', :as => 'sso_cognito_tenants'
34
+ post '/sso/aviate/tenants' => 'sso_cognito/tenants#create', :as => 'sso_aviate_tenants'
32
35
 
33
36
  scope '/accounts' do
34
37
  post '/pagination' => 'accounts#pagination', :as => 'accounts_pagination'
data/lib/kaui/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Kaui
4
- VERSION = '4.0.31'
4
+ VERSION = '4.0.32'
5
5
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kaui
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.0.31
4
+ version: 4.0.32
5
5
  platform: ruby
6
6
  authors:
7
7
  - Kill Bill core team
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-25 00:00:00.000000000 Z
11
+ date: 2026-11-29 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: actionpack
@@ -468,6 +468,8 @@ files:
468
468
  - app/controllers/kaui/registrations_controller.rb
469
469
  - app/controllers/kaui/role_definitions_controller.rb
470
470
  - app/controllers/kaui/sessions_controller.rb
471
+ - app/controllers/kaui/sso_cognito/base_controller.rb
472
+ - app/controllers/kaui/sso_cognito/tenants_controller.rb
471
473
  - app/controllers/kaui/sso_cognito_controller.rb
472
474
  - app/controllers/kaui/subscriptions_controller.rb
473
475
  - app/controllers/kaui/tag_definitions_controller.rb