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
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module CommandTower
|
|
4
|
+
module Workflows
|
|
5
|
+
module Me
|
|
6
|
+
# Username availability for an authenticated user who may set or change their username
|
|
7
|
+
# (GET /me/username/availability). Limited per user and per IP per day.
|
|
8
|
+
class UsernameAvailabilityWorkflow < CommandTower::Workflows::ApplicationWorkflow
|
|
9
|
+
USER_LIMIT_PER_DAY = 100
|
|
10
|
+
IP_LIMIT_PER_DAY = 300
|
|
11
|
+
WINDOW_SECONDS = 86_400
|
|
12
|
+
|
|
13
|
+
retry_strategy :none
|
|
14
|
+
|
|
15
|
+
def call(current_user:, username:, client_ip:)
|
|
16
|
+
unless CommandTower::Services::Me::UsernameChangeEligibility.eligible?(current_user)
|
|
17
|
+
return failure(
|
|
18
|
+
errors: [CommandTower::Errors::Account::UsernameChangeNotAllowedError.new],
|
|
19
|
+
http_status: :forbidden
|
|
20
|
+
)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
limited = rate_limit_failure(current_user, client_ip)
|
|
24
|
+
return limited if limited
|
|
25
|
+
|
|
26
|
+
check_availability(username)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
private
|
|
30
|
+
|
|
31
|
+
def check_availability(username)
|
|
32
|
+
result = CommandTower::Services::Auth::UsernameAvailability.call(username: username)
|
|
33
|
+
return failure(errors: result.errors, http_status: :internal_server_error) unless result.success?
|
|
34
|
+
|
|
35
|
+
success(payload: payload(username, result.data), http_status: :ok)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def payload(username, data)
|
|
39
|
+
email_shaped = username.include?("@")
|
|
40
|
+
valid = data[:valid] && !email_shaped
|
|
41
|
+
CommandTower::Serializers::Auth::UsernameAvailabilitySerializer.serialize(
|
|
42
|
+
valid: valid,
|
|
43
|
+
available: valid && data[:available],
|
|
44
|
+
message: valid ? data[:message] : invalid_message(email_shaped)
|
|
45
|
+
)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def invalid_message(email_shaped)
|
|
49
|
+
return "Username must not be an email address" if email_shaped
|
|
50
|
+
|
|
51
|
+
CommandTower.config.username.username_failure_message
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def rate_limit_failure(user, client_ip)
|
|
55
|
+
day = Time.now.to_i / WINDOW_SECONDS
|
|
56
|
+
[
|
|
57
|
+
["me:username_availability:user:#{user.id}:#{day}", USER_LIMIT_PER_DAY],
|
|
58
|
+
["me:username_availability:ip:#{client_ip}:#{day}", IP_LIMIT_PER_DAY]
|
|
59
|
+
].each do |key, limit|
|
|
60
|
+
error = breach(key, limit)
|
|
61
|
+
return failure(errors: [error], http_status: :too_many_requests) if error
|
|
62
|
+
end
|
|
63
|
+
nil
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Fails open on a Redis failure; availability is advisory and the unique index guards the write.
|
|
67
|
+
def breach(key, limit)
|
|
68
|
+
result = CommandTower::Services::RateLimits::Check.call(key: key, ttl_seconds: WINDOW_SECONDS)
|
|
69
|
+
return if result.failure? || result.data[:count] <= limit
|
|
70
|
+
|
|
71
|
+
ttl = result.data[:ttl]
|
|
72
|
+
CommandTower::Errors::Auth::AuthRateLimitedError.new(retry_after_seconds: ttl.positive? ? ttl : nil)
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module CommandTower
|
|
4
|
+
module Workflows
|
|
5
|
+
module Me
|
|
6
|
+
# Self-service username set/change (PATCH /me/username).
|
|
7
|
+
class UsernameWorkflow < CommandTower::Workflows::ApplicationWorkflow
|
|
8
|
+
retry_strategy :none
|
|
9
|
+
|
|
10
|
+
def call(current_user:, username:, auth_context: nil)
|
|
11
|
+
if CommandTower::Current.impersonation_active == true
|
|
12
|
+
return failure(errors: [CommandTower::Errors::ForbiddenError.new], http_status: :forbidden)
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
set_result = CommandTower::Services::Me::SetUsername.call(user: current_user, username:)
|
|
16
|
+
return failure_from(set_result) unless set_result.success?
|
|
17
|
+
|
|
18
|
+
success(
|
|
19
|
+
payload: account_payload(set_result.data[:user]),
|
|
20
|
+
http_status: :ok,
|
|
21
|
+
response_effects: expire_header_effects(auth_context)
|
|
22
|
+
)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
private
|
|
26
|
+
|
|
27
|
+
def failure_from(set_result)
|
|
28
|
+
failure(
|
|
29
|
+
errors: set_result.errors,
|
|
30
|
+
http_status: CommandTower::Workflows::Me::ErrorStatus.http_status_for(set_result.errors.first)
|
|
31
|
+
)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def account_payload(user)
|
|
35
|
+
capabilities = CommandTower::Services::Me::Capabilities.project(user)
|
|
36
|
+
CommandTower::Serializers::Me::AccountSerializer.serialize(user, capabilities: capabilities)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def expire_header_effects(auth_context)
|
|
40
|
+
return if auth_context.nil?
|
|
41
|
+
|
|
42
|
+
{ set_expire_header: auth_context.token_expires_at }
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
data/config/routes.rb
CHANGED
|
@@ -23,6 +23,7 @@ CommandTower::Engine.routes.draw do
|
|
|
23
23
|
post "register", to: "register#create"
|
|
24
24
|
post "signup-session", to: "signup_session/create#create"
|
|
25
25
|
get "identity-policy", to: "identity_policy#show"
|
|
26
|
+
post "password-check", to: "password_check#create"
|
|
26
27
|
|
|
27
28
|
constraints(->(_req) { CommandTower.config.signup_session.email_availability? }) do
|
|
28
29
|
namespace :email do
|
|
@@ -65,6 +66,8 @@ CommandTower::Engine.routes.draw do
|
|
|
65
66
|
get "profile", to: "profile#show"
|
|
66
67
|
namespace :me do
|
|
67
68
|
patch "name", to: "name#update"
|
|
69
|
+
patch "username", to: "username#update"
|
|
70
|
+
get "username/availability", to: "username_availability#show"
|
|
68
71
|
patch "password", to: "password#update"
|
|
69
72
|
delete "account", to: "account#destroy"
|
|
70
73
|
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class CreateCommandTowerDeviceSessions < ActiveRecord::Migration[7.2]
|
|
4
|
+
TABLE = :command_tower_device_sessions
|
|
5
|
+
LEGACY_INDEX = "index_ct_device_sessions_on_user_legacy_generated_at"
|
|
6
|
+
|
|
7
|
+
def change
|
|
8
|
+
create_table TABLE do |t|
|
|
9
|
+
add_identity_columns(t)
|
|
10
|
+
add_lifecycle_columns(t)
|
|
11
|
+
t.timestamps
|
|
12
|
+
end
|
|
13
|
+
add_device_sessions_indexes
|
|
14
|
+
add_foreign_key TABLE, :users
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
private
|
|
18
|
+
|
|
19
|
+
def add_identity_columns(table)
|
|
20
|
+
table.string :public_id, limit: 36, null: false
|
|
21
|
+
table.bigint :user_id, null: false
|
|
22
|
+
table.string :installation_id, limit: 36
|
|
23
|
+
table.string :platform, limit: 16
|
|
24
|
+
table.string :app_version, limit: 32
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def add_lifecycle_columns(table)
|
|
28
|
+
table.datetime :last_seen_at, null: false
|
|
29
|
+
table.datetime :absolute_expires_at, null: false
|
|
30
|
+
table.datetime :revoked_at
|
|
31
|
+
table.string :revoked_reason, limit: 32
|
|
32
|
+
table.datetime :legacy_generated_at
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def add_device_sessions_indexes
|
|
36
|
+
add_index TABLE, :public_id, unique: true
|
|
37
|
+
add_index TABLE, %i[user_id revoked_at]
|
|
38
|
+
add_index TABLE, :installation_id
|
|
39
|
+
add_index TABLE, %i[user_id legacy_generated_at], unique: true, name: LEGACY_INDEX
|
|
40
|
+
add_index TABLE, :revoked_at
|
|
41
|
+
add_index TABLE, :absolute_expires_at
|
|
42
|
+
end
|
|
43
|
+
end
|
data/docs/api_reference.md
CHANGED
|
@@ -100,13 +100,17 @@ Default JWT TTL is **7 days** (`config.jwt.ttl`).
|
|
|
100
100
|
|--|--|
|
|
101
101
|
| **Auth** | Public |
|
|
102
102
|
| **Gate** | Always drawn |
|
|
103
|
-
| **Body** | `
|
|
104
|
-
| **Success** | **201** — `data`: `{ user, message }` where `message` is `"Account created successfully"`.
|
|
105
|
-
| **Errors** | `422` `validation_failed` / `email_already_registered
|
|
103
|
+
| **Body** | `email`, `password` required; optional `start_session` (boolean). **Deprecated** (still accepted): `first_name`, `last_name`, `username`, `password_confirmation` (snake_case) |
|
|
104
|
+
| **Success** | **201** — `data`: `{ user, message }` where `message` is `"Account created successfully"`. With `start_session: true` the body also carries `tokenExpiresAt` and, unless the cookie-mode web rule omits it (same rule as login), `token`; the response sets the session cookie/headers like login and a device session exists. Without `start_session` there is no token. |
|
|
105
|
+
| **Errors** | `422` `validation_failed` (password length 8–64 inclusive, common-password blocklist; email 3–254 inclusive; a policy failure adds `passwordRulesFailed`, a list of rule ids `min_length`, `max_length`, `not_common`) / `email_already_registered` (message: "You already have an account with this email. Sign in or reset your password."); `429` `signup_ip_rate_limited` (per IP) or the per-email bucket, with `details.retry_after_seconds` |
|
|
106
106
|
| **Spec** | `spec/requests/command_tower/auth/register_spec.rb` |
|
|
107
107
|
|
|
108
|
+
The six-field body is the old shape. It keeps working; each use emits `auth.legacy_contract_used` (`endpoint: register_old_shape`). Names default to empty strings and `username` is optional. The per-email bucket is `config.login.rate_limits.register_attempts_per_email` (default 5 per hour, `0` disables).
|
|
109
|
+
|
|
108
110
|
`user` fields: `id`, `email`, `username`, `firstName`, `lastName`, `emailValidated`, `roles`.
|
|
109
111
|
|
|
112
|
+
With `start_session: true` the body also carries `capabilities: { editUsername: { enabled } }` so the client can show the username step right after signup, including for unverified accounts with no grace period.
|
|
113
|
+
|
|
110
114
|
### `POST /auth/plain-text/login`
|
|
111
115
|
|
|
112
116
|
| | |
|
|
@@ -114,10 +118,14 @@ Default JWT TTL is **7 days** (`config.jwt.ttl`).
|
|
|
114
118
|
| **Auth** | Public |
|
|
115
119
|
| **Gate** | `config.login.plain_text.enable?` (else route absent → **404**) |
|
|
116
120
|
| **Body** | `identifier`, `password` (snake_case) |
|
|
117
|
-
| **Success** | **201** — `data`: `{ user, token, tokenExpiresAt }` |
|
|
118
|
-
| **Errors** | `401` `invalid_credentials` |
|
|
121
|
+
| **Success** | **201** — `data`: `{ user, token, tokenExpiresAt }`; `token` is absent for the new web client in cookie mode |
|
|
122
|
+
| **Errors** | `401` `invalid_credentials`; `429` `auth_rate_limited` (per-IP ceiling or soft account lockout) |
|
|
119
123
|
| **Spec** | `spec/requests/command_tower/auth/plain_text/login_spec.rb` |
|
|
120
124
|
|
|
125
|
+
**Installation id and body token:** the request may carry `X-Installation-Id` (UUID v4) or the `ct_installation` cookie, plus optional `X-Client-Platform` and `X-App-Version`. A cookie-mode login without an id sets `ct_installation`. `token` is omitted from the body only when cookie mode is on, `config.session.omit_body_token` is true, `X-Client-Platform` is `web` and `X-App-Version` is at or above `config.session.omit_body_token_min_app_version`. See the [cookie guide](cookie_authentication_guide.md#installation-id-and-body-token).
|
|
126
|
+
|
|
127
|
+
`429` `auth_rate_limited` carries `details.retry_after_seconds` and a `Retry-After` header. The same error is returned by the email-verification and password-reset validate/reset endpoints when their limits trip. Limits: [Authentication](authentication.md#rate-limits-and-soft-lockout).
|
|
128
|
+
|
|
121
129
|
### `POST /auth/logout`
|
|
122
130
|
|
|
123
131
|
| | |
|
|
@@ -136,6 +144,8 @@ Default JWT TTL is **7 days** (`config.jwt.ttl`).
|
|
|
136
144
|
| **Errors** | `401`; `403`; `412` `email_verification_required` when email verification gate applies |
|
|
137
145
|
| **Spec** | `spec/requests/command_tower/auth/session_spec.rb` |
|
|
138
146
|
|
|
147
|
+
A valid sid-less legacy token is upgraded here when `config.session.upgrade_legacy_tokens` is on: the response carries a replacement token with a `sid` (cookie, or `X-Authorization-With-Reset` for bearer), and the CSRF cookie is not rotated. See the [cookie guide](cookie_authentication_guide.md#legacy-token-upgrade).
|
|
148
|
+
|
|
139
149
|
`user` is the **effective** principal (target while overlaying). When an impersonation overlay is active, `impersonation` is present:
|
|
140
150
|
|
|
141
151
|
```json
|
|
@@ -165,6 +175,8 @@ Does **not** authorize `admin_impersonation` on the effective user. Shared front
|
|
|
165
175
|
|
|
166
176
|
### `POST /auth/signup-session`
|
|
167
177
|
|
|
178
|
+
**Deprecated.** New clients register without a signup session. Each call emits `auth.legacy_contract_used` (`endpoint: signup_session`); so does any use of the `Signup` authorization scheme (`authorization_scheme.signup`).
|
|
179
|
+
|
|
168
180
|
| | |
|
|
169
181
|
|--|--|
|
|
170
182
|
| **Auth** | Public |
|
|
@@ -181,6 +193,21 @@ Does **not** authorize `admin_impersonation` on the effective user. Shared front
|
|
|
181
193
|
| **Success** | **200** — `data`: password / email / username / verificationCode / phoneVerificationCode policy objects (`minLength`, `maxLength`, `pattern`, …) |
|
|
182
194
|
| **Spec** | `spec/requests/command_tower/auth/identity_policy_spec.rb` |
|
|
183
195
|
|
|
196
|
+
Length bounds are inclusive and are the configured values as-is (no `+1`/`-1` adjustment). `password` also has `maxBytes` (72, the bcrypt limit; a password must satisfy both the character and byte limits), `passwordRules` (a `passwordrules` attribute string such as `minlength: 8; maxlength: 64;`) and `rules`. `email` and `username` have `rules`. Each rule is `{ id, label, check }` where `check` is `client` (the client can evaluate it) or `server` (needs the server, for example `not_common` via `POST /auth/password-check`). `username` also carries `selfService`, `selfChange` and `prompt` (`after_signup` or `off`) from `config.username`.
|
|
197
|
+
|
|
198
|
+
### `POST /auth/password-check`
|
|
199
|
+
|
|
200
|
+
| | |
|
|
201
|
+
|--|--|
|
|
202
|
+
| **Auth** | Public |
|
|
203
|
+
| **Gate** | Always drawn |
|
|
204
|
+
| **Body** | `password` (string, not stripped) |
|
|
205
|
+
| **Success** | **200** — `data`: `{ valid, failures, message }`. `failures` is a list of `too_short`, `too_long`, `blocklisted`; `message` is `null` when valid. |
|
|
206
|
+
| **Errors** | `422` missing or non-string `password`; `429` `auth_rate_limited` (60 per minute per IP, fails open on a Redis outage) |
|
|
207
|
+
| **Spec** | `spec/requests/command_tower/auth/password_check_spec.rb` |
|
|
208
|
+
|
|
209
|
+
Live feedback for signup, reset and change-password screens. The password is evaluated in memory only; it is never stored, logged or echoed. Register, password reset and `PATCH /me/password` apply the same check, so a password that passes here is not rejected for policy on submit.
|
|
210
|
+
|
|
184
211
|
### `GET /auth/principal-capabilities`
|
|
185
212
|
|
|
186
213
|
| | |
|
|
@@ -194,6 +221,8 @@ Projection is effective entity grants ∩ curated `config.registry.principal_cap
|
|
|
194
221
|
|
|
195
222
|
### `GET /auth/email/availability`
|
|
196
223
|
|
|
224
|
+
**Deprecated** (emits `auth.legacy_contract_used`, `endpoint: email_availability`).
|
|
225
|
+
|
|
197
226
|
| | |
|
|
198
227
|
|--|--|
|
|
199
228
|
| **Auth** | Signup session (`Authorization: Signup …`) |
|
|
@@ -205,6 +234,8 @@ Projection is effective entity grants ∩ curated `config.registry.principal_cap
|
|
|
205
234
|
|
|
206
235
|
### `GET /auth/username/availability`
|
|
207
236
|
|
|
237
|
+
**Deprecated** (emits `auth.legacy_contract_used`, `endpoint: username_availability`).
|
|
238
|
+
|
|
208
239
|
| | |
|
|
209
240
|
|--|--|
|
|
210
241
|
| **Auth** | Signup session |
|
|
@@ -221,8 +252,8 @@ Projection is effective entity grants ∩ curated `config.registry.principal_cap
|
|
|
221
252
|
| **Auth** | `authenticate_request!(bypass_email_validation: true)` + authorize |
|
|
222
253
|
| **Gate** | `config.login.plain_text.email_verify?` |
|
|
223
254
|
| **Body** | none |
|
|
224
|
-
| **Success** | **201** when sent / **200** when already verified — `data`: `{ message }` |
|
|
225
|
-
| **Errors** | `401`/`403`; `502` `verification_send_failed` |
|
|
255
|
+
| **Success** | **201** when sent / **200** when already verified, or when a code was sent inside the quiet window (nothing sent) — `data`: `{ message, resendAvailableAt? }` |
|
|
256
|
+
| **Errors** | `401`/`403`; `429` `auth_rate_limited` (hourly cap); `502` `verification_send_failed` |
|
|
226
257
|
| **Spec** | `spec/requests/command_tower/auth/email_verification_spec.rb` |
|
|
227
258
|
|
|
228
259
|
### `POST /auth/email-verification/verify`
|
|
@@ -233,13 +264,15 @@ Projection is effective entity grants ∩ curated `config.registry.principal_cap
|
|
|
233
264
|
| **Gate** | Same |
|
|
234
265
|
| **Body** | `code` |
|
|
235
266
|
| **Success** | **201** `"Successfully verified email"` / **200** already verified — `data`: `{ message }` |
|
|
236
|
-
| **Errors** | `422` `verification_code_invalid` |
|
|
267
|
+
| **Errors** | `422` `verification_code_invalid`; `429` `auth_rate_limited` |
|
|
237
268
|
| **Spec** | `spec/requests/command_tower/auth/email_verification_spec.rb` |
|
|
238
269
|
|
|
239
270
|
Workflow detail: [email_verification_workflow.md](email_verification_workflow.md).
|
|
240
271
|
|
|
241
272
|
### `POST /auth/password-recovery-session`
|
|
242
273
|
|
|
274
|
+
**Deprecated** (emits `auth.legacy_contract_used`, `endpoint: password_recovery_session`; the `Recovery` authorization scheme emits `authorization_scheme.recovery`).
|
|
275
|
+
|
|
243
276
|
| | |
|
|
244
277
|
|--|--|
|
|
245
278
|
| **Auth** | Public (always drawn; not gated by password_reset) |
|
|
@@ -266,7 +299,7 @@ Workflow detail: [email_verification_workflow.md](email_verification_workflow.md
|
|
|
266
299
|
| **Gate** | `password_reset?` |
|
|
267
300
|
| **Body** | `token` (required); `email` optional unless config requires it |
|
|
268
301
|
| **Success** | **200** — `data`: `{ valid: true, expiresAt? }` |
|
|
269
|
-
| **Errors** | `401` `password_reset_invalid_token`; `422` |
|
|
302
|
+
| **Errors** | `401` `password_reset_invalid_token`; `422`; `429` `auth_rate_limited` |
|
|
270
303
|
| **Spec** | `spec/requests/command_tower/auth/password_reset_validate_and_reset_spec.rb` |
|
|
271
304
|
|
|
272
305
|
### `POST /auth/password-reset/reset`
|
|
@@ -275,9 +308,9 @@ Workflow detail: [email_verification_workflow.md](email_verification_workflow.md
|
|
|
275
308
|
|--|--|
|
|
276
309
|
| **Auth** | Public |
|
|
277
310
|
| **Gate** | `password_reset?` |
|
|
278
|
-
| **Body** | `token`, `password
|
|
311
|
+
| **Body** | `token`, `password`; optional `email`; optional `passwordConfirmation` or `password_confirmation` (when sent it must match, else `422`) |
|
|
279
312
|
| **Success** | **200** — `data`: `{ message: "Password has been successfully reset" }` |
|
|
280
|
-
| **Errors** | `401` `password_reset_invalid_token`; `422` |
|
|
313
|
+
| **Errors** | `401` `password_reset_invalid_token`; `422`; `429` `auth_rate_limited` |
|
|
281
314
|
| **Spec** | `spec/requests/command_tower/auth/password_reset_validate_and_reset_spec.rb` |
|
|
282
315
|
|
|
283
316
|
Workflow detail: [password_reset_workflow.md](password_reset_workflow.md).
|
|
@@ -294,7 +327,7 @@ Workflow detail: [password_reset_workflow.md](password_reset_workflow.md).
|
|
|
294
327
|
| **Success** | **200** — account payload including `id`, `firstName`, `lastName`, `fullName`, `username`, `email`, `emailValidated`, `phoneNumber`, `phoneNumberValidated`, `roles`, `createdAt`, `capabilities` |
|
|
295
328
|
| **Spec** | `spec/requests/command_tower/me_spec.rb` |
|
|
296
329
|
|
|
297
|
-
`capabilities` keys (each `{ enabled: boolean }`): `editName`, `editUsername`, `changeEmail`, `changePassword`, `editPhone`, `editPushover`, `logoutAllDevices`, `verifyEmail`.
|
|
330
|
+
`editUsername` is true when `config.username.self_service` is on and the user has no username (or `self_change` is on). `capabilities` keys (each `{ enabled: boolean }`): `editName`, `editUsername`, `changeEmail`, `changePassword`, `editPhone`, `editPushover`, `logoutAllDevices`, `verifyEmail`.
|
|
298
331
|
|
|
299
332
|
### `GET /profile`
|
|
300
333
|
|
|
@@ -314,14 +347,40 @@ Workflow detail: [password_reset_workflow.md](password_reset_workflow.md).
|
|
|
314
347
|
| **Errors** | `422` `validation_failed` |
|
|
315
348
|
| **Spec** | `spec/requests/command_tower/me/name_spec.rb` |
|
|
316
349
|
|
|
317
|
-
Name-only. There is no engine HTTP for email
|
|
350
|
+
Name-only. There is no engine HTTP for email self-modify or verifier rotation except via password change (and host ops). Username has its own endpoints below.
|
|
351
|
+
|
|
352
|
+
### `PATCH /me/username`
|
|
353
|
+
|
|
354
|
+
| | |
|
|
355
|
+
|--|--|
|
|
356
|
+
| **Auth** | authenticate + authorize (`me_username`); the email-verification `412` gate is bypassed so an unverified account can finish signup |
|
|
357
|
+
| **Gate** | `config.username.self_service` (set) and `config.username.self_change` (change an existing username) |
|
|
358
|
+
| **Body** | `username` (string, required) |
|
|
359
|
+
| **Success** | **200** — AccountSerializer (same shape as `GET /me`) |
|
|
360
|
+
| **Errors** | `422` `validation_failed` (shape per `config.username`, or an `@` / email-shaped value); `422` `username_taken` (case-insensitive among non-deleted users; a concurrent race on the unique index maps to the same code); `403` `username_change_not_allowed` (flag off, deleted user, or already has a username and `self_change` is off); `403` while impersonating; `429` `auth_rate_limited` (10 per hour per user) |
|
|
361
|
+
| **Audit** | `username_set` (see [audit.md](audit.md)) |
|
|
362
|
+
| **Spec** | `spec/requests/command_tower/me/username_spec.rb` |
|
|
363
|
+
|
|
364
|
+
Sending the current username again is a no-op success.
|
|
365
|
+
|
|
366
|
+
### `GET /me/username/availability`
|
|
367
|
+
|
|
368
|
+
| | |
|
|
369
|
+
|--|--|
|
|
370
|
+
| **Auth** | authenticate + authorize (`me_username_availability`); bypasses the email-verification `412` gate |
|
|
371
|
+
| **Query** | `username` (required) |
|
|
372
|
+
| **Success** | **200** — `data`: `{ valid, available, message }`; email-shaped values return `valid: false` |
|
|
373
|
+
| **Errors** | `422` `validation_failed` (missing `username`); `403` `username_change_not_allowed` (same eligibility as `PATCH /me/username`); `429` `auth_rate_limited` (100 per day per user and 300 per day per IP; fails open on a Redis outage) |
|
|
374
|
+
| **Spec** | `spec/requests/command_tower/me/username_availability_spec.rb` |
|
|
375
|
+
|
|
376
|
+
Replaces the deprecated signup-session `GET /auth/username/availability` for signed-in users. It is not gated by `realtime_username_check`.
|
|
318
377
|
|
|
319
378
|
### `PATCH /me/password`
|
|
320
379
|
|
|
321
380
|
| | |
|
|
322
381
|
|--|--|
|
|
323
382
|
| **Auth** | authenticate + authorize |
|
|
324
|
-
| **Body** | `currentPassword`/`current_password`, `password
|
|
383
|
+
| **Body** | `currentPassword`/`current_password`, `password`; optional `passwordConfirmation`/`password_confirmation` (when sent it must match, else `422`) |
|
|
325
384
|
| **Success** | **200** — `data`: `{ message: "Password updated successfully." }` |
|
|
326
385
|
| **Errors** | `422` validation / wrong current password |
|
|
327
386
|
| **Spec** | `spec/requests/command_tower/me/password_spec.rb` |
|
|
@@ -805,7 +864,7 @@ When a gate is off, the route is **not drawn** → **404**.
|
|
|
805
864
|
| Email verification send/verify | `login.plain_text.email_verify?` |
|
|
806
865
|
| Password reset send/validate/reset | `login.plain_text.password_reset?` |
|
|
807
866
|
|
|
808
|
-
Always drawn (not route-gated): register, logout, session, signup-session, identity-policy, principal-capabilities, password-recovery-session, Me/profile/inbox/audit-events/preferences/phone/pushover, admin workspace, admin announcements, admin audit-events. Phone/Pushover use **503** capability errors when product adapters are unavailable.
|
|
867
|
+
Always drawn (not route-gated): `PATCH /me/username` and `GET /me/username/availability` (eligibility is the `username.self_service` / `self_change` flags, not a route gate), register, logout, session, signup-session, identity-policy, principal-capabilities, password-recovery-session, Me/profile/inbox/audit-events/preferences/phone/pushover, admin workspace, admin announcements, admin audit-events. Phone/Pushover use **503** capability errors when product adapters are unavailable.
|
|
809
868
|
|
|
810
869
|
---
|
|
811
870
|
|
data/docs/audit.md
CHANGED
|
@@ -74,6 +74,7 @@ CommandTower.config.registry.audit.set_enabled!(:login_failed, true)
|
|
|
74
74
|
| `role_assigned` | yes | no |
|
|
75
75
|
| `password_changed` | yes | no |
|
|
76
76
|
| `email_verified` | yes | no |
|
|
77
|
+
| `username_set` | yes | no |
|
|
77
78
|
| `phone_updated` | yes | no |
|
|
78
79
|
| `phone_cleared` | yes | no |
|
|
79
80
|
| `phone_verified` | yes | no |
|
data/docs/authentication.md
CHANGED
|
@@ -38,6 +38,109 @@ Impersonation is a **CommandTower session primitive**, not a User mutation. The
|
|
|
38
38
|
|
|
39
39
|
See [API reference](api_reference.md#impersonation) and [Authorization](authorization.md).
|
|
40
40
|
|
|
41
|
+
## Device sessions
|
|
42
|
+
|
|
43
|
+
Each login starts a **device session**: one row in `command_tower_device_sessions` per signed-in device. The JWT carries its `public_id` as the `sid` claim. For a token with `sid`, the row (not `jwt.ttl`) decides how long the session lives.
|
|
44
|
+
|
|
45
|
+
Table `command_tower_device_sessions`:
|
|
46
|
+
|
|
47
|
+
| Column | Purpose |
|
|
48
|
+
|--------|---------|
|
|
49
|
+
| `public_id` (string 36, unique) | The `sid` claim |
|
|
50
|
+
| `user_id` (FK `users`) | Owner |
|
|
51
|
+
| `installation_id`, `platform`, `app_version` | Optional device metadata; `installation_id` is indexed |
|
|
52
|
+
| `last_seen_at` | Last authenticated request (write-throttled) |
|
|
53
|
+
| `absolute_expires_at` | Hard end of the session |
|
|
54
|
+
| `revoked_at`, `revoked_reason` | Set when the session is ended or replaced |
|
|
55
|
+
| `legacy_generated_at` | Reserved for upgrading legacy tokens; unique with `user_id` |
|
|
56
|
+
|
|
57
|
+
Starting a session (`Services::Auth::DeviceSessions::Start`, used by `Services::Auth::IssueSession` for login) always creates a new row. If the caller supplies an `installation_id`, that user's active session on the same installation is revoked with reason `replaced`.
|
|
58
|
+
|
|
59
|
+
### Configuration
|
|
60
|
+
|
|
61
|
+
`config.session`:
|
|
62
|
+
|
|
63
|
+
| Key | Default | Meaning |
|
|
64
|
+
|-----|---------|---------|
|
|
65
|
+
| `idle_timeout` | 30 days | No authenticated request for this long expires the session |
|
|
66
|
+
| `absolute_timeout` | 90 days | Maximum lifetime from creation |
|
|
67
|
+
| `last_seen_write_interval` | 5 minutes | `last_seen_at` is written at most once per interval, so idle expiry is accurate to about this interval |
|
|
68
|
+
| `enforce` | `true` (ENV `COMMAND_TOWER_SESSION_ENFORCE`, `false` disables) | Kill switch. When false the revoked and idle checks are skipped; the absolute check still applies |
|
|
69
|
+
| `upgrade_legacy_tokens` | `true` (ENV `COMMAND_TOWER_SESSION_UPGRADE_LEGACY_TOKENS`, `false` disables) | Reserved for upgrading sid-less tokens on `GET /auth/session`. Not yet acted on |
|
|
70
|
+
|
|
71
|
+
### Body token omission (host obligation)
|
|
72
|
+
|
|
73
|
+
In cookie mode, login and `start_session` register leave `token` out of the response body for `web` clients whose `X-App-Version` is at or above `config.session.omit_body_token_min_app_version`.
|
|
74
|
+
|
|
75
|
+
| Key | Default | Meaning |
|
|
76
|
+
|-----|---------|---------|
|
|
77
|
+
| `omit_body_token` | `true` (ENV `COMMAND_TOWER_SESSION_OMIT_BODY_TOKEN`, `false` disables) | Switch for the omission |
|
|
78
|
+
| `omit_body_token_min_app_version` | `"0.4.0"` (ENV `COMMAND_TOWER_SESSION_OMIT_BODY_TOKEN_MIN_APP_VERSION`) | Minimum `X-App-Version` that gets no body token |
|
|
79
|
+
|
|
80
|
+
The default `0.4.0` is a gem-wide placeholder, not a value any host chose. It is compared with the **host app's** `X-App-Version`, not the `@commandtower/frontend` package version. A host app already above `0.4.0` (for example DoubleFloor Me at `1.0.0`) therefore has the body token omitted for every web client as soon as it upgrades, including web builds that still read `token` from the body.
|
|
81
|
+
|
|
82
|
+
Each host must decide this before upgrading: set `config.session.omit_body_token_min_app_version` to the first host app version whose web client works from the cookie alone, or leave omission off with `COMMAND_TOWER_SESSION_OMIT_BODY_TOKEN=false`. Native clients and requests without the headers always keep the body token.
|
|
83
|
+
|
|
84
|
+
### Session checks and 401 codes
|
|
85
|
+
|
|
86
|
+
`AuthenticateUser` looks up the row by `sid` and fails the request when:
|
|
87
|
+
|
|
88
|
+
| Condition | HTTP | Code |
|
|
89
|
+
|-----------|------|------|
|
|
90
|
+
| Row missing, belongs to another user, or revoked (with `enforce`) | 401 | `session_revoked` |
|
|
91
|
+
| Past `absolute_expires_at`, or idle longer than `idle_timeout` (idle with `enforce`) | 401 | `session_expired` |
|
|
92
|
+
|
|
93
|
+
These two answer with the client envelope `{ "data": null, "errors": [{ "code": "...", "message": "..." }] }` so clients can tell them from a bad token. All other 401 and 412 bodies are unchanged. The auth cookie is cleared as before.
|
|
94
|
+
|
|
95
|
+
Tokens without `sid` (issued before device sessions) keep the old rule: `generated_at + jwt.ttl`. `AuthContext#legacy_token` is true for them and `AuthContext#device_session` is nil.
|
|
96
|
+
|
|
97
|
+
A refreshed token (`GET /auth/session` with reset) keeps the same `sid`; its reported expiry is the earlier of idle expiry and absolute expiry. A cookie-sourced refresh sets the cookie only; the `X-Authorization-With-Reset` header is written only for bearer-sourced requests, at most once per response.
|
|
98
|
+
|
|
99
|
+
### Session lifecycle
|
|
100
|
+
|
|
101
|
+
| Event | Effect on device sessions |
|
|
102
|
+
|-------|---------------------------|
|
|
103
|
+
| `POST /auth/logout` | Revokes only the signing-out device (`revoked_reason: logout`). Other devices stay signed in |
|
|
104
|
+
| Authenticated password change, password reset, admin `verifier_token` mutation, account tombstone | Revokes **all** the user's active sessions, including the caller's (`Services::Auth::DeviceSessions::RevokeAll`; reasons `password_change`, `password_reset`, `admin_mutation`, `tombstone`). Idempotent: already-revoked rows keep their original `revoked_at` and reason |
|
|
105
|
+
| Login on an installation that already has a session | Old session revoked as `replaced` |
|
|
106
|
+
| Impersonation start / stop | The overlay and restored tokens keep the actor's `sid`, so the overlay shares the actor device's lifecycle |
|
|
107
|
+
|
|
108
|
+
Revoked sessions answer `401` `session_revoked` on the next request.
|
|
109
|
+
|
|
110
|
+
### Expiry signals
|
|
111
|
+
|
|
112
|
+
- `X-Authorization-Expire` is the **sliding** (idle) expiry: the earlier of idle expiry and absolute expiry.
|
|
113
|
+
- The auth cookie, when cookie auth is enabled, expires at the device session's **absolute** expiry (`absolute_expires_at`). Without a device session it uses `jwt.cookie.ttl` as before.
|
|
114
|
+
|
|
115
|
+
### Purging ended sessions
|
|
116
|
+
|
|
117
|
+
Ended rows accumulate (one per login) until purged. `CommandTower::Auth::DeviceSessions::PurgeEndedJob` (no arguments) runs `Workflows::Auth::DeviceSessions::PurgeEndedWorkflow`, which deletes sessions revoked or past `absolute_expires_at` more than 30 days ago (`retain_for`, default `30.days`). It works in batches of 1,000 ids over the indexed `revoked_at` and `absolute_expires_at` columns and writes only CommandTower-owned rows. Sessions that are only idle-expired are not purged; they reach absolute expiry and are purged then.
|
|
118
|
+
|
|
119
|
+
**The host schedules the job.** CommandTower does not schedule it. Run it daily with the host's scheduler (for example a recurring job or cron calling `CommandTower::Auth::DeviceSessions::PurgeEndedJob.perform_later`). Until it is scheduled, nothing breaks; rows only accumulate.
|
|
120
|
+
|
|
121
|
+
Host seams: `Jwt::LoginCreate.call` takes an optional `device_session:`; `Jwt::AuthenticateUser` returns `AuthenticationOutcome` with `code` and `device_session`. Hosts that wrap either must pass these through ([upgrade guide](upgrades/0.25.0.md)).
|
|
122
|
+
|
|
123
|
+
## Rate limits and soft lockout
|
|
124
|
+
|
|
125
|
+
Password login, password-reset token use, and email-verification endpoints are limited by `config.login.rate_limits`. A limit set to `0` disables that bucket. A rejected request returns `429` `auth_rate_limited` with `details.retry_after_seconds` and a `Retry-After` header. See [API reference](api_reference.md#post-authplain-textlogin).
|
|
126
|
+
|
|
127
|
+
| Bucket | Applies to | Default | Setting |
|
|
128
|
+
|--------|-----------|---------|---------|
|
|
129
|
+
| Account lockout | Failed logins per account, or per unknown identifier (same behavior for both, so it does not reveal which accounts exist) | 10 failures in 15 min | `account_failures`, `account_window_seconds` |
|
|
130
|
+
| Lock length | First soft lock, doubling on each repeat inside the level window, capped. Every lock expires; a failed attempt while locked never extends it | 15 min, max 60 min, levels remembered 24 h | `lock_base_seconds`, `lock_max_seconds`, `lock_level_window_seconds` |
|
|
131
|
+
| Login per IP | `POST /auth/plain-text/login` | 100 in 15 min | `ip_attempts`, `ip_window_seconds` |
|
|
132
|
+
| Reset per IP | `POST /auth/password-reset/validate` and `/reset` | 30 in 15 min | `reset_attempts_per_ip`, `reset_window_seconds` |
|
|
133
|
+
| Verify attempts | `POST /auth/email-verification/verify`, per user | 10 in 15 min | `verify_attempts`, `verify_window_seconds` |
|
|
134
|
+
| Verification send | `POST /auth/email-verification/send`, per user. A second request inside the quiet window sends nothing and answers `200` with `resendAvailableAt`; the hourly cap answers `429` | 60 s quiet, 20 per hour | `verify_send_quiet_seconds`, `verify_send_per_hour` |
|
|
135
|
+
|
|
136
|
+
A successful login clears the account's failure count and lock. A successful password reset also clears the lock. Lockout subjects are HMAC'd, so no email or username is stored in Redis in plaintext.
|
|
137
|
+
|
|
138
|
+
**Redis outage.** Limits fail open: login still works, `auth.rate_limit.fail_open` is published, and a per-process counter keeps a coarse ceiling. It is not shared across processes.
|
|
139
|
+
|
|
140
|
+
**`trusted_proxies` is required behind a load balancer.** The per-IP buckets use `request.remote_ip`, which follows `X-Forwarded-For` only from the host's `trusted_proxies`. Without it every request shares the proxy's IP and one bucket.
|
|
141
|
+
|
|
142
|
+
`login.plain_text.lockable` is a deprecated no-op; use `login.rate_limits`.
|
|
143
|
+
|
|
41
144
|
## Where to go next
|
|
42
145
|
|
|
43
146
|
| Need | Guide |
|
|
@@ -41,6 +41,18 @@ config.signup_session.jwt_secret = ENV.fetch("SIGNUP_SESSION_JWT_SECRET")
|
|
|
41
41
|
config.password_recovery_session.jwt_secret = ENV.fetch("PASSWORD_RECOVERY_SESSION_JWT_SECRET")
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
+
Boot guard: outside development/test (`Rails.env.local?`), the app raises `CommandTower::Errors::InsecureJwtSecretError` at `after_initialize` when `config.jwt.hmac_secret` is blank or the published default. Set a private secret. As a temporary escape hatch only, set `config.jwt.allow_insecure_default_secret = true` (or ENV `COMMAND_TOWER_ALLOW_INSECURE_JWT_SECRET=true`).
|
|
45
|
+
|
|
46
|
+
Password and email policy: `config.login.plain_text.password_length_min` / `password_length_max` (defaults 8 / 64) and `email_length_min` / `email_length_max` (defaults 3 / 254) are **inclusive**; a value of 8 accepts 8 characters. Earlier releases treated them as exclusive and served `min + 1` / `max - 1`. Passwords are also checked against a bundled top-100k common-password list; `config.login.plain_text.password_blocklist_paths` replaces it (`.gz` files are gunzipped). Clients read the result from `GET /auth/identity-policy`.
|
|
47
|
+
|
|
48
|
+
Auth mail delivery: `config.login.mail_delivery = :later` (default) sends password-reset and email-verification mail from ActiveJob so requests never wait on mail; hosts need a working ActiveJob queue adapter. `:inline` performs the job in the request (useful for tests and hosts without a worker).
|
|
49
|
+
|
|
50
|
+
Self-service username: `config.username.self_service` (default `false`) lets a user set their own username through `PATCH /me/username`; `config.username.self_change` (default `false`) also lets a user who already has one change it; `config.username.prompt` (`after_signup` default, or `off`) tells clients whether to show the post-signup step. All three are served by `GET /auth/identity-policy`, and `self_service` / `self_change` drive the `editUsername` capability on `GET /me`. Grant `me_username` and `me_username_availability` to the roles that may use it ([09 RBAC](09-rbac.md)). Contract: [API reference](../api_reference.md#patch-meusername).
|
|
51
|
+
|
|
52
|
+
Rate limits: `config.login.rate_limits.*` ships with safe defaults (soft per-account lockout, per-IP ceilings, verification send caps); set a value to `0` to disable one bucket. Hosts behind a load balancer must configure `trusted_proxies` or all clients share one IP bucket. `config.login.plain_text.lockable` is a deprecated no-op. Settings and defaults: [Authentication](../authentication.md#rate-limits-and-soft-lockout).
|
|
53
|
+
|
|
54
|
+
Existing deployments: run `command_tower:user_secrets:clear_plaintext` once after migrating to digest and blank legacy plaintext secrets.
|
|
55
|
+
|
|
44
56
|
Exact setter names are in the generated initializer comments and [`../initializing.md`](../initializing.md). Match those names; do not invent parallel keys.
|
|
45
57
|
|
|
46
58
|
### Cookies / CSRF (required for Command Tower frontend on web)
|
data/docs/bootstrap/09-rbac.md
CHANGED
|
@@ -48,7 +48,9 @@ Rails.application.config.middleware.insert_before 0, Rack::Cors do
|
|
|
48
48
|
end
|
|
49
49
|
```
|
|
50
50
|
|
|
51
|
-
`headers: :any` already covers the `X-UI-Catalog` and `X-
|
|
51
|
+
`headers: :any` already covers the `X-UI-Catalog`, `X-Time-Zone`, `X-Installation-Id`, `X-Client-Platform` and `X-App-Version` request headers. A host that lists allowed headers explicitly must add all five.
|
|
52
|
+
|
|
53
|
+
`X-Installation-Id` (native clients, a UUID v4) identifies the app install. Web clients get it from the HttpOnly `ct_installation` cookie that login plants, so the CORS `credentials: true` setting above is required for it too. `X-Client-Platform` (`web`, `ios`, `android`) and `X-App-Version` (`MAJOR.MINOR.PATCH`) are optional. In cookie mode, login leaves `token` out of the response body only for `web` at or above `config.session.omit_body_token_min_app_version`; every other client still receives it. See [cookie guide](../cookie_authentication_guide.md#installation-id-and-body-token).
|
|
52
54
|
|
|
53
55
|
`credentials: true` requires an **explicit origin list**, not `*`. Compose already passes `CORS_ALLOWED_ORIGINS` from step 01. The sample origins `8081`, `8082`, and `19006` belong to one web product. Add the origin this Expo web app actually uses, and keep it aligned with `config.application.url` and the API’s published port.
|
|
54
56
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Authenticated Password Change Workflow
|
|
2
2
|
|
|
3
|
-
Authenticated password change lets a signed-in user replace their password by proving knowledge of the current password. On success, CommandTower rotates `verifier_token` in the same transaction as the password digest update, invalidating **all** existing JWT sessions (including the caller’s). The API does **not** re-issue a JWT; hosts must clear local auth and send the user through Sign In again.
|
|
3
|
+
Authenticated password change lets a signed-in user replace their password by proving knowledge of the current password. On success, CommandTower rotates `verifier_token` in the same transaction as the password digest update, invalidating **all** existing JWT sessions (including the caller’s) and ending every device session (see [Authentication](authentication.md#session-lifecycle)); old tokens then answer `401` `session_revoked`. The API does **not** re-issue a JWT; hosts must clear local auth and send the user through Sign In again.
|
|
4
4
|
|
|
5
5
|
This is distinct from [password recovery](password_reset_workflow.md), which is public and recovery-session/token-based.
|
|
6
6
|
|
|
@@ -25,10 +25,12 @@ This is distinct from [password recovery](password_reset_workflow.md), which is
|
|
|
25
25
|
{
|
|
26
26
|
"current_password": "string",
|
|
27
27
|
"password": "string",
|
|
28
|
-
"password_confirmation": "string"
|
|
28
|
+
"password_confirmation": "string (optional)"
|
|
29
29
|
}
|
|
30
30
|
```
|
|
31
31
|
|
|
32
|
+
`password_confirmation` (or `passwordConfirmation`) is optional. When sent and different from `password` the request fails; when absent no comparison is made.
|
|
33
|
+
|
|
32
34
|
## Success (200)
|
|
33
35
|
|
|
34
36
|
Serialized success payload (message only). Response effects include `clear_token: true` so cookie/header sessions are cleared. No JWT, verifier, or password material is returned.
|
|
@@ -36,9 +38,9 @@ Serialized success payload (message only). Response effects include `clear_token
|
|
|
36
38
|
## Service flow (under the workflow)
|
|
37
39
|
|
|
38
40
|
1. Authenticate `current_password`
|
|
39
|
-
2.
|
|
41
|
+
2. If `password_confirmation` was sent, confirm it matches `password`
|
|
40
42
|
3. Enforce configured password length bounds
|
|
41
|
-
4. In one DB transaction: persist new password digest → `reset_verifier_token!`
|
|
43
|
+
4. In one DB transaction: persist new password digest → `reset_verifier_token!` → revoke all device sessions (`RevokeAll`, reason `password_change`), including the caller's
|
|
42
44
|
5. On failure: typed application errors → workflow HTTP mapping
|
|
43
45
|
|
|
44
46
|
## Failures
|
|
@@ -53,6 +53,22 @@ config.jwt.cookie.csrf.cookie_name = "other_csrf"
|
|
|
53
53
|
1. `Authorization: Bearer <token>` header (wins when present)
|
|
54
54
|
2. HttpOnly JWT cookie when cookie mode is enabled
|
|
55
55
|
|
|
56
|
+
## Sessions and the cookie
|
|
57
|
+
|
|
58
|
+
Login starts a device session and the JWT carries its `sid`. The session's idle and absolute timeouts (`config.session`) decide when it ends; see [Authentication](authentication.md#device-sessions). When a session has ended, the API answers `401` with code `session_expired` or `session_revoked` in the envelope `{ "data": null, "errors": [{ "code", "message" }] }`, and clears the cookie.
|
|
59
|
+
|
|
60
|
+
On a cookie-sourced `GET /auth/session` refresh the new token is set in the cookie only. The `X-Authorization-With-Reset` response header is sent only when the request used a bearer token.
|
|
61
|
+
|
|
62
|
+
## Installation id and body token
|
|
63
|
+
|
|
64
|
+
The HTTP boundary reads an installation id from the `X-Installation-Id` header first, then the `ct_installation` cookie. Only a UUID v4 is accepted; anything else is ignored. A cookie-mode login that arrives without an id gets a fresh one and sets `ct_installation` (HttpOnly, 400 days, same `SameSite` / `Secure` / `domain` options as the auth cookie). When the client already sent the header (native), no cookie is set. Starting a session replaces the same installation's earlier session and records the `X-Client-Platform` and `X-App-Version` values.
|
|
65
|
+
|
|
66
|
+
In cookie mode, `POST /auth/plain-text/login` omits `token` from the body (`tokenExpiresAt` stays) only when `X-Client-Platform` is `web` and `X-App-Version` is at or above `config.session.omit_body_token_min_app_version` (default `0.4.0`, ENV `COMMAND_TOWER_SESSION_OMIT_BODY_TOKEN_MIN_APP_VERSION`). Turn the behavior off with `config.session.omit_body_token = false` (ENV `COMMAND_TOWER_SESSION_OMIT_BODY_TOKEN=false`). Native clients, older web clients and requests without the headers keep the body token.
|
|
67
|
+
|
|
68
|
+
## Legacy token upgrade
|
|
69
|
+
|
|
70
|
+
`GET /auth/session` with a valid sid-less (legacy) token creates a device session for it and returns a replacement token that carries the `sid` (set in the cookie, or in `X-Authorization-With-Reset` for bearer). The session row is keyed by the legacy token's `generated_at`, so concurrent upgrades produce one session, and it expires at `generated_at + absolute_timeout`. The upgrade wins over a plain refresh and never rotates the CSRF cookie. Revoking the upgraded session also ends the legacy token (`401` `session_revoked`). Disable with `config.session.upgrade_legacy_tokens = false` (ENV `COMMAND_TOWER_SESSION_UPGRADE_LEGACY_TOKENS=false`).
|
|
71
|
+
|
|
56
72
|
## Login / logout examples
|
|
57
73
|
|
|
58
74
|
Paths are engine-relative. Prefix with your mount (generator often mounts at `/`; hosts may use `/api`).
|
|
@@ -158,7 +174,7 @@ allow do
|
|
|
158
174
|
end
|
|
159
175
|
```
|
|
160
176
|
|
|
161
|
-
`headers: :any` covers the `X-Time-Zone` and `X-
|
|
177
|
+
`headers: :any` covers the `X-Time-Zone`, `X-UI-Catalog`, `X-Installation-Id`, `X-Client-Platform` and `X-App-Version` request headers. A host that lists allowed headers explicitly must add all five.
|
|
162
178
|
|
|
163
179
|
`SameSite=None` cookies require `Secure=true` (HTTPS). Prefer same-site deployments with `SameSite=Lax` when possible.
|
|
164
180
|
|