command_tower 0.24.0 → 0.25.0

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.
Files changed (150) hide show
  1. checksums.yaml +4 -4
  2. data/app/auth/command_tower/auth/auth_context.rb +17 -4
  3. data/app/controllers/command_tower/admin/users/impersonation_sessions_controller.rb +2 -1
  4. data/app/controllers/command_tower/application_controller.rb +18 -1
  5. data/app/controllers/command_tower/auth/email/availability_controller.rb +1 -0
  6. data/app/controllers/command_tower/auth/impersonation_session_controller.rb +2 -1
  7. data/app/controllers/command_tower/auth/password_check_controller.rb +31 -0
  8. data/app/controllers/command_tower/auth/password_recovery_session/create_controller.rb +3 -0
  9. data/app/controllers/command_tower/auth/password_reset/reset_controller.rb +4 -1
  10. data/app/controllers/command_tower/auth/password_reset/send_controller.rb +6 -2
  11. data/app/controllers/command_tower/auth/password_reset/validate_controller.rb +4 -1
  12. data/app/controllers/command_tower/auth/plain_text/login_controller.rb +2 -1
  13. data/app/controllers/command_tower/auth/register_controller.rb +9 -0
  14. data/app/controllers/command_tower/auth/signup_session/create_controller.rb +3 -0
  15. data/app/controllers/command_tower/auth/username/availability_controller.rb +1 -0
  16. data/app/controllers/command_tower/me/username_availability_controller.rb +37 -0
  17. data/app/controllers/command_tower/me/username_controller.rb +38 -0
  18. data/app/controllers/concerns/command_tower/api/application_response_renderer.rb +30 -6
  19. data/app/controllers/concerns/command_tower/auth/legacy_contract_boundary.rb +24 -0
  20. data/app/controllers/concerns/command_tower/auth/password_recovery_session_boundary.rb +2 -0
  21. data/app/controllers/concerns/command_tower/auth/signup_session_boundary.rb +2 -0
  22. data/app/controllers/concerns/command_tower/execution/http_boundary.rb +22 -1
  23. data/app/deserializers/command_tower/deserializers/auth/password_check_deserializer.rb +21 -0
  24. data/app/deserializers/command_tower/deserializers/auth/password_reset/reset_deserializer.rb +3 -2
  25. data/app/deserializers/command_tower/deserializers/auth/register_deserializer.rb +10 -12
  26. data/app/deserializers/command_tower/deserializers/me/change_password_deserializer.rb +6 -4
  27. data/app/deserializers/command_tower/deserializers/me/update_username_deserializer.rb +21 -0
  28. data/app/errors/command_tower/errors/account/username_change_not_allowed_error.rb +17 -0
  29. data/app/errors/command_tower/errors/account/username_taken_error.rb +21 -0
  30. data/app/errors/command_tower/errors/auth/auth_rate_limited_error.rb +25 -0
  31. data/app/errors/command_tower/errors/auth/session_expired_error.rb +18 -0
  32. data/app/errors/command_tower/errors/auth/session_revoked_error.rb +18 -0
  33. data/app/errors/command_tower/errors/insecure_jwt_secret_error.rb +22 -0
  34. data/app/jobs/command_tower/auth/device_sessions/purge_ended_job.rb +16 -0
  35. data/app/jobs/command_tower/auth/email_verification/issue_job.rb +23 -0
  36. data/app/jobs/command_tower/auth/password_reset/issue_job.rb +23 -0
  37. data/app/models/command_tower/auth/device_session.rb +32 -0
  38. data/app/models/user.rb +10 -1
  39. data/app/models/user_secret.rb +17 -4
  40. data/app/serializers/command_tower/serializers/auth/email_verification/message_response_serializer.rb +5 -2
  41. data/app/serializers/command_tower/serializers/auth/identity_policy_serializer.rb +16 -3
  42. data/app/serializers/command_tower/serializers/auth/login_response_serializer.rb +6 -6
  43. data/app/serializers/command_tower/serializers/auth/password_check_serializer.rb +17 -0
  44. data/app/serializers/command_tower/serializers/auth/register_response_serializer.rb +11 -2
  45. data/app/services/command_tower/jwt/authenticate_user.rb +140 -19
  46. data/app/services/command_tower/jwt/authentication_outcome.rb +30 -6
  47. data/app/services/command_tower/jwt/login_create.rb +4 -3
  48. data/app/services/command_tower/secrets/generate.rb +8 -5
  49. data/app/services/command_tower/secrets/verify.rb +6 -5
  50. data/app/services/command_tower/services/account/phone_verification/verify.rb +1 -1
  51. data/app/services/command_tower/services/auth/authenticate_session.rb +15 -1
  52. data/app/services/command_tower/services/auth/device_sessions/revoke_all.rb +27 -0
  53. data/app/services/command_tower/services/auth/device_sessions/start.rb +52 -0
  54. data/app/services/command_tower/services/auth/device_sessions/upgrade_legacy.rb +44 -0
  55. data/app/services/command_tower/services/auth/email_verification/send.rb +23 -29
  56. data/app/services/command_tower/services/auth/email_verification/verify.rb +6 -0
  57. data/app/services/command_tower/services/auth/identity_policy.rb +63 -17
  58. data/app/services/command_tower/services/auth/identity_rate_limits/check_reset_attempt.rb +40 -0
  59. data/app/services/command_tower/services/auth/identity_rate_limits/check_verification_send.rb +61 -0
  60. data/app/services/command_tower/services/auth/identity_rate_limits/check_verify_attempt.rb +39 -0
  61. data/app/services/command_tower/services/auth/issue_session.rb +62 -0
  62. data/app/services/command_tower/services/auth/login_rate_limits/check_ip.rb +38 -0
  63. data/app/services/command_tower/services/auth/login_rate_limits/enforcement.rb +33 -0
  64. data/app/services/command_tower/services/auth/login_rate_limits/fail_open.rb +50 -0
  65. data/app/services/command_tower/services/auth/login_rate_limits/lockout.rb +131 -0
  66. data/app/services/command_tower/services/auth/omit_body_token.rb +30 -0
  67. data/app/services/command_tower/services/auth/password_policy/check.rb +45 -0
  68. data/app/services/command_tower/services/auth/password_policy/check_rate_limit.rb +38 -0
  69. data/app/services/command_tower/services/auth/password_recovery/rate_limits/check_send.rb +16 -13
  70. data/app/services/command_tower/services/auth/password_reset/reset.rb +21 -14
  71. data/app/services/command_tower/services/auth/password_reset/send.rb +9 -42
  72. data/app/services/command_tower/services/auth/password_reset/token_verification.rb +9 -1
  73. data/app/services/command_tower/services/auth/password_reset/validate.rb +3 -0
  74. data/app/services/command_tower/services/auth/plain_text/login.rb +68 -11
  75. data/app/services/command_tower/services/auth/record_legacy_contract_use.rb +28 -0
  76. data/app/services/command_tower/services/auth/register.rb +19 -13
  77. data/app/services/command_tower/services/auth/signup_rate_limits/check_register_email.rb +39 -0
  78. data/app/services/command_tower/services/auth/tombstone_user.rb +1 -0
  79. data/app/services/command_tower/services/me/capabilities.rb +1 -1
  80. data/app/services/command_tower/services/me/change_password.rb +10 -8
  81. data/app/services/command_tower/services/me/set_username.rb +100 -0
  82. data/app/services/command_tower/services/me/username_change_eligibility.rb +34 -0
  83. data/app/services/command_tower/services/rate_limits/check.rb +1 -1
  84. data/app/services/command_tower/services/rate_limits/clear.rb +18 -0
  85. data/app/services/command_tower/services/rate_limits/peek.rb +23 -0
  86. data/app/services/command_tower/user_attributes/mutate.rb +1 -0
  87. data/app/services/command_tower/username/available.rb +1 -1
  88. data/app/workflows/command_tower/workflows/auth/authentication_response_effects.rb +11 -0
  89. data/app/workflows/command_tower/workflows/auth/device_sessions/purge_ended_workflow.rb +44 -0
  90. data/app/workflows/command_tower/workflows/auth/email_verification/issue_workflow.rb +64 -0
  91. data/app/workflows/command_tower/workflows/auth/email_verification/send_workflow.rb +4 -2
  92. data/app/workflows/command_tower/workflows/auth/identity_error_status.rb +2 -1
  93. data/app/workflows/command_tower/workflows/auth/logout_workflow.rb +12 -0
  94. data/app/workflows/command_tower/workflows/auth/password_check_workflow.rb +34 -0
  95. data/app/workflows/command_tower/workflows/auth/password_reset/issue_workflow.rb +62 -0
  96. data/app/workflows/command_tower/workflows/auth/password_reset/reset_workflow.rb +3 -2
  97. data/app/workflows/command_tower/workflows/auth/password_reset/send_workflow.rb +3 -2
  98. data/app/workflows/command_tower/workflows/auth/password_reset/validate_workflow.rb +3 -2
  99. data/app/workflows/command_tower/workflows/auth/plain_text/login_workflow.rb +27 -8
  100. data/app/workflows/command_tower/workflows/auth/register_session_response.rb +54 -0
  101. data/app/workflows/command_tower/workflows/auth/register_workflow.rb +64 -56
  102. data/app/workflows/command_tower/workflows/auth/session/show_workflow.rb +54 -5
  103. data/app/workflows/command_tower/workflows/auth/session_error_status.rb +4 -0
  104. data/app/workflows/command_tower/workflows/auth/signup_error_status.rb +2 -1
  105. data/app/workflows/command_tower/workflows/impersonation/start_workflow.rb +5 -2
  106. data/app/workflows/command_tower/workflows/impersonation/stop_workflow.rb +4 -2
  107. data/app/workflows/command_tower/workflows/me/error_status.rb +2 -0
  108. data/app/workflows/command_tower/workflows/me/username_availability_workflow.rb +77 -0
  109. data/app/workflows/command_tower/workflows/me/username_workflow.rb +47 -0
  110. data/config/routes.rb +3 -0
  111. data/db/migrate/20261124000002_add_secret_digest_to_user_secrets.rb +8 -0
  112. data/db/migrate/20261124000003_create_command_tower_device_sessions.rb +43 -0
  113. data/docs/api_reference.md +74 -15
  114. data/docs/audit.md +1 -0
  115. data/docs/authentication.md +103 -0
  116. data/docs/bootstrap/08-initializer.md +12 -0
  117. data/docs/bootstrap/09-rbac.md +2 -0
  118. data/docs/bootstrap/11-auth-client-path.md +3 -1
  119. data/docs/change_password_workflow.md +6 -4
  120. data/docs/cookie_authentication_guide.md +17 -1
  121. data/docs/email_verification_workflow.md +6 -0
  122. data/docs/password_reset_workflow.md +10 -2
  123. data/docs/upgrades/0.25.0.md +50 -0
  124. data/docs/upgrades/README.md +2 -0
  125. data/lib/command_tower/authorization/default.yml +6 -0
  126. data/lib/command_tower/configuration/config.rb +6 -0
  127. data/lib/command_tower/configuration/jwt/config.rb +23 -1
  128. data/lib/command_tower/configuration/login/config.rb +14 -0
  129. data/lib/command_tower/configuration/login/rate_limits.rb +125 -0
  130. data/lib/command_tower/configuration/login/strategy/plain_text/config.rb +12 -6
  131. data/lib/command_tower/configuration/login/strategy/plain_text/lockable.rb +14 -2
  132. data/lib/command_tower/configuration/registry/audit/config.rb +14 -0
  133. data/lib/command_tower/configuration/registry/client_compatibility/config.rb +5 -3
  134. data/lib/command_tower/configuration/session/config.rb +61 -0
  135. data/lib/command_tower/configuration/username/config.rb +17 -0
  136. data/lib/command_tower/current.rb +4 -0
  137. data/lib/command_tower/data/NOTICE +8 -0
  138. data/lib/command_tower/data/password-blocklist-100k.txt.gz +0 -0
  139. data/lib/command_tower/engine.rb +1 -0
  140. data/lib/command_tower/execution.rb +5 -1
  141. data/lib/command_tower/install/baseline.rb +2 -0
  142. data/lib/command_tower/jwt/authorization_helper.rb +14 -6
  143. data/lib/command_tower/password_policy/blocklist.rb +53 -0
  144. data/lib/command_tower/version.rb +1 -1
  145. data/lib/command_tower.rb +1 -0
  146. data/lib/tasks/user_secrets.rake +21 -0
  147. data/lib/tasks/users.rake +71 -0
  148. data/spec/factories/device_session.rb +14 -0
  149. data/spec/factories/user_secret.rb +5 -1
  150. metadata +55 -1
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Deserializers
5
+ module Me
6
+ class UpdateUsernameDeserializer < CommandTower::Deserializers::ApplicationDeserializer
7
+ Input = Data.define(:username)
8
+
9
+ def call(params)
10
+ username = params[:username]
11
+ return failure(errors: { message: "missing_required_fields" }) unless username.is_a?(String)
12
+
13
+ username = username.strip
14
+ return failure(errors: { message: "missing_required_fields" }) if username.empty?
15
+
16
+ success(Input.new(username:))
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module Account
6
+ class UsernameChangeNotAllowedError < CommandTower::Errors::ForbiddenError
7
+ def code
8
+ "username_change_not_allowed"
9
+ end
10
+
11
+ def message
12
+ "Username cannot be changed"
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module Account
6
+ class UsernameTakenError < CommandTower::Errors::ValidationError
7
+ def initialize(cause: nil)
8
+ super(details: { username: "has already been taken" }, cause: cause)
9
+ end
10
+
11
+ def code
12
+ "username_taken"
13
+ end
14
+
15
+ def message
16
+ "Username is already taken"
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module Auth
6
+ class AuthRateLimitedError < CommandTower::Errors::ApplicationError
7
+ def initialize(retry_after_seconds: nil)
8
+ super(details: retry_after_seconds ? { retry_after_seconds: retry_after_seconds } : nil)
9
+ end
10
+
11
+ def code
12
+ "auth_rate_limited"
13
+ end
14
+
15
+ def message
16
+ "Too many attempts. Please try again later."
17
+ end
18
+
19
+ def log_level
20
+ :warn
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module Auth
6
+ # The device session passed its idle or absolute timeout.
7
+ class SessionExpiredError < CommandTower::Errors::UnauthorizedError
8
+ def code
9
+ "session_expired"
10
+ end
11
+
12
+ def message
13
+ "Your session has expired. Please sign in again."
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module Auth
6
+ # The device session was signed out, replaced, or no longer exists.
7
+ class SessionRevokedError < CommandTower::Errors::UnauthorizedError
8
+ def code
9
+ "session_revoked"
10
+ end
11
+
12
+ def message
13
+ "Your session has ended. Please sign in again."
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ class InsecureJwtSecretError < ApplicationError
6
+ def code
7
+ "insecure_jwt_secret"
8
+ end
9
+
10
+ def message
11
+ "config.jwt.hmac_secret is blank or the published default. Set a private secret " \
12
+ "(for example ENV SECRET_KEY_BASE) or, only as a temporary escape hatch, " \
13
+ "config.jwt.allow_insecure_default_secret = true " \
14
+ "(ENV #{CommandTower::Configuration::Jwt::Config::ALLOW_INSECURE_ENV})."
15
+ end
16
+
17
+ def log_level
18
+ :error
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Auth
5
+ module DeviceSessions
6
+ # Scheduled by the host (see authentication.md). Takes no arguments.
7
+ class PurgeEndedJob < CommandTower::ApplicationJob
8
+ queue_as :default
9
+
10
+ def perform
11
+ CommandTower::Workflows::Auth::DeviceSessions::PurgeEndedWorkflow.call_from_job(job: self)
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Auth
5
+ module EmailVerification
6
+ # Generates and emails an email-verification code off the request path. The
7
+ # only argument is the user id; the code is generated inside the job and
8
+ # never travels through the queue or its logs.
9
+ class IssueJob < CommandTower::ApplicationJob
10
+ queue_as :default
11
+
12
+ self.log_arguments = false
13
+
14
+ def perform(user_id)
15
+ CommandTower::Workflows::Auth::EmailVerification::IssueWorkflow.call_from_job(
16
+ job: self,
17
+ user_id: user_id
18
+ )
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Auth
5
+ module PasswordReset
6
+ # Issues a reset token and emails it, off the request path. The only
7
+ # argument is the normalized email; the token is generated inside the job
8
+ # and never travels through the queue or its logs.
9
+ class IssueJob < CommandTower::ApplicationJob
10
+ queue_as :default
11
+
12
+ self.log_arguments = false
13
+
14
+ def perform(normalized_email)
15
+ CommandTower::Workflows::Auth::PasswordReset::IssueWorkflow.call_from_job(
16
+ job: self,
17
+ email: normalized_email
18
+ )
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Auth
5
+ # One signed-in device. `public_id` is carried in the JWT as `sid`.
6
+ class DeviceSession < CommandTower::ApplicationRecord
7
+ self.table_name = "command_tower_device_sessions"
8
+
9
+ REVOKED_REASONS = %w[logout password_reset password_change admin_mutation tombstone replaced].freeze
10
+
11
+ belongs_to :user
12
+
13
+ before_validation :assign_public_id, on: :create
14
+
15
+ validates :public_id, :last_seen_at, :absolute_expires_at, presence: true
16
+ validates :public_id, uniqueness: true
17
+ validates :revoked_reason, inclusion: { in: REVOKED_REASONS }, allow_nil: true
18
+
19
+ scope :active, -> { where(revoked_at: nil) }
20
+
21
+ def revoked?
22
+ revoked_at.present?
23
+ end
24
+
25
+ private
26
+
27
+ def assign_public_id
28
+ self.public_id = SecureRandom.uuid if public_id.blank?
29
+ end
30
+ end
31
+ end
32
+ end
data/app/models/user.rb CHANGED
@@ -39,8 +39,17 @@ class User < CommandTower::ApplicationRecord
39
39
 
40
40
  scope :not_deleted, -> { where(deleted_at: nil) }
41
41
 
42
- validates :username, uniqueness: { conditions: -> { not_deleted } }
42
+ normalizes :email, with: ->(email) { email.strip.downcase }
43
+
44
+ validates :username, uniqueness: { conditions: -> { not_deleted } }, allow_nil: true
43
45
  validates :email, uniqueness: { conditions: -> { not_deleted } }
46
+ validates :email,
47
+ format: { with: URI::MailTo::EMAIL_REGEXP },
48
+ length: {
49
+ minimum: ->(_user) { CommandTower.config.login.plain_text.email_length_min },
50
+ maximum: ->(_user) { CommandTower.config.login.plain_text.email_length_max }
51
+ },
52
+ if: :will_save_change_to_email?
44
53
 
45
54
  ###
46
55
  # Serialize the roles column to check for inclusion easily
@@ -9,6 +9,7 @@
9
9
  # extra :string(255)
10
10
  # reason :string(255)
11
11
  # secret :string(255)
12
+ # secret_digest :string(64)
12
13
  # use_count :integer default(0)
13
14
  # use_count_max :integer
14
15
  # created_at :datetime not null
@@ -17,8 +18,9 @@
17
18
  #
18
19
  # Indexes
19
20
  #
20
- # index_user_secrets_on_secret (secret) UNIQUE
21
- # index_user_secrets_on_user_id (user_id)
21
+ # index_user_secrets_on_secret (secret) UNIQUE
22
+ # index_user_secrets_on_secret_digest (secret_digest) UNIQUE
23
+ # index_user_secrets_on_user_id (user_id)
22
24
  #
23
25
  # Foreign Keys
24
26
  #
@@ -27,8 +29,19 @@
27
29
  class UserSecret < ApplicationRecord
28
30
  belongs_to :user
29
31
 
30
- def self.find_record(secret:, reason: nil, access_count: true)
31
- params = { secret:, reason: }.compact
32
+ DIGEST_KEY_PURPOSE = "command_tower.user_secret_digest"
33
+
34
+ # Keyed digest of a plaintext secret. Only the digest is persisted.
35
+ def self.digest_for(plaintext)
36
+ OpenSSL::HMAC.hexdigest("SHA256", digest_key, plaintext.to_s)
37
+ end
38
+
39
+ def self.digest_key
40
+ @digest_key ||= Rails.application.key_generator.generate_key(DIGEST_KEY_PURPOSE, 32)
41
+ end
42
+
43
+ def self.find_record(secret:, reason: nil, user: nil, access_count: true)
44
+ params = { secret_digest: digest_for(secret), reason:, user_id: user&.id }.compact
32
45
  record = where(**params).first
33
46
  return { found: false } if record.nil?
34
47
 
@@ -5,8 +5,11 @@ module CommandTower
5
5
  module Auth
6
6
  module EmailVerification
7
7
  class MessageResponseSerializer
8
- def self.serialize(message:)
9
- { message: message }
8
+ # resend_available_at (a Time) is only present on code-request responses.
9
+ def self.serialize(message:, resend_available_at: nil)
10
+ payload = { message: message }
11
+ payload[:resendAvailableAt] = resend_available_at.utc.iso8601 if resend_available_at
12
+ payload
10
13
  end
11
14
  end
12
15
  end
@@ -8,17 +8,25 @@ module CommandTower
8
8
  {
9
9
  password: {
10
10
  minLength: policy[:password][:min_length],
11
- maxLength: policy[:password][:max_length]
11
+ maxLength: policy[:password][:max_length],
12
+ maxBytes: policy[:password][:max_bytes],
13
+ passwordRules: policy[:password][:password_rules],
14
+ rules: serialize_rules(policy[:password][:rules])
12
15
  },
13
16
  email: {
14
17
  minLength: policy[:email][:min_length],
15
- maxLength: policy[:email][:max_length]
18
+ maxLength: policy[:email][:max_length],
19
+ rules: serialize_rules(policy[:email][:rules])
16
20
  },
17
21
  username: {
18
22
  minLength: policy[:username][:min_length],
19
23
  maxLength: policy[:username][:max_length],
20
24
  pattern: policy[:username][:pattern],
21
- patternDescription: policy[:username][:pattern_description]
25
+ patternDescription: policy[:username][:pattern_description],
26
+ rules: serialize_rules(policy[:username][:rules]),
27
+ selfService: policy[:username][:self_service],
28
+ selfChange: policy[:username][:self_change],
29
+ prompt: policy[:username][:prompt]
22
30
  },
23
31
  verificationCode: {
24
32
  length: policy[:verification_code][:length],
@@ -30,6 +38,11 @@ module CommandTower
30
38
  }
31
39
  }
32
40
  end
41
+
42
+ def self.serialize_rules(rules)
43
+ rules.map { |rule| { id: rule[:id], label: rule[:label], check: rule[:check] } }
44
+ end
45
+ private_class_method :serialize_rules
33
46
  end
34
47
  end
35
48
  end
@@ -4,12 +4,12 @@ module CommandTower
4
4
  module Serializers
5
5
  module Auth
6
6
  class LoginResponseSerializer
7
- def self.serialize(user:, token:, token_expires_at:)
8
- {
9
- user: UserSerializer.serialize(user),
10
- token: token,
11
- tokenExpiresAt: token_expires_at
12
- }
7
+ # include_token: false drops `token` from the body (cookie-mode web client); tokenExpiresAt stays.
8
+ def self.serialize(user:, token:, token_expires_at:, include_token: true)
9
+ body = { user: UserSerializer.serialize(user) }
10
+ body[:token] = token if include_token
11
+ body[:tokenExpiresAt] = token_expires_at
12
+ body
13
13
  end
14
14
  end
15
15
  end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Serializers
5
+ module Auth
6
+ class PasswordCheckSerializer
7
+ def self.serialize(valid:, failures:, message:)
8
+ {
9
+ valid: valid,
10
+ failures: failures.map(&:to_s),
11
+ message: message
12
+ }
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -4,11 +4,20 @@ module CommandTower
4
4
  module Serializers
5
5
  module Auth
6
6
  class RegisterResponseSerializer
7
- def self.serialize(user:)
8
- {
7
+ # Without `token_expires_at` the body is the legacy `{ user, message }`. A started session
8
+ # adds the login-shaped `token` and `tokenExpiresAt`; include_token: false drops `token`
9
+ # for the cookie-mode web client (same rule as login).
10
+ def self.serialize(user:, token: nil, token_expires_at: nil, include_token: true, capabilities: nil)
11
+ body = {
9
12
  user: UserSerializer.serialize(user),
10
13
  message: "Account created successfully"
11
14
  }
15
+ return body if token_expires_at.nil?
16
+
17
+ body[:token] = token if include_token
18
+ body[:tokenExpiresAt] = token_expires_at
19
+ body[:capabilities] = capabilities if capabilities
20
+ body
12
21
  end
13
22
  end
14
23
  end
@@ -1,9 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module CommandTower::Jwt
4
- class AuthenticateUser
4
+ class AuthenticateUser # rubocop:disable Metrics/ClassLength
5
5
  INVALID_TOKEN_MSG = "Unauthorized Access. Invalid Authorization token"
6
6
  STALE_TOKEN_MSG = "Unauthorized Access. Token is no longer valid"
7
+ SESSION_EXPIRED_MSG = "Unauthorized Access. Session has expired"
8
+ SESSION_REVOKED_MSG = "Unauthorized Access. Session is no longer valid"
7
9
  EMAIL_VERIFICATION_MSG = "Email must be verified to continue"
8
10
  EMAIL_VERIFICATION_STATUS = 412
9
11
 
@@ -22,27 +24,56 @@ module CommandTower::Jwt
22
24
  return invalid_token if decoded.failure?
23
25
 
24
26
  payload = decoded.payload
27
+ sid = payload[:sid].presence
25
28
 
29
+ sid ? authenticate_session_token(payload, sid) : authenticate_legacy_token(payload)
30
+ end
31
+
32
+ private
33
+
34
+ attr_reader :token, :bypass_email_validation, :with_reset
35
+
36
+ # Tokens minted with a device session: the session row is the source of truth
37
+ # for lifetime. `jwt.ttl` is not applied, so a session token outlives 7 days.
38
+ def authenticate_session_token(payload, sid)
39
+ device_session = CommandTower::Auth::DeviceSession.includes(:user).find_by(public_id: sid.to_s)
40
+ failure = session_failure(device_session, payload)
41
+ return failure if failure
42
+
43
+ user = device_session.user
44
+ failure = user_failure(user, payload)
45
+ return failure if failure
46
+
47
+ touch_last_seen(device_session)
48
+
49
+ generated_token = nil
50
+ impersonation_session_id = payload[:impersonation_session_id].presence
51
+ if with_reset
52
+ generated_token = LoginCreate.(user:, impersonation_session_id:, device_session:).token
53
+ end
54
+
55
+ AuthenticationOutcome.success(
56
+ user:,
57
+ expires_at: session_expires_at(device_session).to_s,
58
+ generated_token:,
59
+ impersonation_session_id:,
60
+ device_session:
61
+ )
62
+ end
63
+
64
+ # Sid-less tokens (issued before device sessions): today's rule, generated_at + jwt.ttl.
65
+ def authenticate_legacy_token(payload)
26
66
  expires_at = expires_at_for(generated_at: payload[:generated_at])
27
67
  return invalid_token if expires_at.nil?
28
68
 
29
69
  user = User.find_by(id: payload[:user_id])
30
- if user.nil? || user.deleted?
31
- log_warn("user_id [#{payload[:user_id]}] was not found. Cannot Continue")
32
- return invalid_token
33
- end
70
+ failure = user_failure(user, payload)
71
+ return failure if failure
34
72
 
35
- unless user.verifier_token == payload[:verifier_token]
36
- return AuthenticationOutcome.failure(msg: STALE_TOKEN_MSG)
37
- end
73
+ return session_revoked if upgraded_row_revoked?(user, payload[:generated_at])
38
74
 
39
- if email_validation_required?(user:)
40
- return AuthenticationOutcome.failure(
41
- msg: EMAIL_VERIFICATION_MSG,
42
- status: EMAIL_VERIFICATION_STATUS,
43
- user:
44
- )
45
- end
75
+ # Only a valid sid-less token reaches here (expired and rejected ones do not count).
76
+ CommandTower::Services::Auth::RecordLegacyContractUse.call(endpoint: "sidless_token")
46
77
 
47
78
  generated_token = nil
48
79
  impersonation_session_id = payload[:impersonation_session_id].presence
@@ -55,16 +86,106 @@ module CommandTower::Jwt
55
86
  user:,
56
87
  expires_at: expires_at.to_s,
57
88
  generated_token:,
58
- impersonation_session_id:
89
+ impersonation_session_id:,
90
+ legacy_generated_at: payload[:generated_at]
59
91
  )
60
92
  end
61
93
 
62
- private
94
+ # A legacy token that was already upgraded has a device session row keyed by
95
+ # (user, generated_at). Revoking that row ends the legacy token too.
96
+ def upgraded_row_revoked?(user, generated_at)
97
+ return false unless CommandTower.config.session.enforce
63
98
 
64
- attr_reader :token, :bypass_email_validation, :with_reset
99
+ row = CommandTower::Auth::DeviceSession.find_by(
100
+ user_id: user.id,
101
+ legacy_generated_at: Time.zone.at(generated_at)
102
+ )
103
+ return false unless row&.revoked?
104
+
105
+ log_info("legacy token's upgraded device session [#{row.id}] is revoked")
106
+ true
107
+ end
108
+
109
+ def session_failure(device_session, payload)
110
+ if device_session.nil?
111
+ log_warn("device session for the presented sid was not found")
112
+ return session_revoked
113
+ end
114
+
115
+ if device_session.user_id.to_s != payload[:user_id].to_s
116
+ log_warn("device session [#{device_session.id}] does not belong to the token's user")
117
+ return session_revoked
118
+ end
119
+
120
+ now = Time.current
121
+ if now > device_session.absolute_expires_at
122
+ log_info("device session [#{device_session.id}] passed its absolute expiry")
123
+ return session_expired
124
+ end
125
+
126
+ # Kill switch: with enforcement off, revoked and idle are skipped; absolute still applies.
127
+ return nil unless CommandTower.config.session.enforce
128
+
129
+ if device_session.revoked?
130
+ log_info("device session [#{device_session.id}] is revoked")
131
+ return session_revoked
132
+ end
133
+
134
+ if now > device_session.last_seen_at + CommandTower.config.session.idle_timeout
135
+ log_info("device session [#{device_session.id}] passed its idle timeout")
136
+ return session_expired
137
+ end
138
+
139
+ nil
140
+ end
141
+
142
+ # Checks shared by session and legacy tokens: deleted user, verifier, email gate.
143
+ def user_failure(user, payload)
144
+ if user.nil? || user.deleted?
145
+ log_warn("user_id [#{payload[:user_id]}] was not found. Cannot Continue")
146
+ return invalid_token
147
+ end
148
+
149
+ unless user.verifier_token == payload[:verifier_token]
150
+ return AuthenticationOutcome.failure(msg: STALE_TOKEN_MSG, code: AuthenticationOutcome::STALE_TOKEN)
151
+ end
152
+
153
+ if email_validation_required?(user:)
154
+ return AuthenticationOutcome.failure(
155
+ msg: EMAIL_VERIFICATION_MSG,
156
+ status: EMAIL_VERIFICATION_STATUS,
157
+ user:,
158
+ code: AuthenticationOutcome::EMAIL_VERIFICATION_REQUIRED
159
+ )
160
+ end
161
+
162
+ nil
163
+ end
164
+
165
+ # At most one write per session per `last_seen_write_interval`; idle precision is ± that interval.
166
+ def touch_last_seen(device_session)
167
+ now = Time.current
168
+ return if device_session.last_seen_at > now - CommandTower.config.session.last_seen_write_interval
169
+
170
+ # Intentional: a throttled heartbeat write must not run validations or bump updated_at.
171
+ device_session.update_columns(last_seen_at: now) # rubocop:disable Rails/SkipsModelValidations
172
+ end
173
+
174
+ def session_expires_at(device_session)
175
+ idle_expires_at = device_session.last_seen_at + CommandTower.config.session.idle_timeout
176
+ [idle_expires_at, device_session.absolute_expires_at].min.to_time
177
+ end
65
178
 
66
179
  def invalid_token
67
- AuthenticationOutcome.failure(msg: INVALID_TOKEN_MSG)
180
+ AuthenticationOutcome.failure(msg: INVALID_TOKEN_MSG, code: AuthenticationOutcome::INVALID_TOKEN)
181
+ end
182
+
183
+ def session_expired
184
+ AuthenticationOutcome.failure(msg: SESSION_EXPIRED_MSG, code: AuthenticationOutcome::SESSION_EXPIRED)
185
+ end
186
+
187
+ def session_revoked
188
+ AuthenticationOutcome.failure(msg: SESSION_REVOKED_MSG, code: AuthenticationOutcome::SESSION_REVOKED)
68
189
  end
69
190
 
70
191
  # Returns nil when the token cannot be trusted to carry a usable expiration.