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.
- checksums.yaml +4 -4
- data/app/auth/command_tower/auth/auth_context.rb +17 -4
- data/app/controllers/command_tower/admin/users/impersonation_sessions_controller.rb +2 -1
- data/app/controllers/command_tower/application_controller.rb +18 -1
- data/app/controllers/command_tower/auth/email/availability_controller.rb +1 -0
- data/app/controllers/command_tower/auth/impersonation_session_controller.rb +2 -1
- data/app/controllers/command_tower/auth/password_check_controller.rb +31 -0
- data/app/controllers/command_tower/auth/password_recovery_session/create_controller.rb +3 -0
- data/app/controllers/command_tower/auth/password_reset/reset_controller.rb +4 -1
- data/app/controllers/command_tower/auth/password_reset/send_controller.rb +6 -2
- data/app/controllers/command_tower/auth/password_reset/validate_controller.rb +4 -1
- data/app/controllers/command_tower/auth/plain_text/login_controller.rb +2 -1
- data/app/controllers/command_tower/auth/register_controller.rb +9 -0
- data/app/controllers/command_tower/auth/signup_session/create_controller.rb +3 -0
- data/app/controllers/command_tower/auth/username/availability_controller.rb +1 -0
- data/app/controllers/command_tower/me/username_availability_controller.rb +37 -0
- data/app/controllers/command_tower/me/username_controller.rb +38 -0
- data/app/controllers/concerns/command_tower/api/application_response_renderer.rb +30 -6
- data/app/controllers/concerns/command_tower/auth/legacy_contract_boundary.rb +24 -0
- data/app/controllers/concerns/command_tower/auth/password_recovery_session_boundary.rb +2 -0
- data/app/controllers/concerns/command_tower/auth/signup_session_boundary.rb +2 -0
- data/app/controllers/concerns/command_tower/execution/http_boundary.rb +22 -1
- data/app/deserializers/command_tower/deserializers/auth/password_check_deserializer.rb +21 -0
- data/app/deserializers/command_tower/deserializers/auth/password_reset/reset_deserializer.rb +3 -2
- data/app/deserializers/command_tower/deserializers/auth/register_deserializer.rb +10 -12
- data/app/deserializers/command_tower/deserializers/me/change_password_deserializer.rb +6 -4
- data/app/deserializers/command_tower/deserializers/me/update_username_deserializer.rb +21 -0
- data/app/errors/command_tower/errors/account/username_change_not_allowed_error.rb +17 -0
- data/app/errors/command_tower/errors/account/username_taken_error.rb +21 -0
- data/app/errors/command_tower/errors/auth/auth_rate_limited_error.rb +25 -0
- data/app/errors/command_tower/errors/auth/session_expired_error.rb +18 -0
- data/app/errors/command_tower/errors/auth/session_revoked_error.rb +18 -0
- data/app/errors/command_tower/errors/insecure_jwt_secret_error.rb +22 -0
- data/app/jobs/command_tower/auth/device_sessions/purge_ended_job.rb +16 -0
- data/app/jobs/command_tower/auth/email_verification/issue_job.rb +23 -0
- data/app/jobs/command_tower/auth/password_reset/issue_job.rb +23 -0
- data/app/models/command_tower/auth/device_session.rb +32 -0
- data/app/models/user.rb +10 -1
- data/app/models/user_secret.rb +17 -4
- data/app/serializers/command_tower/serializers/auth/email_verification/message_response_serializer.rb +5 -2
- data/app/serializers/command_tower/serializers/auth/identity_policy_serializer.rb +16 -3
- data/app/serializers/command_tower/serializers/auth/login_response_serializer.rb +6 -6
- data/app/serializers/command_tower/serializers/auth/password_check_serializer.rb +17 -0
- data/app/serializers/command_tower/serializers/auth/register_response_serializer.rb +11 -2
- data/app/services/command_tower/jwt/authenticate_user.rb +140 -19
- data/app/services/command_tower/jwt/authentication_outcome.rb +30 -6
- data/app/services/command_tower/jwt/login_create.rb +4 -3
- data/app/services/command_tower/secrets/generate.rb +8 -5
- data/app/services/command_tower/secrets/verify.rb +6 -5
- data/app/services/command_tower/services/account/phone_verification/verify.rb +1 -1
- data/app/services/command_tower/services/auth/authenticate_session.rb +15 -1
- data/app/services/command_tower/services/auth/device_sessions/revoke_all.rb +27 -0
- data/app/services/command_tower/services/auth/device_sessions/start.rb +52 -0
- data/app/services/command_tower/services/auth/device_sessions/upgrade_legacy.rb +44 -0
- data/app/services/command_tower/services/auth/email_verification/send.rb +23 -29
- data/app/services/command_tower/services/auth/email_verification/verify.rb +6 -0
- data/app/services/command_tower/services/auth/identity_policy.rb +63 -17
- data/app/services/command_tower/services/auth/identity_rate_limits/check_reset_attempt.rb +40 -0
- data/app/services/command_tower/services/auth/identity_rate_limits/check_verification_send.rb +61 -0
- data/app/services/command_tower/services/auth/identity_rate_limits/check_verify_attempt.rb +39 -0
- data/app/services/command_tower/services/auth/issue_session.rb +62 -0
- data/app/services/command_tower/services/auth/login_rate_limits/check_ip.rb +38 -0
- data/app/services/command_tower/services/auth/login_rate_limits/enforcement.rb +33 -0
- data/app/services/command_tower/services/auth/login_rate_limits/fail_open.rb +50 -0
- data/app/services/command_tower/services/auth/login_rate_limits/lockout.rb +131 -0
- data/app/services/command_tower/services/auth/omit_body_token.rb +30 -0
- data/app/services/command_tower/services/auth/password_policy/check.rb +45 -0
- data/app/services/command_tower/services/auth/password_policy/check_rate_limit.rb +38 -0
- data/app/services/command_tower/services/auth/password_recovery/rate_limits/check_send.rb +16 -13
- data/app/services/command_tower/services/auth/password_reset/reset.rb +21 -14
- data/app/services/command_tower/services/auth/password_reset/send.rb +9 -42
- data/app/services/command_tower/services/auth/password_reset/token_verification.rb +9 -1
- data/app/services/command_tower/services/auth/password_reset/validate.rb +3 -0
- data/app/services/command_tower/services/auth/plain_text/login.rb +68 -11
- data/app/services/command_tower/services/auth/record_legacy_contract_use.rb +28 -0
- data/app/services/command_tower/services/auth/register.rb +19 -13
- data/app/services/command_tower/services/auth/signup_rate_limits/check_register_email.rb +39 -0
- data/app/services/command_tower/services/auth/tombstone_user.rb +1 -0
- data/app/services/command_tower/services/me/capabilities.rb +1 -1
- data/app/services/command_tower/services/me/change_password.rb +10 -8
- data/app/services/command_tower/services/me/set_username.rb +100 -0
- data/app/services/command_tower/services/me/username_change_eligibility.rb +34 -0
- data/app/services/command_tower/services/rate_limits/check.rb +1 -1
- data/app/services/command_tower/services/rate_limits/clear.rb +18 -0
- data/app/services/command_tower/services/rate_limits/peek.rb +23 -0
- data/app/services/command_tower/user_attributes/mutate.rb +1 -0
- data/app/services/command_tower/username/available.rb +1 -1
- data/app/workflows/command_tower/workflows/auth/authentication_response_effects.rb +11 -0
- data/app/workflows/command_tower/workflows/auth/device_sessions/purge_ended_workflow.rb +44 -0
- data/app/workflows/command_tower/workflows/auth/email_verification/issue_workflow.rb +64 -0
- data/app/workflows/command_tower/workflows/auth/email_verification/send_workflow.rb +4 -2
- data/app/workflows/command_tower/workflows/auth/identity_error_status.rb +2 -1
- data/app/workflows/command_tower/workflows/auth/logout_workflow.rb +12 -0
- data/app/workflows/command_tower/workflows/auth/password_check_workflow.rb +34 -0
- data/app/workflows/command_tower/workflows/auth/password_reset/issue_workflow.rb +62 -0
- data/app/workflows/command_tower/workflows/auth/password_reset/reset_workflow.rb +3 -2
- data/app/workflows/command_tower/workflows/auth/password_reset/send_workflow.rb +3 -2
- data/app/workflows/command_tower/workflows/auth/password_reset/validate_workflow.rb +3 -2
- data/app/workflows/command_tower/workflows/auth/plain_text/login_workflow.rb +27 -8
- data/app/workflows/command_tower/workflows/auth/register_session_response.rb +54 -0
- data/app/workflows/command_tower/workflows/auth/register_workflow.rb +64 -56
- data/app/workflows/command_tower/workflows/auth/session/show_workflow.rb +54 -5
- data/app/workflows/command_tower/workflows/auth/session_error_status.rb +4 -0
- data/app/workflows/command_tower/workflows/auth/signup_error_status.rb +2 -1
- data/app/workflows/command_tower/workflows/impersonation/start_workflow.rb +5 -2
- data/app/workflows/command_tower/workflows/impersonation/stop_workflow.rb +4 -2
- data/app/workflows/command_tower/workflows/me/error_status.rb +2 -0
- data/app/workflows/command_tower/workflows/me/username_availability_workflow.rb +77 -0
- data/app/workflows/command_tower/workflows/me/username_workflow.rb +47 -0
- data/config/routes.rb +3 -0
- data/db/migrate/20261124000002_add_secret_digest_to_user_secrets.rb +8 -0
- data/db/migrate/20261124000003_create_command_tower_device_sessions.rb +43 -0
- data/docs/api_reference.md +74 -15
- data/docs/audit.md +1 -0
- data/docs/authentication.md +103 -0
- data/docs/bootstrap/08-initializer.md +12 -0
- data/docs/bootstrap/09-rbac.md +2 -0
- data/docs/bootstrap/11-auth-client-path.md +3 -1
- data/docs/change_password_workflow.md +6 -4
- data/docs/cookie_authentication_guide.md +17 -1
- data/docs/email_verification_workflow.md +6 -0
- data/docs/password_reset_workflow.md +10 -2
- data/docs/upgrades/0.25.0.md +50 -0
- data/docs/upgrades/README.md +2 -0
- data/lib/command_tower/authorization/default.yml +6 -0
- data/lib/command_tower/configuration/config.rb +6 -0
- data/lib/command_tower/configuration/jwt/config.rb +23 -1
- data/lib/command_tower/configuration/login/config.rb +14 -0
- data/lib/command_tower/configuration/login/rate_limits.rb +125 -0
- data/lib/command_tower/configuration/login/strategy/plain_text/config.rb +12 -6
- data/lib/command_tower/configuration/login/strategy/plain_text/lockable.rb +14 -2
- data/lib/command_tower/configuration/registry/audit/config.rb +14 -0
- data/lib/command_tower/configuration/registry/client_compatibility/config.rb +5 -3
- data/lib/command_tower/configuration/session/config.rb +61 -0
- data/lib/command_tower/configuration/username/config.rb +17 -0
- data/lib/command_tower/current.rb +4 -0
- data/lib/command_tower/data/NOTICE +8 -0
- data/lib/command_tower/data/password-blocklist-100k.txt.gz +0 -0
- data/lib/command_tower/engine.rb +1 -0
- data/lib/command_tower/execution.rb +5 -1
- data/lib/command_tower/install/baseline.rb +2 -0
- data/lib/command_tower/jwt/authorization_helper.rb +14 -6
- data/lib/command_tower/password_policy/blocklist.rb +53 -0
- data/lib/command_tower/version.rb +1 -1
- data/lib/command_tower.rb +1 -0
- data/lib/tasks/user_secrets.rake +21 -0
- data/lib/tasks/users.rake +71 -0
- data/spec/factories/device_session.rb +14 -0
- data/spec/factories/user_secret.rb +5 -1
- metadata +55 -1
|
@@ -8,32 +8,93 @@ module CommandTower
|
|
|
8
8
|
validate :identifier, is_a: String, required: true, sensitive: true
|
|
9
9
|
validate :password, is_a: String, required: true, sensitive: true
|
|
10
10
|
|
|
11
|
+
# Digest of a throwaway secret at the cost has_secure_password currently uses
|
|
12
|
+
# (min cost in test). Computed once, on first use after boot.
|
|
13
|
+
def self.dummy_digest
|
|
14
|
+
@dummy_digest ||= begin
|
|
15
|
+
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
|
|
16
|
+
BCrypt::Password.create(SecureRandom.hex(16), cost:).to_s
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# client_ip is optional so callers without a request (console, tests) skip the IP bucket.
|
|
21
|
+
validate :client_ip, is_a: String
|
|
22
|
+
|
|
23
|
+
# Optional device attributes recorded on the device session.
|
|
24
|
+
validate :installation_id, is_a: String
|
|
25
|
+
validate :platform, is_a: String
|
|
26
|
+
validate :app_version, is_a: String
|
|
27
|
+
|
|
11
28
|
def call
|
|
29
|
+
enforce_ip_limit!
|
|
30
|
+
|
|
12
31
|
user = User.not_deleted.where(username: identifier).or(User.not_deleted.where(email: identifier)).first
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
32
|
+
lockout = LoginRateLimits::Lockout.new(subject: LoginRateLimits::Lockout.subject_for(user:, identifier:))
|
|
33
|
+
lock = lockout.status
|
|
34
|
+
|
|
35
|
+
# bcrypt always runs (real or dummy digest) so a locked, known and unknown
|
|
36
|
+
# identifier cost the same, and a lock answers even a correct password.
|
|
37
|
+
authenticated = user ? user.authenticate(password) : dummy_password_match?
|
|
38
|
+
|
|
39
|
+
if lock.locked?
|
|
40
|
+
audit_login_failed(affected_user: user, outcome: "locked")
|
|
41
|
+
rate_limited!(lock.retry_after)
|
|
16
42
|
end
|
|
17
43
|
|
|
18
|
-
if user.
|
|
44
|
+
if user.nil?
|
|
45
|
+
audit_login_failed(affected_user: nil, outcome: "unknown_identifier")
|
|
46
|
+
fail_login!(lockout)
|
|
47
|
+
elsif authenticated
|
|
19
48
|
user.successful_login += 1
|
|
20
49
|
user.password_consecutive_fail = 0
|
|
21
50
|
user.save
|
|
51
|
+
lockout.clear
|
|
22
52
|
else
|
|
23
53
|
user.password_consecutive_fail += 1
|
|
24
54
|
user.save
|
|
25
55
|
log_warn("Valid identifier. Incorrect password. Consecutive Password failures: #{user.password_consecutive_fail}")
|
|
26
56
|
audit_login_failed(affected_user: user, outcome: "invalid_password")
|
|
27
|
-
|
|
57
|
+
fail_login!(lockout)
|
|
28
58
|
end
|
|
29
59
|
|
|
30
60
|
context.user = user
|
|
31
|
-
|
|
32
|
-
context.
|
|
61
|
+
issued = IssueSession.call(user:, installation_id:, platform:, app_version:)
|
|
62
|
+
context.fail!(application_error: issued.errors.first) if issued.failure?
|
|
63
|
+
|
|
64
|
+
context.device_session = issued.data[:device_session]
|
|
65
|
+
context.token = issued.data[:token]
|
|
66
|
+
context.expires_at = issued.data[:expires_at]
|
|
67
|
+
context.installation_id = issued.data[:installation_id]
|
|
68
|
+
context.set_installation_cookie = issued.data[:set_installation_cookie]
|
|
33
69
|
end
|
|
34
70
|
|
|
35
71
|
private
|
|
36
72
|
|
|
73
|
+
def enforce_ip_limit!
|
|
74
|
+
return if client_ip.blank?
|
|
75
|
+
|
|
76
|
+
result = LoginRateLimits::CheckIp.call(client_ip:)
|
|
77
|
+
context.fail!(application_error: result.errors.first) if result.failure?
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# Equalize request-side work with the known-user path: one bcrypt comparison.
|
|
81
|
+
def dummy_password_match?
|
|
82
|
+
BCrypt::Password.new(self.class.dummy_digest).is_password?(password)
|
|
83
|
+
false
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# A failed attempt counts; when it trips the lock the caller is told so (429),
|
|
87
|
+
# with the same answer for known and unknown identifiers.
|
|
88
|
+
def fail_login!(lockout)
|
|
89
|
+
lock = lockout.record_failure
|
|
90
|
+
rate_limited!(lock.retry_after) if lock.locked?
|
|
91
|
+
invalid_credentials!
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def rate_limited!(retry_after)
|
|
95
|
+
context.fail!(application_error: CommandTower::Errors::Auth::AuthRateLimitedError.new(retry_after_seconds: retry_after.to_i.positive? ? retry_after.to_i : nil))
|
|
96
|
+
end
|
|
97
|
+
|
|
37
98
|
def invalid_credentials!
|
|
38
99
|
context.fail!(application_error: CommandTower::Errors::Auth::InvalidCredentialsError.new)
|
|
39
100
|
end
|
|
@@ -41,10 +102,6 @@ module CommandTower
|
|
|
41
102
|
def audit_login_failed(affected_user:, outcome:)
|
|
42
103
|
audit(:login_failed, affected_user:, changes: {}, metadata: { outcome: })
|
|
43
104
|
end
|
|
44
|
-
|
|
45
|
-
def token_expires_at_from_ttl
|
|
46
|
-
CommandTower.config.jwt.ttl.from_now.to_time.to_s
|
|
47
|
-
end
|
|
48
105
|
end
|
|
49
106
|
end
|
|
50
107
|
end
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module CommandTower
|
|
4
|
+
module Services
|
|
5
|
+
module Auth
|
|
6
|
+
# Emits `command_tower.auth.legacy_contract_used` when a client uses part of the auth
|
|
7
|
+
# contract that is deprecated (the signup/recovery sessions, the availability endpoints,
|
|
8
|
+
# the old register shape, or a valid sid-less token). Observation only: it never changes
|
|
9
|
+
# a response. The payload is the endpoint, app version and platform, and nothing else, so
|
|
10
|
+
# no PII reaches the event stream.
|
|
11
|
+
class RecordLegacyContractUse < CommandTower::Services::ApplicationService
|
|
12
|
+
validate :endpoint, is_a: String, required: true
|
|
13
|
+
|
|
14
|
+
def call
|
|
15
|
+
CommandTower::Events.publish(
|
|
16
|
+
category: :auth,
|
|
17
|
+
name: "legacy_contract_used",
|
|
18
|
+
payload: {
|
|
19
|
+
endpoint: endpoint,
|
|
20
|
+
app_version: CommandTower::Current.client_app_version,
|
|
21
|
+
platform: CommandTower::Current.client_platform
|
|
22
|
+
}
|
|
23
|
+
)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
end
|
|
@@ -6,24 +6,27 @@ module CommandTower
|
|
|
6
6
|
class Register < CommandTower::Services::ApplicationService
|
|
7
7
|
EMAIL_TAKEN_FRAGMENT = "already been taken"
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
EMAIL_TAKEN_MESSAGE = "You already have an account with this email. Sign in or reset your password."
|
|
10
|
+
RULE_IDS = { too_short: "min_length", too_long: "max_length", blocklisted: "not_common" }.freeze
|
|
11
|
+
|
|
12
|
+
validate :first_name, is_a: String
|
|
13
|
+
validate :last_name, is_a: String
|
|
14
|
+
validate :username, is_a: String
|
|
12
15
|
validate :email, is_a: String, required: true, sensitive: true
|
|
13
16
|
validate :password, is_a: String, required: true, sensitive: true
|
|
14
|
-
validate :password_confirmation, is_a: String,
|
|
17
|
+
validate :password_confirmation, is_a: String, sensitive: true
|
|
15
18
|
|
|
16
19
|
def call
|
|
17
20
|
errors = credential_errors
|
|
18
21
|
reject!(errors) if errors.any?
|
|
19
22
|
|
|
20
23
|
user = User.new(
|
|
21
|
-
first_name
|
|
22
|
-
last_name
|
|
23
|
-
username
|
|
24
|
+
first_name: first_name.to_s,
|
|
25
|
+
last_name: last_name.to_s,
|
|
26
|
+
username: username.presence,
|
|
24
27
|
email:,
|
|
25
28
|
password:,
|
|
26
|
-
password_confirmation:
|
|
29
|
+
password_confirmation: password_confirmation.presence
|
|
27
30
|
)
|
|
28
31
|
|
|
29
32
|
reject!(persistence_errors(user)) unless user.save
|
|
@@ -41,17 +44,19 @@ module CommandTower
|
|
|
41
44
|
config = plain_text_config
|
|
42
45
|
errors = {}
|
|
43
46
|
|
|
44
|
-
unless email.length
|
|
45
|
-
errors[:email] = "Email length must be between #{config.email_length_min
|
|
47
|
+
unless email.length.between?(config.email_length_min, config.email_length_max)
|
|
48
|
+
errors[:email] = "Email length must be between #{config.email_length_min} and #{config.email_length_max} characters"
|
|
46
49
|
end
|
|
47
50
|
|
|
48
|
-
|
|
49
|
-
|
|
51
|
+
check = CommandTower::Services::Auth::PasswordPolicy::Check.call(password:)
|
|
52
|
+
unless check.data[:valid]
|
|
53
|
+
errors[:password] = CommandTower::Services::Auth::PasswordPolicy::Check.message_for(check.data[:failures])
|
|
54
|
+
errors[:passwordRulesFailed] = check.data[:failures].filter_map { RULE_IDS[_1] }
|
|
50
55
|
end
|
|
51
56
|
|
|
52
57
|
errors[:email] ||= "Invalid email address" unless email =~ URI::MailTo::EMAIL_REGEXP
|
|
53
58
|
|
|
54
|
-
|
|
59
|
+
if username.present? && !CommandTower::Username::Available.(username:).valid?
|
|
55
60
|
errors[:username] = "Username is invalid. #{CommandTower.config.username.username_failure_message}"
|
|
56
61
|
end
|
|
57
62
|
|
|
@@ -64,6 +69,7 @@ module CommandTower
|
|
|
64
69
|
|
|
65
70
|
def reject!(details)
|
|
66
71
|
if details[:email].to_s.downcase.include?(EMAIL_TAKEN_FRAGMENT)
|
|
72
|
+
details = details.merge(email: EMAIL_TAKEN_MESSAGE)
|
|
67
73
|
context.fail!(
|
|
68
74
|
application_error: CommandTower::Errors::Auth::EmailAlreadyRegisteredError.new(details:)
|
|
69
75
|
)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module CommandTower
|
|
4
|
+
module Services
|
|
5
|
+
module Auth
|
|
6
|
+
module SignupRateLimits
|
|
7
|
+
# Per-email ceiling on POST /auth/register attempts per hour (every attempt counts). The
|
|
8
|
+
# key is an HMAC of the normalized email, so no email sits in Redis in plaintext.
|
|
9
|
+
# Registration reveals whether an email is taken by design, so this bucket is what throttles
|
|
10
|
+
# probing. A Redis failure fails open: the per-IP bucket still applies.
|
|
11
|
+
class CheckRegisterEmail < CommandTower::Services::ApplicationService
|
|
12
|
+
include LoginRateLimits::Enforcement
|
|
13
|
+
|
|
14
|
+
WINDOW_SECONDS = 3600
|
|
15
|
+
|
|
16
|
+
validate :email, is_a: String, required: true, sensitive: true
|
|
17
|
+
|
|
18
|
+
def call
|
|
19
|
+
return unless limits.register_attempts_per_email.positive?
|
|
20
|
+
|
|
21
|
+
result = count_attempt
|
|
22
|
+
return if result.failure? || result.data[:count] <= limits.register_attempts_per_email
|
|
23
|
+
|
|
24
|
+
context.fail!(application_error: rate_limit_error(result.data[:ttl]))
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
private
|
|
28
|
+
|
|
29
|
+
def count_attempt
|
|
30
|
+
CommandTower::Services::RateLimits::Check.call(
|
|
31
|
+
key: "auth:register:email:#{hmac_segment(email)}",
|
|
32
|
+
ttl_seconds: WINDOW_SECONDS
|
|
33
|
+
)
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
@@ -16,7 +16,7 @@ module CommandTower
|
|
|
16
16
|
def project
|
|
17
17
|
{
|
|
18
18
|
editName: { enabled: !user.deleted? },
|
|
19
|
-
editUsername: { enabled:
|
|
19
|
+
editUsername: { enabled: UsernameChangeEligibility.eligible?(user) },
|
|
20
20
|
changeEmail: { enabled: false },
|
|
21
21
|
changePassword: { enabled: !user.deleted? },
|
|
22
22
|
editPhone: { enabled: sms_enabled? && !user.deleted? },
|
|
@@ -15,17 +15,18 @@ module CommandTower
|
|
|
15
15
|
validate :user, is_a: User, required: true
|
|
16
16
|
validate :current_password, is_a: String, required: true, sensitive: true
|
|
17
17
|
validate :password, is_a: String, required: true, sensitive: true
|
|
18
|
-
validate :password_confirmation, is_a: String, required:
|
|
18
|
+
validate :password_confirmation, is_a: String, required: false, sensitive: true
|
|
19
19
|
|
|
20
20
|
def call
|
|
21
21
|
reject!(current_password: "Incorrect current password") unless user.authenticate(current_password)
|
|
22
|
-
|
|
22
|
+
# Confirmation is optional; it is only compared when the caller sent one.
|
|
23
|
+
if password_confirmation.present? && password != password_confirmation
|
|
24
|
+
reject!(password_confirmation: "Password and confirmation do not match")
|
|
25
|
+
end
|
|
23
26
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
reject!(
|
|
27
|
-
password: "Password length must be between #{config.password_length_min} and #{config.password_length_max} characters"
|
|
28
|
-
)
|
|
27
|
+
check = CommandTower::Services::Auth::PasswordPolicy::Check.call(password:)
|
|
28
|
+
unless check.data[:valid]
|
|
29
|
+
reject!(password: CommandTower::Services::Auth::PasswordPolicy::Check.message_for(check.data[:failures]))
|
|
29
30
|
end
|
|
30
31
|
|
|
31
32
|
persistence_errors = nil
|
|
@@ -33,7 +34,7 @@ module CommandTower
|
|
|
33
34
|
|
|
34
35
|
ActiveRecord::Base.transaction do
|
|
35
36
|
user.password = password
|
|
36
|
-
user.password_confirmation =
|
|
37
|
+
user.password_confirmation = password
|
|
37
38
|
|
|
38
39
|
unless user.save
|
|
39
40
|
persistence_errors = user.errors.to_hash.transform_values { Array(_1).join(", ") }
|
|
@@ -42,6 +43,7 @@ module CommandTower
|
|
|
42
43
|
|
|
43
44
|
begin
|
|
44
45
|
user.reset_verifier_token!
|
|
46
|
+
CommandTower::Services::Auth::DeviceSessions::RevokeAll.call(user:, reason: "password_change")
|
|
45
47
|
CommandTower::Services::Impersonation::TerminateOpenSessions.call(
|
|
46
48
|
actor_user_id: user.id,
|
|
47
49
|
reason: "revoked"
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module CommandTower
|
|
4
|
+
module Services
|
|
5
|
+
module Me
|
|
6
|
+
# Sets or changes the caller's own username. Eligibility, rate limit (10 per hour per user),
|
|
7
|
+
# shape rules, case-insensitive uniqueness among non-deleted users, and the `username_set` audit.
|
|
8
|
+
class SetUsername < CommandTower::Services::ApplicationService
|
|
9
|
+
LIMIT_PER_HOUR = 10
|
|
10
|
+
WINDOW_SECONDS = 3600
|
|
11
|
+
|
|
12
|
+
validate :user, is_a: User, required: true
|
|
13
|
+
validate :username, is_a: String, required: true
|
|
14
|
+
|
|
15
|
+
def call
|
|
16
|
+
normalized = username.to_s.strip
|
|
17
|
+
guard!(normalized)
|
|
18
|
+
change_username!(normalized) unless user.username.to_s == normalized
|
|
19
|
+
|
|
20
|
+
context.user = user.reload
|
|
21
|
+
rescue ActiveRecord::RecordNotUnique => e
|
|
22
|
+
fail_with!(CommandTower::Errors::Account::UsernameTakenError.new(cause: e))
|
|
23
|
+
rescue ActiveRecord::RecordInvalid => e
|
|
24
|
+
fail_for_invalid_record!(e)
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
private
|
|
28
|
+
|
|
29
|
+
def guard!(normalized)
|
|
30
|
+
unless UsernameChangeEligibility.eligible?(user)
|
|
31
|
+
fail_with!(CommandTower::Errors::Account::UsernameChangeNotAllowedError.new)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
enforce_rate_limit!
|
|
35
|
+
reject_invalid_shape!(normalized)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def fail_with!(error)
|
|
39
|
+
context.fail!(application_error: error)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Fails open on a Redis failure; the unique index still guards the write.
|
|
43
|
+
def enforce_rate_limit!
|
|
44
|
+
result = CommandTower::Services::RateLimits::Check.call(
|
|
45
|
+
key: "me:username:user:#{user.id}:#{Time.now.to_i / WINDOW_SECONDS}",
|
|
46
|
+
ttl_seconds: WINDOW_SECONDS
|
|
47
|
+
)
|
|
48
|
+
return if result.failure? || result.data[:count] <= LIMIT_PER_HOUR
|
|
49
|
+
|
|
50
|
+
ttl = result.data[:ttl]
|
|
51
|
+
fail_with!(
|
|
52
|
+
CommandTower::Errors::Auth::AuthRateLimitedError.new(retry_after_seconds: ttl.positive? ? ttl : nil)
|
|
53
|
+
)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def reject_invalid_shape!(normalized)
|
|
57
|
+
fail_with!(validation_error("Username must not be an email address")) if normalized.include?("@")
|
|
58
|
+
return if CommandTower::Username::Available.call(username: normalized).valid?
|
|
59
|
+
|
|
60
|
+
fail_with!(validation_error(CommandTower.config.username.username_failure_message))
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def validation_error(message)
|
|
64
|
+
CommandTower::Errors::ValidationError.new(details: { username: message })
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def change_username!(normalized)
|
|
68
|
+
fail_with!(CommandTower::Errors::Account::UsernameTakenError.new) if taken?(normalized)
|
|
69
|
+
|
|
70
|
+
changes = { username: { from: user.username, to: normalized } }
|
|
71
|
+
ActiveRecord::Base.transaction do
|
|
72
|
+
apply!(normalized)
|
|
73
|
+
audit(:username_set, subject: user, affected_user: user, changes:)
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def taken?(normalized)
|
|
78
|
+
User.not_deleted.where.not(id: user.id).exists?(["LOWER(username) = ?", normalized.downcase])
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def apply!(normalized)
|
|
82
|
+
outcome = CommandTower::UserAttributes::Mutate.call(user:, username: normalized)
|
|
83
|
+
return if outcome.success?
|
|
84
|
+
|
|
85
|
+
details = outcome.invalid_argument_hash.transform_values { |entry| entry[:msg].to_s }
|
|
86
|
+
fail_with!(CommandTower::Errors::ValidationError.new(details:))
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def fail_for_invalid_record!(error)
|
|
90
|
+
record = error.record
|
|
91
|
+
entries = record ? Array(record.errors.details[:username]) : []
|
|
92
|
+
taken = entries.any? { |entry| entry[:error] == :taken }
|
|
93
|
+
fail_with!(CommandTower::Errors::Account::UsernameTakenError.new(cause: error)) if taken
|
|
94
|
+
|
|
95
|
+
raise error
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
end
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module CommandTower
|
|
4
|
+
module Services
|
|
5
|
+
module Me
|
|
6
|
+
# Decides whether a user may set or change their own username.
|
|
7
|
+
# Gated by the host flags `username.self_service` (set) and `username.self_change` (change an existing one).
|
|
8
|
+
class UsernameChangeEligibility
|
|
9
|
+
def self.eligible?(user)
|
|
10
|
+
new(user).eligible?
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def initialize(user)
|
|
14
|
+
@user = user
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def eligible?
|
|
18
|
+
return false if user.deleted?
|
|
19
|
+
return false unless config.self_service
|
|
20
|
+
|
|
21
|
+
user.username.blank? || config.self_change
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
private
|
|
25
|
+
|
|
26
|
+
attr_reader :user
|
|
27
|
+
|
|
28
|
+
def config
|
|
29
|
+
CommandTower.config.username
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
end
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module CommandTower
|
|
4
|
+
module Services
|
|
5
|
+
module RateLimits
|
|
6
|
+
# Deletes a rate-limit counter so the next Check starts a fresh window.
|
|
7
|
+
class Clear < CommandTower::Services::ApplicationService
|
|
8
|
+
validate :key, is_a: String, required: true
|
|
9
|
+
|
|
10
|
+
def call
|
|
11
|
+
CommandTower::RedisConnection.with { |redis| redis.del(key) }
|
|
12
|
+
rescue Redis::BaseError, Timeout::Error => e
|
|
13
|
+
context.fail!(application_error: CommandTower::Errors::InternalError.new(cause: e))
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
end
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module CommandTower
|
|
4
|
+
module Services
|
|
5
|
+
module RateLimits
|
|
6
|
+
# Reads a rate-limit counter without incrementing it.
|
|
7
|
+
class Peek < CommandTower::Services::ApplicationService
|
|
8
|
+
validate :key, is_a: String, required: true
|
|
9
|
+
|
|
10
|
+
def call
|
|
11
|
+
count, ttl = CommandTower::RedisConnection.with do |redis|
|
|
12
|
+
[redis.get(key), redis.ttl(key)]
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
context.count = count.to_i
|
|
16
|
+
context.ttl = [ttl.to_i, 0].max
|
|
17
|
+
rescue Redis::BaseError, Timeout::Error => e
|
|
18
|
+
context.fail!(application_error: CommandTower::Errors::InternalError.new(cause: e))
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
|
@@ -50,7 +50,7 @@ module CommandTower::Username
|
|
|
50
50
|
# If we can use Redis, a bloom filter would be great
|
|
51
51
|
def populate_local_cache!
|
|
52
52
|
CACHE_MUTEX.synchronize do
|
|
53
|
-
values = User.pluck(:username).map { [_1, 1] }.to_h rescue {}
|
|
53
|
+
values = User.pluck(:username).compact_blank.map { [_1, 1] }.to_h rescue {}
|
|
54
54
|
realtime.local_cache.write_multi(values)
|
|
55
55
|
realtime.local_cache.write(REFRESH_KEY, realtime.local_cache_ttl.from_now)
|
|
56
56
|
|
|
@@ -8,6 +8,17 @@ module CommandTower
|
|
|
8
8
|
module AuthenticationResponseEffects
|
|
9
9
|
module_function
|
|
10
10
|
|
|
11
|
+
# Token-issuing effect. `expires_at` is the sliding signal (X-Authorization-Expire);
|
|
12
|
+
# the cookie lives to the device session's absolute expiry when one exists.
|
|
13
|
+
def for_set_token(token:, expires_at:, device_session: nil, header: true)
|
|
14
|
+
{
|
|
15
|
+
token: token,
|
|
16
|
+
expires_at: expires_at,
|
|
17
|
+
header: header,
|
|
18
|
+
cookie_expires_at: device_session&.absolute_expires_at
|
|
19
|
+
}
|
|
20
|
+
end
|
|
21
|
+
|
|
11
22
|
def for_auth_failure(metadata)
|
|
12
23
|
effects = {}
|
|
13
24
|
# 412 email verification is a live session that still needs the JWT
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module CommandTower
|
|
4
|
+
module Workflows
|
|
5
|
+
module Auth
|
|
6
|
+
module DeviceSessions
|
|
7
|
+
# Deletes device sessions that ended (revoked, or past their absolute expiry)
|
|
8
|
+
# more than `retain_for` ago. Walks the indexed `revoked_at` and
|
|
9
|
+
# `absolute_expires_at` columns in id-bounded batches so no statement is large.
|
|
10
|
+
# Idle-expired rows are not purged here: they are ended only by `last_seen_at`,
|
|
11
|
+
# which is unindexed, and they reach absolute expiry in time.
|
|
12
|
+
class PurgeEndedWorkflow < CommandTower::Workflows::ApplicationWorkflow
|
|
13
|
+
BATCH_SIZE = 1_000
|
|
14
|
+
DEFAULT_RETAIN_FOR = 30.days
|
|
15
|
+
|
|
16
|
+
retry_strategy :none
|
|
17
|
+
|
|
18
|
+
def call(retain_for: DEFAULT_RETAIN_FOR)
|
|
19
|
+
cutoff = Time.current - retain_for
|
|
20
|
+
scope = CommandTower::Auth::DeviceSession
|
|
21
|
+
purged = purge(scope.where(revoked_at: ...cutoff))
|
|
22
|
+
purged += purge(scope.where(absolute_expires_at: ...cutoff))
|
|
23
|
+
|
|
24
|
+
log_info("Purged #{purged} ended device sessions")
|
|
25
|
+
success(payload: { purged: purged }, http_status: :ok)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
private
|
|
29
|
+
|
|
30
|
+
def purge(scope)
|
|
31
|
+
total = 0
|
|
32
|
+
loop do
|
|
33
|
+
ids = scope.limit(BATCH_SIZE).pluck(:id)
|
|
34
|
+
break if ids.empty?
|
|
35
|
+
|
|
36
|
+
total += CommandTower::Auth::DeviceSession.where(id: ids).delete_all
|
|
37
|
+
end
|
|
38
|
+
total
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module CommandTower
|
|
4
|
+
module Workflows
|
|
5
|
+
module Auth
|
|
6
|
+
module EmailVerification
|
|
7
|
+
# Job-entry orchestration: generate a single-use verification code for the
|
|
8
|
+
# user and email it. Failures raise so the job (or an inline caller) sees
|
|
9
|
+
# them; the code itself is never logged.
|
|
10
|
+
class IssueWorkflow < CommandTower::Workflows::ApplicationWorkflow
|
|
11
|
+
retry_strategy :none
|
|
12
|
+
|
|
13
|
+
class DeliveryError < StandardError; end
|
|
14
|
+
|
|
15
|
+
def call(user_id:)
|
|
16
|
+
user = User.find_by(id: user_id)
|
|
17
|
+
return success(payload: {}, http_status: :ok) if user.nil? || user.email_validated
|
|
18
|
+
|
|
19
|
+
deliver(user, issued_code(user))
|
|
20
|
+
success(payload: {}, http_status: :ok)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
private
|
|
24
|
+
|
|
25
|
+
def email_verify
|
|
26
|
+
CommandTower.config.login.plain_text.email_verify
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def issued_code(user)
|
|
30
|
+
result = generate_secret(user)
|
|
31
|
+
return result.secret if result.success?
|
|
32
|
+
|
|
33
|
+
log_error("Secret Generation is not available at this time for user [#{user.id}]")
|
|
34
|
+
raise DeliveryError, "verification code generation failed"
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def generate_secret(user)
|
|
38
|
+
CommandTower::Secrets::Generate.call(
|
|
39
|
+
user: user,
|
|
40
|
+
secret_length: email_verify.verify_code_length,
|
|
41
|
+
reason: CommandTower::Secrets::EMAIL_VERIFICIATION,
|
|
42
|
+
use_count_max: 1,
|
|
43
|
+
death_time: email_verify.verify_code_link_valid_for,
|
|
44
|
+
type: CommandTower::Secrets::NUMERIC,
|
|
45
|
+
cleanse: true
|
|
46
|
+
)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def deliver(user, secret)
|
|
50
|
+
CommandTower::EmailVerificationMailer.verify_email(
|
|
51
|
+
user.email,
|
|
52
|
+
user,
|
|
53
|
+
secret,
|
|
54
|
+
template_name: email_verify.custom_template_name
|
|
55
|
+
).deliver
|
|
56
|
+
rescue StandardError => e
|
|
57
|
+
log_error("Failed to send verification email to user [#{user.id}]: #{e.class}")
|
|
58
|
+
raise DeliveryError, "verification email delivery failed"
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
end
|
|
@@ -18,11 +18,13 @@ module CommandTower
|
|
|
18
18
|
end
|
|
19
19
|
|
|
20
20
|
message = send_result.data[:message]
|
|
21
|
+
resend_available_at = send_result.data[:resend_available_at]
|
|
21
22
|
success(
|
|
22
23
|
payload: CommandTower::Serializers::Auth::EmailVerification::MessageResponseSerializer.serialize(
|
|
23
|
-
message: message
|
|
24
|
+
message: message,
|
|
25
|
+
resend_available_at: resend_available_at
|
|
24
26
|
),
|
|
25
|
-
http_status: message.include?("already verified") ? :ok : :created
|
|
27
|
+
http_status: message.include?("already verified") || send_result.data[:quiet] ? :ok : :created
|
|
26
28
|
)
|
|
27
29
|
end
|
|
28
30
|
end
|