kaui 4.0.29 → 4.0.31

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: fe249d7727e4018a5ac75692ea7bcd96eabf47c7a088831467e3e92a4fa4bfde
4
- data.tar.gz: 2531c79e6230ef5b94c3488eebc672053d94a61fac348b44373baeaf7557fedc
3
+ metadata.gz: b8bd5073d201b723a1cb3ace16d0b405457c243592ab0fdf5bead28945853437
4
+ data.tar.gz: cd7416b2d1e811dc57770beea370ff42c797d7ba94817d3a049ea9f957bc2bb9
5
5
  SHA512:
6
- metadata.gz: 5b6d597074b06778d4985fed8a1f1343646f00b95837a7dbd041cb63ad0e583d0cb7d856596b01a42ca58be02875929aae6040f4ac57e9fb075dacaed63f305b
7
- data.tar.gz: e14677cc4af0bd52371fb2ef9bcf62be6db87ffbfcfc1933dc544b1bb06a2841ad9cbcfc7d5728b42dd3e29c879179de8307b9ca581d67f2316833045765249c
6
+ metadata.gz: 11655f4cf7f9ca622fdec404b92a1788ad9df18bbe2be8fb9192460b4e4a6f58806fa797c3f694ea27f7bced9912dd223ed999157f15997fa824d48640cbd517
7
+ data.tar.gz: dd08f65788df81b02c8f3f43cf0be801943f1dd3ebdceda6149e913d28dd25fa44ff09bf19d83d6486ea8e25cb1b0a1ae990c407ab1efbc966b58f6a35732693
data/README.md CHANGED
@@ -126,3 +126,21 @@ KAUI has been enriched with new models and new screens to manage the multi-tenan
126
126
 
127
127
 
128
128
 
129
+
130
+ Cognito token exchange (optional)
131
+ ---------------------------------
132
+
133
+ A web application whose users sign in with AWS Cognito can open Kaui for them without a second login, through `POST /sso/cognito/exchange` (`POST /sso/aviate/exchange` is kept as an alias). The feature is **disabled** (the endpoint answers `404`) unless the Cognito issuer and at least one app client id are configured, either as system properties or as environment variables:
134
+
135
+ | System property | Environment variable | Description |
136
+ |---|---|---|
137
+ | `kaui.cognito.issuer` | `KAUI_COGNITO_ISSUER` | `https://cognito-idp.<region>.amazonaws.com/<user-pool-id>` |
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
+ | `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
+
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:
142
+
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
+ * **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
+
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).
@@ -98,6 +98,11 @@
98
98
  text-decoration: none !important;
99
99
  }
100
100
 
101
+ .payments-index .payments .payments-table tr td a.payment-number-link {
102
+ color: var(--kb-primary) !important;
103
+ font-weight: 600;
104
+ }
105
+
101
106
  .payments-index .payments .payments-table td:first-child {
102
107
  padding-left: 1.25rem !important;
103
108
  }
@@ -2,6 +2,9 @@
2
2
 
3
3
  module Kaui
4
4
  class AdminAllowedUsersController < Kaui::EngineController
5
+ # Before the tenant selection redirect: the answer must not depend on the selected tenant
6
+ prepend_before_action :require_kaui_admin_screens!
7
+
5
8
  skip_before_action :check_for_redirect_to_tenant_screen
6
9
 
7
10
  def index
@@ -2,6 +2,9 @@
2
2
 
3
3
  module Kaui
4
4
  class AdminTenantsController < Kaui::EngineController
5
+ # Before the tenant selection redirect: the answer must not depend on the selected tenant
6
+ prepend_before_action :require_kaui_admin_screens!
7
+
5
8
  skip_before_action :check_for_redirect_to_tenant_screen
6
9
 
7
10
  def index
@@ -9,6 +9,8 @@ class Kaui::EngineController < ApplicationController
9
9
 
10
10
  layout :get_layout
11
11
 
12
+ helper_method :kaui_admin_screens_allowed?
13
+
12
14
  # Common options for the Kill Bill client
13
15
  def options_for_klient(options = {})
14
16
  user_tenant_options = Kaui.current_tenant_user_options(current_user, session)
@@ -30,6 +32,23 @@ class Kaui::EngineController < ApplicationController
30
32
  @current_ability ||= Kaui::Ability.new(current_user)
31
33
  end
32
34
 
35
+ # The Kaui administration screens (tenants, users, roles) are not for the users who signed in through the Cognito token
36
+ # exchange, unless they hold the *:* role
37
+ def kaui_admin_screens_allowed?
38
+ !current_user&.cognito_principal? || can?(:manage, :all)
39
+ end
40
+
41
+ def require_kaui_admin_screens!
42
+ return if kaui_admin_screens_allowed?
43
+
44
+ # Links to these screens are hidden for such users; this is for the ones typed in the address bar
45
+ if request.format.html? && !request.xhr?
46
+ redirect_to kaui_engine.home_path, flash: { warning: 'You do not have access to this screen.' }
47
+ else
48
+ head :forbidden
49
+ end
50
+ end
51
+
33
52
  def check_for_redirect_to_tenant_screen
34
53
  unless Kaui.user_assigned_valid_tenant?(current_user, session)
35
54
  session[:kb_tenant_id] = nil
@@ -46,7 +65,7 @@ class Kaui::EngineController < ApplicationController
46
65
  if current_user.root?
47
66
  Kaui::Tenant.all.map(&:kb_tenant_id)
48
67
  else
49
- Kaui::AllowedUser.preload(:kaui_tenants).find_by_kb_username(current_user.kb_username).kaui_tenants.map(&:kb_tenant_id)
68
+ Kaui::AllowedUser.preload(:kaui_tenants).find_by_kb_username(current_user.kb_username)&.kaui_tenants&.map(&:kb_tenant_id) || []
50
69
  end
51
70
  end
52
71
 
@@ -32,8 +32,9 @@ module Kaui
32
32
  kb_params[:startDate] = Date.parse(start_date).strftime('%Y-%m-%d') if start_date
33
33
  kb_params[:endDate] = Date.parse(end_date).strftime('%Y-%m-%d') if end_date
34
34
  query_string = remapping_addvanced_search_fields(query_string, Kaui::Invoice::ADVANCED_SEARCH_NAME_CHANGES)
35
+ include_components = columns.intersect?(Kaui::Invoice::COMPONENT_COLUMNS)
35
36
  invoices = if account_id.present? && query_string.blank?
36
- Kaui::Account.paginated_invoices(account_id, nil, nil, 'NONE', options_for_klient).map! { |invoice| Kaui::Invoice.build_from_raw_invoice(invoice) }
37
+ Kaui::Account.paginated_invoices(account_id, nil, nil, 'NONE', options_for_klient, include_components).map! { |invoice| Kaui::Invoice.build_from_raw_invoice(invoice) }
37
38
  else
38
39
  Kaui::Invoice.list_or_search(query_string, 0, MAXIMUM_NUMBER_OF_RECORDS_DOWNLOAD, options_for_klient.merge(params: kb_params))
39
40
  end
@@ -59,6 +60,9 @@ module Kaui
59
60
 
60
61
  def pagination
61
62
  cached_options_for_klient = options_for_klient
63
+ # Amount and balance are only available when the invoice components are loaded (only for the invoices of the page):
64
+ # the UI asks for them only when at least one of these columns is visible
65
+ include_components = params[:include_invoice_components] == 'true'
62
66
 
63
67
  searcher = lambda do |search_key, offset, limit|
64
68
  account = begin
@@ -70,7 +74,7 @@ module Kaui
70
74
  search_key = remapping_addvanced_search_fields(search_key, Kaui::Invoice::ADVANCED_SEARCH_NAME_CHANGES)
71
75
  Kaui::Invoice.list_or_search(search_key, offset, limit, cached_options_for_klient)
72
76
  else
73
- Kaui::Account.paginated_invoices(search_key, offset, limit, 'NONE', cached_options_for_klient).map! { |invoice| Kaui::Invoice.build_from_raw_invoice(invoice) }
77
+ Kaui::Account.paginated_invoices(search_key, offset, limit, 'NONE', cached_options_for_klient, include_components).map! { |invoice| Kaui::Invoice.build_from_raw_invoice(invoice) }
74
78
  end
75
79
  end
76
80
 
@@ -0,0 +1,173 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kaui
4
+ # Shared Cognito token + Kill Bill authentication flow of the Cognito token exchange (see Kaui::SsoCognitoController).
5
+ # It can be included by other controllers (e.g. custom ones living in a Kaui deployment) to get the same login.
6
+ #
7
+ # Two modes, selected by the client:
8
+ #
9
+ # * basic: Cognito ID token + kb_username/kb_password. Kaui logs into Kill Bill with Basic auth. The Kaui user is
10
+ # kb_username (defaults to the email of the token), the tenant comes from kaui_allowed_users.
11
+ # * bearer: Cognito ID token, no kb_password (the Kill Bill instance needs the Cognito realm). Kaui logs into Kill Bill
12
+ # with the Bearer token. The Kaui user is the principal reported by Kill Bill (e.g. cognito:alice@acme.com)
13
+ # and the tenant comes from the tenant api key/secret (tenant_api_key and tenant_api_secret).
14
+ module KbCognitoAuthenticatable
15
+ # An error to report to the client with the given HTTP status
16
+ class Error < StandardError
17
+ attr_reader :status
18
+
19
+ def initialize(message, status)
20
+ super(message)
21
+ @status = status
22
+ end
23
+ end
24
+
25
+ # Name of the session key flagging a session established by the exchange. It is used by killbill-aviate
26
+ # (Aviate::SSO_SESSION_KEY) to display the Aviate sidebar, hence only set here, after reset_session.
27
+ SSO_SESSION_KEY = :aviate_sso
28
+
29
+ private
30
+
31
+ def warden
32
+ request.env['warden']
33
+ end
34
+
35
+ def extract_bearer_token
36
+ auth_header = request.headers['Authorization'].to_s
37
+ token = auth_header.start_with?('Bearer ') ? auth_header.split(' ', 2)[1].to_s.strip : nil
38
+ raise Error.new('Missing or invalid Authorization header', :unauthorized) if token.blank?
39
+
40
+ token
41
+ end
42
+
43
+ # Basic mode when the client sends the Kill Bill password, bearer mode otherwise
44
+ def kb_bearer_mode?
45
+ params[:kb_password].blank?
46
+ end
47
+
48
+ # Returns the authenticated Kaui::User, and signs it in
49
+ def authenticate_kb_user!
50
+ token = extract_bearer_token
51
+ claims = Kaui::CognitoJwtVerifier.verify!(token)
52
+
53
+ if kb_bearer_mode?
54
+ # Check the tenant before logging in, so that a wrong key/secret doesn't leave a session around
55
+ @kb_exchange_tenant = find_tenant_from_api_credentials!
56
+ user, kb_session_id = login_to_kb_with_bearer!(token)
57
+ else
58
+ user, kb_session_id = login_to_kb_with_password!(claims)
59
+ end
60
+
61
+ user.kb_session_id = kb_session_id
62
+ user.save!
63
+
64
+ reset_session
65
+ warden.set_user(user, scope: :user, store: true)
66
+ # Flag the session as signed in through the exchange: killbill-aviate (Aviate::SSO_SESSION_KEY) then displays the
67
+ # Aviate sidebar on the Kaui pages. Set after reset_session, so it only lives as long as this session.
68
+ session[SSO_SESSION_KEY] = true
69
+
70
+ user
71
+ end
72
+
73
+ def login_to_kb_with_password!(claims)
74
+ kb_username = params[:kb_username].presence || claims['email'].to_s.downcase.presence
75
+ raise Error.new('kb_username is required when the token has no email claim', :bad_request) if kb_username.blank?
76
+
77
+ response = Kaui::User.find_permissions(username: kb_username, password: params[:kb_password])
78
+ [Kaui::User.find_or_initialize_by(kb_username:), response.session_id]
79
+ rescue KillBillClient::API::Unauthorized
80
+ raise Error.new('Invalid Kill Bill credentials', :unauthorized)
81
+ end
82
+
83
+ def login_to_kb_with_bearer!(token)
84
+ response = Kaui::User.find_permissions(bearer: token)
85
+ # Key the Kaui user by the principal Kill Bill reports (e.g. cognito:alice@acme.com), not by the bare email:
86
+ # a bearer user never shares the Kaui row, Kill Bill session and tenants of a basic user with the same name
87
+ principal = KillBillClient::Model::Security.find_subject(session_id: response.session_id).principal
88
+ raise Error.new('Kill Bill did not report a principal for this token', :unauthorized) if principal.blank?
89
+
90
+ [Kaui::User.find_or_initialize_by(kb_username: principal), response.session_id]
91
+ rescue KillBillClient::API::Unauthorized
92
+ raise Error.new('Cognito authentication is not enabled on this Kill Bill, or the token is not accepted by its Cognito realm', :unauthorized)
93
+ end
94
+
95
+ # Bearer mode: returns the tenant identified by the api key/secret of the request (nil if none was sent)
96
+ def find_tenant_from_api_credentials!
97
+ api_key = params[:tenant_api_key].presence
98
+ api_secret = params[:tenant_api_secret].presence
99
+ return nil if api_key.nil? && api_secret.nil?
100
+ raise Error.new('tenant_api_key and tenant_api_secret must be sent together', :bad_request) if api_key.nil? || api_secret.nil?
101
+
102
+ tenant = Kaui::Tenant.find_by(api_key:)
103
+ valid = tenant&.api_secret.present? && ActiveSupport::SecurityUtils.secure_compare(tenant.api_secret.to_s, api_secret.to_s)
104
+ raise Error.new('Unknown tenant or invalid tenant api secret', :forbidden) unless valid
105
+
106
+ tenant
107
+ end
108
+
109
+ # Selects the tenant of the session for the given user when possible.
110
+ #
111
+ # In bearer mode, it is the tenant of the api key/secret (the user is allowed on it).
112
+ #
113
+ # In basic mode (kaui_allowed_users):
114
+ # - a single allowed tenant is always selected
115
+ # - with multiple tenants, the `tenant_name` param is used to disambiguate
116
+ # - otherwise, when default_to_first is true, the first tenant is used
117
+ # as a default; when false, the user is left for tenant selection
118
+ def select_tenant_for_user(user, log_prefix:, default_to_first: true)
119
+ return select_tenant_from_api_credentials(user, log_prefix:) if kb_bearer_mode?
120
+
121
+ allowed_user = Kaui::AllowedUser.find_by(kb_username: user.kb_username)
122
+ return unless allowed_user
123
+
124
+ tenants = allowed_user.kaui_tenants
125
+
126
+ if tenants.size == 1
127
+ tenant = tenants.first
128
+ set_tenant_session(tenant)
129
+ Rails.logger.info("#{log_prefix}: Auto-selected tenant #{tenant.name} for user #{user.kb_username}")
130
+ elsif tenants.size > 1 && params[:tenant_name].present?
131
+ tenant = tenants.find { |t| t.name == params[:tenant_name] }
132
+ if tenant
133
+ set_tenant_session(tenant)
134
+ Rails.logger.info("#{log_prefix}: Selected tenant #{tenant.name} for user #{user.kb_username}")
135
+ else
136
+ Rails.logger.warn("#{log_prefix}: Tenant '#{params[:tenant_name]}' not found for user #{user.kb_username}")
137
+ end
138
+ elsif tenants.size > 1 && default_to_first
139
+ tenant = tenants.first
140
+ set_tenant_session(tenant)
141
+ Rails.logger.info("#{log_prefix}: Default-selected first tenant #{tenant.name} for user #{user.kb_username}")
142
+ end
143
+ end
144
+
145
+ # Selects the tenant validated by find_tenant_from_api_credentials! and makes sure the user is allowed on it
146
+ # (so that the Kaui tenant screen lists it)
147
+ def select_tenant_from_api_credentials(user, log_prefix:)
148
+ tenant = @kb_exchange_tenant
149
+ return unless tenant
150
+
151
+ allowed_user = begin
152
+ Kaui::AllowedUser.find_or_create_by!(kb_username: user.kb_username)
153
+ rescue ActiveRecord::RecordNotUnique
154
+ Kaui::AllowedUser.find_by!(kb_username: user.kb_username)
155
+ end
156
+
157
+ begin
158
+ Kaui::AllowedUserTenant.find_or_create_by!(kaui_allowed_user: allowed_user, kaui_tenant: tenant)
159
+ rescue ActiveRecord::RecordNotUnique
160
+ nil # Concurrent exchange for the same user
161
+ end
162
+
163
+ set_tenant_session(tenant)
164
+ Rails.logger.info("#{log_prefix}: Selected tenant #{tenant.name} for user #{user.kb_username}")
165
+ end
166
+
167
+ def set_tenant_session(tenant) # rubocop:disable Naming/AccessorMethodName
168
+ session[:kb_tenant_id] = tenant.kb_tenant_id
169
+ session[:kb_tenant_name] = tenant.name
170
+ session[:tenant_id] = tenant.id
171
+ end
172
+ end
173
+ end
@@ -2,6 +2,9 @@
2
2
 
3
3
  module Kaui
4
4
  class RoleDefinitionsController < Kaui::EngineController
5
+ # Before the tenant selection redirect: the answer must not depend on the selected tenant
6
+ prepend_before_action :require_kaui_admin_screens!
7
+
5
8
  DEFAULT_PAGE_SIZE = 20
6
9
 
7
10
  def index
@@ -106,7 +109,7 @@ module Kaui
106
109
  notice: "Role '#{@role_definition.role}' was successfully created"
107
110
  end
108
111
  else
109
- redirect_to admin_allowed_users_path, notice: 'Role was successfully created'
112
+ redirect_to role_definitions_path, notice: "Role '#{@role_definition.role}' was successfully created"
110
113
  end
111
114
  rescue StandardError => e
112
115
  flash.now[:error] = "Error while creating role: #{as_string(e)}"
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kaui
4
+ # Optional Cognito token exchange: a web application whose users signed in with AWS Cognito can open Kaui for them
5
+ # without a second login (see Kaui::KbCognitoAuthenticatable and Kaui::CognitoJwtVerifier).
6
+ #
7
+ # POST /sso/cognito/exchange (alias: POST /sso/aviate/exchange)
8
+ # Authorization: Bearer <Cognito ID token>
9
+ # body: kb_username/kb_password (basic mode) or tenant_api_key/tenant_api_secret (bearer mode), optionally
10
+ # tenant_name (basic mode) and target (path of the Kaui page to open)
11
+ #
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
16
+
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
41
+
42
+ 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
+ # Verify the token, authenticate against Kill Bill, and establish the Warden session of the Kaui::User
46
+ user = authenticate_kb_user!
47
+ Rails.logger.info("SSO: Authenticated #{user.kb_username} (user ##{user.id})")
48
+
49
+ # Select the tenant if possible. This prevents the redirect to the tenant selection page
50
+ select_tenant_for_user(user, log_prefix: 'SSO', default_to_first: false)
51
+
52
+ render json: { redirectUrl: sso_target_url }, status: :ok
53
+ end
54
+
55
+ # Instead of the sign-in form (they have no Kill Bill password), for the users whose Kill Bill session expired:
56
+ # back to the login page of the application they came from if it is configured, an explanation otherwise
57
+ def session_expired
58
+ login_url = Kaui::CognitoJwtVerifier.login_url
59
+ return redirect_to(login_url, allow_other_host: true) if login_url
60
+
61
+ render layout: false
62
+ end
63
+
64
+ private
65
+
66
+ def render_error(message, status)
67
+ render json: { error: message }, status:
68
+ end
69
+
70
+ def sso_target_url
71
+ # Allow only known internal paths to avoid open redirect vulnerability
72
+ path = params[:target].to_s.strip
73
+ path = '/' if path.blank? || path.include?('..') || path.include?('\\')
74
+
75
+ # Only allow the home page or the known pages (and their sub-paths), home otherwise
76
+ path = '/' unless path == '/' || ALLOWED_TARGETS.any? { |allowed| path == allowed || path.start_with?("#{allowed}/") }
77
+
78
+ # The full URL includes the context path Kaui is mounted at (e.g. /kaui)
79
+ "#{request.protocol}#{request.host_with_port}#{request.script_name}#{path}"
80
+ end
81
+ end
82
+ end
@@ -19,8 +19,11 @@ module Kaui
19
19
  tenant = KillBillClient.api_key.nil? ? nil : KillBillClient::Model::Tenant.find_by_api_key(KillBillClient.api_key, session_id: current_user.kb_session_id)
20
20
  if tenant.present?
21
21
  select_tenant_for_tenant_id(tenant.tenant_id, tenant.external_key, nil)
22
- else
22
+ elsif kaui_admin_screens_allowed?
23
23
  redirect_to new_admin_tenant_path
24
+ else
25
+ # Not for them to create (and redirecting elsewhere would loop back here): show the empty list
26
+ flash.now[:warning] = 'No tenant is available for your user.'
24
27
  end
25
28
  when 1
26
29
  # If there is only one tenant defined we skip the screen and set the tenant for the user
@@ -2,7 +2,10 @@
2
2
 
3
3
  module Kaui
4
4
  class Invoice < KillBillClient::Model::Invoice
5
- TABLE_IGNORE_COLUMNS = %w[amount balance credit_adj refund_adj items is_parent_invoice parent_invoice_id parent_account_id audit_logs bundle_keys].freeze
5
+ TABLE_IGNORE_COLUMNS = %w[credit_adj refund_adj items is_parent_invoice parent_invoice_id parent_account_id audit_logs bundle_keys].freeze
6
+ # Columns that are only populated when the invoice components are loaded: the paginated account invoices API
7
+ # returns shallow invoices (amount and balance are 0) unless it is asked to include the invoice components.
8
+ COMPONENT_COLUMNS = %w[amount balance].freeze
6
9
  # Columns shown by default on the Invoices list screen (demo-friendly defaults); the rest remain
7
10
  # available but hidden until the user opts in via "Edit Columns".
8
11
  DEFAULT_VISIBLE_COLUMNS = %w[invoice_number invoice_id status invoice_date target_date currency account_id].freeze
@@ -6,6 +6,9 @@ module Kaui
6
6
  class User < ApplicationRecord
7
7
  devise :killbill_authenticatable, :killbill_registerable
8
8
 
9
+ # Principal prefix reported by the Cognito realm of Kill Bill for the users who signed in with a Cognito token (bearer mode of the exchange)
10
+ COGNITO_PRINCIPAL_PREFIX = 'cognito:'
11
+
9
12
  # Managed by Devise
10
13
  attr_accessor :password
11
14
 
@@ -29,6 +32,11 @@ module Kaui
29
32
  false
30
33
  end
31
34
 
35
+ # True for the users signed in through the Cognito token exchange without Kill Bill credentials: they have no password to sign in again
36
+ def cognito_principal?
37
+ kb_username.to_s.start_with?(COGNITO_PRINCIPAL_PREFIX)
38
+ end
39
+
32
40
  def root?
33
41
  Kaui.root_username == kb_username
34
42
  end
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'jwt'
4
+ require 'net/http'
5
+ require 'json'
6
+
7
+ module Kaui
8
+ # Verifies AWS Cognito tokens (ID or access tokens) for the optional Cognito token exchange (see Kaui::SsoCognitoController).
9
+ #
10
+ # The feature is disabled unless an issuer and at least one app client id are configured. Each setting can be set
11
+ # either as a system property (JRuby/Tomcat) or as an environment variable (containers):
12
+ #
13
+ # issuer: -Dkaui.cognito.issuer=https://cognito-idp.<region>.amazonaws.com/<user-pool-id>
14
+ # KAUI_COGNITO_ISSUER
15
+ # client ids: -Dkaui.cognito.client_ids=<id1>,<id2> (or the legacy single -Dkaui.cognito.client_id=<id>)
16
+ # KAUI_COGNITO_CLIENT_IDS=<id1>,<id2> (or KAUI_COGNITO_CLIENT_ID=<id>)
17
+ # login url: (optional) -Dkaui.cognito.login_url=https://app.example.com/login
18
+ # KAUI_COGNITO_LOGIN_URL
19
+ # where to send the users of the exchange when their Kill Bill session expired
20
+ class CognitoJwtVerifier
21
+ # Minimum delay (in seconds) between two refreshes of the JWKS triggered by an unknown 'kid'
22
+ JWKS_MIN_REFRESH_INTERVAL = 60
23
+ JWKS_TIMEOUT = 5
24
+
25
+ JwksEntry = Struct.new(:keys, :fetched_at)
26
+
27
+ JWKS_CACHE = Concurrent::Map.new
28
+ JWKS_LOCK = Mutex.new
29
+
30
+ class << self
31
+ def configured?
32
+ issuer.present? && client_ids.any?
33
+ end
34
+
35
+ # Cognito issuer URL (user pool), e.g. https://cognito-idp.{region}.amazonaws.com/{user-pool-id}
36
+ def issuer
37
+ config_value('kaui.cognito.issuer', 'KAUI_COGNITO_ISSUER').to_s.strip.chomp('/').presence
38
+ end
39
+
40
+ # Accepted Cognito app client ids (the 'aud' of ID tokens)
41
+ def client_ids
42
+ from_properties = split_ids(system_property('kaui.cognito.client_ids')) + split_ids(system_property('kaui.cognito.client_id'))
43
+ return from_properties.uniq if from_properties.any?
44
+
45
+ (split_ids(ENV.fetch('KAUI_COGNITO_CLIENT_IDS', nil)) + split_ids(ENV.fetch('KAUI_COGNITO_CLIENT_ID', nil))).uniq
46
+ end
47
+
48
+ # Where to send the users who signed in through the exchange when their Kill Bill session expired (nil if unset or
49
+ # not an http(s) URL). They have no Kill Bill password: they must sign in again in the application they came from.
50
+ def login_url
51
+ url = config_value('kaui.cognito.login_url', 'KAUI_COGNITO_LOGIN_URL').to_s.strip
52
+ URI.parse(url).is_a?(URI::HTTP) ? url : nil
53
+ rescue URI::InvalidURIError
54
+ nil
55
+ end
56
+
57
+ # Returns the verified claims or raises JWT::DecodeError (including JWT::ExpiredSignature)
58
+ def verify!(jwt_token)
59
+ raise JWT::DecodeError, 'Cognito token verification is not configured' unless configured?
60
+
61
+ # Extract the header WITHOUT verification - only to get the 'kid' for key lookup.
62
+ # This is safe because the full verification happens below with the public key.
63
+ header = begin
64
+ JWT.decode(jwt_token, nil, false)[1]
65
+ rescue JWT::DecodeError => e
66
+ raise JWT::DecodeError, "Invalid JWT format: #{e.message}"
67
+ end
68
+
69
+ kid = header['kid']
70
+ raise JWT::DecodeError, 'Missing kid in token header' if kid.nil?
71
+
72
+ jwk = find_jwk(kid)
73
+ raise JWT::DecodeError, "Unknown key ID: #{kid}" if jwk.nil?
74
+
75
+ decoded_token = JWT.decode(
76
+ jwt_token,
77
+ JWT::JWK.import(jwk).public_key,
78
+ true,
79
+ {
80
+ algorithm: 'RS256',
81
+ iss: issuer,
82
+ verify_iss: true,
83
+ aud: client_ids,
84
+ verify_aud: true
85
+ }
86
+ )
87
+
88
+ claims = decoded_token[0]
89
+ validate_cognito_claims!(claims)
90
+ claims
91
+ end
92
+
93
+ # Drops the cached JWKS (mostly for tests)
94
+ def clear_cache!
95
+ JWKS_CACHE.clear
96
+ end
97
+
98
+ # Fetches the JWKS (JSON Web Key Set) of the issuer from Cognito
99
+ def fetch_jwks
100
+ uri = URI("#{issuer}/.well-known/jwks.json")
101
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: JWKS_TIMEOUT, read_timeout: JWKS_TIMEOUT) do |http|
102
+ http.request(Net::HTTP::Get.new(uri))
103
+ end
104
+ raise "Failed to fetch JWKS from Cognito: #{response.code} #{response.message}" unless response.is_a?(Net::HTTPSuccess)
105
+
106
+ JSON.parse(response.body).fetch('keys')
107
+ rescue StandardError => e
108
+ Rails.logger.error("Failed to fetch JWKS: #{e.message}")
109
+ raise
110
+ end
111
+
112
+ private
113
+
114
+ # Finds a JWK by its key ID. The JWKS is cached, and refetched (at most once per JWKS_MIN_REFRESH_INTERVAL)
115
+ # when the key ID is unknown, to pick up Cognito key rotations without restarting Kaui.
116
+ def find_jwk(kid)
117
+ entry = JWKS_CACHE[issuer] || refresh_jwks(nil)
118
+ jwk = entry.keys.find { |key| key['kid'] == kid }
119
+ return jwk if jwk
120
+
121
+ refresh_jwks(entry)
122
+ JWKS_CACHE[issuer]&.keys&.find { |key| key['kid'] == kid }
123
+ end
124
+
125
+ # Refetches the JWKS, unless another thread already did it, or it was fetched too recently
126
+ def refresh_jwks(stale_entry)
127
+ JWKS_LOCK.synchronize do
128
+ current = JWKS_CACHE[issuer]
129
+ return current if current && (!current.equal?(stale_entry) || (now - current.fetched_at) < JWKS_MIN_REFRESH_INTERVAL)
130
+
131
+ keys = begin
132
+ fetch_jwks
133
+ rescue StandardError
134
+ # Keep serving (and don't hammer Cognito for) the keys we already have; fail only if we have none
135
+ raise if current.nil?
136
+
137
+ current.keys
138
+ end
139
+ JWKS_CACHE[issuer] = JwksEntry.new(keys, now)
140
+ end
141
+ end
142
+
143
+ def now
144
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
145
+ end
146
+
147
+ # Validates Cognito-specific claims in the token
148
+ def validate_cognito_claims!(claims)
149
+ # Verify token_use is either 'id' (ID token) or 'access' (access token)
150
+ token_use = claims['token_use']
151
+ raise JWT::DecodeError, "Invalid token_use: #{token_use}" unless %w[id access].include?(token_use)
152
+ end
153
+
154
+ def split_ids(value)
155
+ value.to_s.split(',').map(&:strip).compact_blank
156
+ end
157
+
158
+ # System property (JRuby only) first, then environment variable, as in the Kaui standalone initializers
159
+ def config_value(property, env_var)
160
+ system_property(property).presence || ENV.fetch(env_var, nil)
161
+ end
162
+
163
+ def system_property(property)
164
+ defined?(JRUBY_VERSION) ? java.lang.System.getProperty(property) : nil
165
+ end
166
+ end
167
+ end
168
+ end
@@ -12,9 +12,11 @@
12
12
  <!-- Settings Section -->
13
13
  <h5 class="fw-semibold pb-4 text-black-900 pt-4 fs-4 fw-500">Settings</h5>
14
14
  <div class="row row-cols-1 row-cols-md-2 g-4 mb-5">
15
+ <% if kaui_admin_screens_allowed? %>
15
16
  <%= render partial: "kaui/components/dashboard/setting", locals: { path: kaui_engine.admin_tenants_path, icon: "kaui/dashboard/users.svg", title: "Tenant", desc: "Run multiple tenants for each Kill Bill deployment." } %>
16
17
  <%= render partial: "kaui/components/dashboard/setting", locals: { path: kaui_engine.admin_allowed_users_path, icon: "kaui/dashboard/users.svg", title: "Users", desc: "Manage users in Kaui – create user roles, create and edit users, assign roles and tenants to users." } %>
17
18
  <%= render partial: "kaui/components/dashboard/setting", locals: { path: kaui_engine.role_definitions_path, icon: "kaui/dashboard/users.svg", title: "Roles", desc: "View and edit role definitions and the permissions they grant." } %>
19
+ <% end %>
18
20
  <%= render partial: "kaui/components/dashboard/setting", locals: { path: kaui_engine.tags_path, icon: "kaui/dashboard/tags.svg", title: "Tags", desc: "Apply one or more tags to accounts and invoices, a tag being a single value." } %>
19
21
  <%= render partial: "kaui/components/dashboard/setting", locals: { path: kaui_engine.custom_fields_path, icon: "kaui/dashboard/custom-field.svg", title: "Custom Fields", desc: "Create custom fields (key/value pairs) and attach them to objects like accounts, payments." } %>
20
22
  <% if kpm_plugin_installed %>
@@ -58,6 +58,23 @@ $(document).ready(function() {
58
58
  localStorage.setItem(stateKey, JSON.stringify(state));
59
59
  }
60
60
 
61
+ // Amount and balance are only fetched (for the invoices of the current page) when one of these columns is visible
62
+ var componentsRequested = false;
63
+ function componentColumnsVisible() {
64
+ var visible = false;
65
+ try {
66
+ $('#invoices-table').DataTable().columns().every(function() {
67
+ var title = $(this.header()).text().trim().toLowerCase();
68
+ if ((title === 'amount' || title === 'balance') && this.visible()) {
69
+ visible = true;
70
+ }
71
+ });
72
+ } catch (e) {
73
+ visible = false;
74
+ }
75
+ return visible;
76
+ }
77
+
61
78
  var table = $('#invoices-table').DataTable({
62
79
  "colReorder": {
63
80
  "enable": false
@@ -88,6 +105,8 @@ $(document).ready(function() {
88
105
  url: "<%= invoices_pagination_path(:ordering => @ordering, :format => :json, :advance_search_query => @advance_search_query) %>",
89
106
  data: function(d) {
90
107
  d.colum_order = $('#invoices-table').DataTable().colReorder.order();
108
+ componentsRequested = componentColumnsVisible();
109
+ d.include_invoice_components = componentsRequested;
91
110
  },
92
111
  dataSrc: function(json) {
93
112
  var colOrder = table.colReorder.order();
@@ -177,5 +196,12 @@ $(document).ready(function() {
177
196
  <% end %>
178
197
  populateSearchLabelsFromUrl();
179
198
  });
199
+
200
+ // Amount or balance has been made visible since the data was requested: load them for the current page
201
+ table.on('column-visibility.dt', function() {
202
+ if (!componentsRequested && componentColumnsVisible()) {
203
+ table.ajax.reload(null, false);
204
+ }
205
+ });
180
206
  });
181
207
  <% end %>
@@ -68,7 +68,8 @@
68
68
 
69
69
  <!-- Settings Icon -->
70
70
  <% if user_signed_in? && session[:tenant_id].present? %>
71
- <%= link_to kaui_engine.admin_tenant_path(session[:tenant_id]), class: 'd-flex align-items-center gap-2 border admin-info text-decoration-none' do %>
71
+ <%# The tenant screen is reserved to Kaui administrators: the other users get the settings they can use %>
72
+ <%= link_to (kaui_admin_screens_allowed? ? kaui_engine.admin_tenant_path(session[:tenant_id]) : kaui_engine.tag_definitions_path), class: 'd-flex align-items-center gap-2 border admin-info text-decoration-none' do %>
72
73
  <%= image_tag 'kaui/header/cog_icon.svg', alt: 'setting' %>
73
74
  <% if user_signed_in? %>
74
75
  <div class="text-sm text-nowrap">
@@ -1,10 +1,13 @@
1
1
  <% identifier = "Settings" %>
2
2
 
3
+ <%# Users signed in through the Cognito token exchange (no Kill Bill credentials) only see the admin screens when their Kill Bill permissions allow it (e.g. a *:* owner role) %>
4
+ <% show_admin_screens = kaui_admin_screens_allowed? %>
5
+
3
6
  <% menu_items = [
4
- session[:tenant_id].present? ? { label: session["kb_tenant_name"], path: kaui_engine.admin_tenant_path(session[:tenant_id]), controller_suffix: "#{session[:tenant_id]}", icon_path: 'kaui/setting/account.svg' } : nil,
5
- { label: 'Tenants', path: kaui_engine.admin_tenants_path, controller_suffix: 'admin_tenants', icon_path: 'kaui/setting/tenants.svg' },
6
- { label: 'Users', path: kaui_engine.admin_allowed_users_path, controller_suffix: 'admin_allowed_users', icon_path: 'kaui/setting/users.svg' },
7
- { label: 'Roles', path: kaui_engine.role_definitions_path, controller_suffix: 'role_definitions', icon_path: 'kaui/setting/users.svg' },
7
+ session[:tenant_id].present? && show_admin_screens ? { label: session["kb_tenant_name"], path: kaui_engine.admin_tenant_path(session[:tenant_id]), controller_suffix: "#{session[:tenant_id]}", icon_path: 'kaui/setting/account.svg' } : nil,
8
+ show_admin_screens ? { label: 'Tenants', path: kaui_engine.admin_tenants_path, controller_suffix: 'admin_tenants', icon_path: 'kaui/setting/tenants.svg' } : nil,
9
+ show_admin_screens ? { label: 'Users', path: kaui_engine.admin_allowed_users_path, controller_suffix: 'admin_allowed_users', icon_path: 'kaui/setting/users.svg' } : nil,
10
+ show_admin_screens ? { label: 'Roles', path: kaui_engine.role_definitions_path, controller_suffix: 'role_definitions', icon_path: 'kaui/setting/users.svg' } : nil,
8
11
  { label: 'Tags', path: kaui_engine.tags_path, controller_suffix: 'tags', icon_path: 'kaui/setting/tags.svg' },
9
12
  { label: 'Tag Definitions', path: kaui_engine.tag_definitions_path, controller_suffix: 'tag_definitions', icon_path: 'kaui/setting/tag-definitions.svg' },
10
13
  { label: 'Custom Fields', path: kaui_engine.custom_fields_path, controller_suffix: 'custom_fields', icon_path: 'kaui/setting/custom-field.svg' }
@@ -0,0 +1,26 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Session expired</title>
7
+ <style>
8
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f5f6f8; color: #212529; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; }
9
+ .card { background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0, 0, 0, .1); padding: 32px 40px; max-width: 460px; text-align: center; }
10
+ h1 { font-size: 1.4rem; margin: 0 0 12px; }
11
+ p { margin: 0; line-height: 1.5; }
12
+ .hint { margin-top: 20px; padding-top: 12px; border-top: 1px solid #dee2e6; font-size: .8rem; color: #6c757d; }
13
+ code { font-size: .78rem; }
14
+ </style>
15
+ </head>
16
+ <body>
17
+ <div class="card">
18
+ <h1>Your session has expired</h1>
19
+ <p>Please reopen Kaui from the application you came from.</p>
20
+ <p class="hint">
21
+ Administrators: set <code>kaui.cognito.login_url</code> (or <code>KAUI_COGNITO_LOGIN_URL</code>) to the login page
22
+ of your application to send users there automatically instead of showing this page.
23
+ </p>
24
+ </div>
25
+ </body>
26
+ </html>
@@ -29,6 +29,8 @@ module Devise
29
29
  opts[:script_name] = nil
30
30
 
31
31
  route = route(scope)
32
+ # Kill Bill session expired for a user without Kill Bill credentials: tell them to reopen Kaui instead of showing the sign-in form
33
+ route = :sso_cognito_session_expired_url if warden_options[:reason] == :cognito_session_expired
32
34
 
33
35
  opts[:format] = request_format unless skip_format?
34
36
 
@@ -77,7 +77,8 @@ Warden::Manager.after_set_user do |user, auth, opts|
77
77
  unless user.authenticated_with_killbill?
78
78
  scope = opts[:scope]
79
79
  auth.logout(scope)
80
- throw(:warden, scope:, reason: 'Kill Bill session expired')
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')
81
82
  end
82
83
  end
83
84
 
data/config/routes.rb CHANGED
@@ -24,6 +24,12 @@ Kaui::Engine.routes.draw do
24
24
  root to: 'home#index', as: 'kaui'
25
25
  get '/500', to: 'errors#show', code: 500
26
26
 
27
+ # Optional Cognito token exchange (disabled unless configured, see Kaui::CognitoJwtVerifier).
28
+ # /sso/aviate/exchange is kept as an alias for existing clients.
29
+ post '/sso/cognito/exchange' => 'sso_cognito#exchange', :as => 'sso_cognito_exchange'
30
+ post '/sso/aviate/exchange' => 'sso_cognito#exchange', :as => 'sso_aviate_exchange'
31
+ get '/sso/cognito/session_expired' => 'sso_cognito#session_expired', :as => 'sso_cognito_session_expired'
32
+
27
33
  scope '/accounts' do
28
34
  post '/pagination' => 'accounts#pagination', :as => 'accounts_pagination'
29
35
  get '/validate_external_key' => 'accounts#validate_external_key', :as => 'accounts_validate_external_key'
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.29'
4
+ VERSION = '4.0.31'
5
5
  end
data/lib/kaui.rb CHANGED
@@ -174,7 +174,7 @@ module Kaui
174
174
  when 'auth_amount', 'captured_amount', 'purchased_amount', 'refunded_amount', 'credited_amount'
175
175
  view_context.humanized_money_with_symbol(payment&.send("#{attr.downcase}_to_money"))
176
176
  when 'payment_number'
177
- view_context.link_to(payment.payment_number, view_context.url_for(controller: :payments, action: :show, account_id: payment.account_id, id: payment.payment_id))
177
+ view_context.link_to(payment.payment_number, view_context.url_for(controller: :payments, action: :show, account_id: payment.account_id, id: payment.payment_id), class: 'payment-number-link')
178
178
  when 'payment_date'
179
179
  view_context.format_date(payment.payment_date, account&.time_zone)
180
180
  when 'status'
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.29
4
+ version: 4.0.31
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-10-29 00:00:00.000000000 Z
11
+ date: 2026-11-25 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: actionpack
@@ -459,6 +459,7 @@ files:
459
459
  - app/controllers/kaui/invoice_items_controller.rb
460
460
  - app/controllers/kaui/invoice_tags_controller.rb
461
461
  - app/controllers/kaui/invoices_controller.rb
462
+ - app/controllers/kaui/kb_cognito_authenticatable.rb
462
463
  - app/controllers/kaui/login_proxy_controller.rb
463
464
  - app/controllers/kaui/payment_methods_controller.rb
464
465
  - app/controllers/kaui/payments_controller.rb
@@ -467,6 +468,7 @@ files:
467
468
  - app/controllers/kaui/registrations_controller.rb
468
469
  - app/controllers/kaui/role_definitions_controller.rb
469
470
  - app/controllers/kaui/sessions_controller.rb
471
+ - app/controllers/kaui/sso_cognito_controller.rb
470
472
  - app/controllers/kaui/subscriptions_controller.rb
471
473
  - app/controllers/kaui/tag_definitions_controller.rb
472
474
  - app/controllers/kaui/tags_controller.rb
@@ -529,6 +531,7 @@ files:
529
531
  - app/models/kaui/user_role.rb
530
532
  - app/services/dependencies/aviate.rb
531
533
  - app/services/dependencies/kenui.rb
534
+ - app/services/kaui/cognito_jwt_verifier.rb
532
535
  - app/views/kaui/account_children/index.html.erb
533
536
  - app/views/kaui/account_custom_fields/index.html.erb
534
537
  - app/views/kaui/account_emails/_account_emails_table.html.erb
@@ -670,6 +673,7 @@ files:
670
673
  - app/views/kaui/sessions/_form.html.erb
671
674
  - app/views/kaui/sessions/new.html.erb
672
675
  - app/views/kaui/shared/_advanced_search_filterbar.html.erb
676
+ - app/views/kaui/sso_cognito/session_expired.html.erb
673
677
  - app/views/kaui/subscriptions/_cancel_by_date_modal.html.erb
674
678
  - app/views/kaui/subscriptions/_edit_form.html.erb
675
679
  - app/views/kaui/subscriptions/_form.html.erb