towerops/lib/towerops/mobile_sessions/mobile_session.ex
Graham McIntire 1d928d4356
security: implement comprehensive security audit fixes
Critical Fixes:
- Remove /health/time endpoint exposing system time information
  * Prevents attackers from detecting time sync issues for TOTP attacks
  * Removed route and controller function, updated tests
- Add email confirmation check to account data export
  * GDPR export now requires confirmed email address
  * Prevents unconfirmed accounts from accessing data export
- Add path traversal validation for MIB archive uploads
  * Extract to temp directory, validate all paths, then copy if safe
  * Prevents malicious tar/zip files from writing outside target directory
  * Added validate_extracted_paths/1 helper function

High Priority Fixes:
- Add comprehensive input validation for mobile auth
  * Length limits: device_name (255), device_os (100), app_version (50), push_token (512)
  * Prevents database corruption and storage exhaustion
- Add heartbeat rate limiting to agent channel
  * Limit database updates to once per 30 seconds (max ~2/min per agent)
  * Prevents malicious agents from exhausting database connections
- Sanitize 500 error responses
  * Return generic error messages to clients
  * Log full details server-side with request_id for support
  * Prevents leaking stack traces and module names
- Add message size limits to agent channel
  * 10MB maximum for all protobuf messages (result, heartbeat, error)
  * Prevents DoS attacks via oversized payloads

Medium Priority Fixes:
- Add GraphQL query depth limits (max_depth: 10)
  * Prevents DoS from deeply nested queries
  * Complements existing complexity limits

Code Quality:
- Refactor agent channel handlers to reduce nesting depth
  * Extract message processing into separate private functions
  * Fixes Credo warnings about excessive nesting
  * Improves code readability and maintainability

Files changed:
- lib/towerops_web/controllers/health_controller.ex
- lib/towerops_web/controllers/api/account_data_controller.ex
- lib/towerops_web/controllers/api/v1/mib_controller.ex
- lib/towerops/mobile_sessions/mobile_session.ex
- lib/towerops_web/channels/agent_channel.ex
- lib/towerops_web/controllers/error_json.ex
- lib/towerops_web/router.ex
- CHANGELOG.txt
- priv/static/changelog.txt
- test/towerops_web/controllers/health_controller_test.exs
- test/towerops_web/controllers/error_json_test.exs

All 7,424 tests passing.
2026-03-05 13:08:10 -06:00

109 lines
2.8 KiB
Elixir

defmodule Towerops.MobileSessions.MobileSession do
@moduledoc """
Schema for mobile app sessions.
Long-lived authentication tokens for mobile apps. Users can manage
their active mobile sessions from the web interface.
"""
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "mobile_sessions" do
field :token, :string
field :device_name, :string
field :device_os, :string
field :app_version, :string
field :last_used_at, :utc_datetime
field :expires_at, :utc_datetime
field :alerts_enabled, :boolean, default: true
field :push_token, :string
field :push_platform, :string
field :raw_token, :string, virtual: true
belongs_to :user, Towerops.Accounts.User
timestamps(type: :utc_datetime)
end
@doc """
Creates a changeset for a new mobile session.
Token is automatically generated if not provided.
Default expiration is 90 days from now.
"""
def create_changeset(mobile_session, attrs) do
mobile_session
|> cast(attrs, [
:user_id,
:device_name,
:device_os,
:app_version,
:token,
:expires_at,
:push_token,
:push_platform,
:alerts_enabled
])
|> validate_required([:user_id])
|> validate_length(:device_name, max: 255)
|> validate_length(:device_os, max: 100)
|> validate_length(:app_version, max: 50)
|> validate_length(:push_token, max: 512)
|> validate_inclusion(:push_platform, ["apns", "fcm", nil])
|> put_token()
|> put_timestamps()
|> unique_constraint(:token)
end
@doc """
Updates the last_used_at timestamp for a session.
"""
def touch_changeset(mobile_session) do
last_used_at = DateTime.truncate(DateTime.utc_now(), :second)
change(mobile_session, last_used_at: last_used_at)
end
defp put_token(changeset) do
if get_field(changeset, :token) do
changeset
else
token = generate_token()
changeset
|> put_change(:token, hash_token(token))
|> put_change(:raw_token, token)
end
end
@doc false
def hash_token(token) do
:sha256 |> :crypto.hash(token) |> Base.url_encode64(padding: false)
end
defp put_timestamps(changeset) do
now = DateTime.truncate(DateTime.utc_now(), :second)
default_expiration = now |> DateTime.add(90, :day) |> DateTime.truncate(:second)
changeset
|> put_change(:last_used_at, now)
|> put_default_expiration(default_expiration)
end
defp put_default_expiration(changeset, default) do
if get_field(changeset, :expires_at) do
changeset
else
put_change(changeset, :expires_at, default)
end
end
# Generate a secure random token (64 bytes = 512 bits)
defp generate_token do
64 |> :crypto.strong_rand_bytes() |> Base.url_encode64(padding: false)
end
end