Commit graph

403 commits

Author SHA1 Message Date
f17ee2183c
fix: Use server-side timestamps for agent polling metrics
Replaces agent-supplied timestamps with server-side DateTime.utc_now()
to prevent clock drift issues between agents from causing weird graphs.

All metrics now use consistent server time regardless of polling method:
- Agent polling (via WebSocket): server time on receipt
- Phoenix polling (direct SNMP): server time on poll (already correct)

This ensures time-series data aligns correctly when graphing metrics
from devices polled by different agents with potentially different
system clocks.
2026-02-06 11:23:26 -06:00
bf4fee4846
feat: Add comprehensive agent polling for all discoverable data
Extended agent polling to collect all available SNMP data during regular
polls, not just sensors and interfaces. This ensures data stays current
and reduces reliance on periodic discovery runs.

Changes:
- Added polling queries for: neighbors (LLDP/CDP), ARP tables, MAC tables,
  IP addresses, HOST-RESOURCES processors and storage
- Process additional data using Replay adapter pattern to reuse existing
  parsing logic from discovery modules
- Made discovery helper functions public for reuse in polling context:
  save_neighbors/2, save_arp_entries/3, sync_ip_addresses/2,
  sync_processors/2, sync_storage/2
- Optimized by fetching interfaces once and reusing across operations
- Fixed compilation warnings by using proper guard syntax (list != [])

Technical details:
- Detection threshold: polls with more OIDs than sensors+interfaces
  are processed for additional data
- Background processing: spawns async process to avoid blocking metric
  recording
- Replay adapter: allows reusing discovery parsing logic without
  re-querying SNMP device
2026-02-06 11:18:36 -06:00
5f0549908e
Add IP address table walks to agent discovery queries
Fixes missing IP addresses tab on device page after agent-based discovery.

Issue:
Discovery was not collecting IP address data because the agent's
discovery job didn't include IP address table OID walks.

Root cause:
build_discovery_queries() walked interface tables, sensors, vendor MIBs,
and neighbors, but was missing the IP-MIB address tables.

Changes:
- Add new SnmpQuery to walk IP address tables during discovery:
  - 1.3.6.1.2.1.4.20 (ipAddrTable - IPv4, deprecated but widely supported)
  - 1.3.6.1.2.1.4.34 (ipAddressTable - RFC 4293, unified IPv4/IPv6)

This matches the OIDs used by Phoenix's direct discovery in
lib/towerops/snmp/profiles/base.ex discover_all_ip_addresses/1.

Result:
Agent now collects IP address data during discovery, which is then
synced to the database and displayed in the IP Addresses tab.

Tests: 5578 tests passing (1 pre-existing failure in unrelated Dahua test)
2026-02-06 11:05:59 -06:00
a4dd7210d8
Improve error logging for SNMP result validation failures
Add detailed error logging to show specific validation error type and
message when SNMP results fail validation. Also handle base64 decode
failures separately.

This will help diagnose validation issues introduced by recent strict
protobuf validation changes (commit 8044a6d1).
2026-02-06 10:36:37 -06:00
0a978746e1
Fix all Credo issues
Resolves 26 Credo warnings/issues:

Code Readability (2 issues):
- Break long line in mac_address.ex (line 316 > 120 chars)
- Break long @spec in agents.ex (line 332 > 120 chars)

Refactoring Opportunities (2 issues):
- Reduce cyclomatic complexity in device_live/form.ex
  - Extract helper functions to simplify SNMPv3 credential resolution
  - Split logic into smaller, focused functions
- Reduce nesting depth in snmp_oid.ex
  - Extract nested logic into separate helper functions

Warnings (22 issues):
- Fix comparison warning in validator.ex
  - Split validate_sensor_value/1 into separate clauses for int/float
  - Add credo directive for valid NaN check (value != value)
- Replace 21 expensive length/1 checks with Enum.empty?/1
  - Change assertions from `assert length(list) >= 1` to `refute Enum.empty?(list)`
  - Change assertions from `assert length(list) > 0` to `refute Enum.empty?(list)`
  - Affected files: device_poller_worker_test.exs, mib_test.exs,
    snmp_tokenizer_test.exs, parser_test.exs, error_test.exs, compiler_test.exs

All tests passing (5578 tests, 0 failures).
Credo now reports: "found no issues"
2026-02-06 10:31:09 -06:00
ed50257d8a
fix snmp v3 test 2026-02-06 10:21:54 -06:00
0a0ec23fc9
Fix all compilation warnings for --warnings-as-errors
Resolves all warnings in agent_channel.ex and validator.ex to enable strict
compilation mode.

agent_channel.ex changes:
- Removed unused aliases: AgentError, AgentHeartbeat, CredentialTestResult, SnmpResult
- Removed unused typep declarations: device_id, job_id, agent_token_id
- Prefixed unused variable with underscore: binary -> _binary
- Grouped handle_in/3 clauses together (moved credential_test_result handler)
- Removed @doc from private functions (safe_base64_decode)
- Removed unused private function safe_base64_encode/1

validator.ex changes:
- Removed unused alias: MikrotikSentence
- Prefixed unused parameter with underscore in validate_counter: field -> _field
- Commented out unused module attributes: @max_oid_length, @max_port, @max_interval_seconds
- Removed redundant validate_response_time(0.0) clause (covered by general case)
- Updated validate_response_time guard to use >= 0.0 instead of pattern matching on 0.0

All tests passing (3434 tests). Compilation now succeeds with --warnings-as-errors.
2026-02-06 09:57:04 -06:00
3fff0db784
Add comprehensive typespecs to agent-related modules
Adds @spec annotations to all public functions in agent-related modules for
better static analysis and documentation.

Changes:
- Added 17 typespecs to Towerops.Agents context module
  - All CRUD operations (create, read, update, delete, revoke)
  - Assignment management functions
  - Agent token resolution and lookup functions
  - PubSub broadcast function
- Added 9 typespecs to Towerops.Agents.Stats module
  - Agent health and metrics statistics
  - Device assignment breakdowns
  - Latency analysis and reassignment candidate detection
- Added typespec to Towerops.Workers.StaleAgentWorker
  - find_stale_agents/0 function
- Preserved existing typespecs in AgentChannel (socket types)

Benefits:
- Improved code documentation with clear function signatures
- Better static analysis via dialyzer
- Clearer API contracts for all agent management functions
- Type-safe UUID handling throughout agent system
2026-02-06 09:33:44 -06:00
20952a781f
add device count to superadmin 2026-02-06 09:32:13 -06:00
8044a6d140
Add strict protobuf validation for agent messages
Implements comprehensive validation layer on top of protobuf schema to
prevent malformed data, DoS attacks, and business logic violations.

Changes:
- Created Towerops.Agent.Validator module with strict validation for all
  agent message types (AgentHeartbeat, MetricBatch, SnmpResult, AgentError,
  CredentialTestResult, MikrotikResult)
- Added validation limits to prevent memory exhaustion and DoS attacks
  (max string lengths, collection sizes, numeric ranges)
- Added format validation for UUIDs, IP addresses, versions, hostnames
- Added enum validation for status and protocol fields
- Modified AgentChannel handlers to validate all incoming messages before
  processing
- Added comprehensive typespecs to AgentChannel for better static analysis
- Created safe_base64_decode/1 helper with error handling
- Added 32 comprehensive tests covering valid cases, invalid inputs, and
  edge cases

Security improvements:
- Prevents memory exhaustion via oversized strings and collections
- Validates all numeric fields are within expected ranges
- Checks UUID format for all ID fields
- Validates IP addresses and hostnames against RFC standards
- Rejects future timestamps and excessive values

Backward compatibility:
- Empty version and hostname strings allowed for older agents
2026-02-06 09:26:04 -06:00
156d9a47bf
UI improvements 2026-02-05 14:57:11 -06:00
cb0cc66768
fix mistaken poller ids 2026-02-05 13:57:15 -06:00
472482c4f5
fix nil firmware comparison 2026-02-05 13:47:56 -06:00
38eeb1c7b8
fix: improve agent polling and SNMP testing
Changes:
- Fix traffic graph to handle nil interface octets gracefully
- Add comprehensive tests for nil octets scenarios
- Fix agent polling query to support devices assigned directly to org (left join on sites)
- Fix test SNMP connection to inherit credentials from site/org
- Refactor agent_channel process_polling_result to reduce nesting (Credo)
- Add alias for JobCleanupTask in application.ex (Credo)

This fixes crashes when interface stats have nil octets and ensures
devices without a site assignment can be polled by agents.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-05 12:34:28 -06:00
987eae0408
fix: improve agent-based live polling with better logging and validation
- Added Logger.require for debug logging
- Refactored fetch_latest_agent_data to reduce nesting depth
- Added debug logging to trace agent assignment detection
- Check for nil/stale sensor readings and log appropriately
- Use actual reading timestamp instead of current time for data points

This will help diagnose why live polling shows 0 values and why
Phoenix SNMP disabled messages appear for agent-assigned devices.
2026-02-05 09:25:29 -06:00
e0592dbf3d
fix: use agent-collected data for live polling when agent assigned
Modified GraphLive live polling to check for agent assignments and use
agent-collected sensor data from the database instead of doing direct
SNMP polling. This respects the agent assignment and prevents Phoenix
from bypassing the agent for live graph updates.

Also refactored handle_params to reduce nesting depth.
2026-02-05 09:21:43 -06:00
dd8c97a45f
fix: handle devices without sites in GraphLive live polling
Devices can belong directly to organizations without sites. Fixed
perform_live_poll to check device.organization_id instead of
device.site.organization_id which caused BadMapError when site is nil.
Also removed unused Repo alias.
2026-02-05 09:16:11 -06:00
912cb8d280
fix: add missing handle_info for state_sensors_updated in GraphLive.Show
Adds handler to reload graph data when state sensors are updated via PubSub,
preventing GenServer crash when viewing graph page during sensor updates.
2026-02-05 09:14:21 -06:00
0d6caa897f
refactor: remove debug logging from SNMPv3 credential handling
Discovery is now working successfully with SNMPv3 after increasing
agent timeout to 60s. Removing the temporary debug logging that was
added to verify credentials were being properly decrypted and sent
to the agent.
2026-02-05 09:00:42 -06:00
b36da6f327
debug: log SNMPv3 credential lengths sent to agent
Added logging to show what SNMPv3 parameters are being sent from Phoenix
to the agent, including password lengths to verify they're decrypted
properly.
2026-02-05 08:35:09 -06:00
129bc9a8f4
fix: handle nil site in graph_live access check
Similar to previous fix - use device.organization_id directly instead of
device.site.organization_id to avoid BadMapError when device has no site.
2026-02-04 18:25:48 -06:00
c70b385db1
refactor: consolidate reorder handlers in device_live
Extract common pattern from perform_site_reorder/4 and perform_device_reorder/4
into a single perform_reorder/4 helper function.

Both reorder handlers now delegate to the shared helper, reducing duplication
and making the reload/regroup/flash pattern consistent.

- Reduces code from 40 lines to 28 lines
- Maintains identical behavior (all tests pass)
- Uses static gettext strings to satisfy compile-time requirements
2026-02-04 18:02:13 -06:00
aa0e7f3d05
help update 2026-02-04 17:56:48 -06:00
6f6627a54d
refactor: consolidate device count calculations in agent_live
Remove duplicate device counting logic by consolidating three identical
implementations into a single reusable function.

**Changes:**
- Refactor agent_live/index.ex mount/3 to use calculate_device_counts/1
- Delete duplicate calculate_cloud_poller_counts/1 function
- Replace all usages with calculate_device_counts/1

**Before:**
- Lines 31-47: Inline counting for agent_tokens and cloud_pollers
- Lines 312-318: calculate_device_counts/1
- Lines 320-326: calculate_cloud_poller_counts/1 (identical logic)

**After:**
- Single calculate_device_counts/1 function used everywhere
- ~20 lines removed

**Benefits:**
- Eliminates triple duplication of counting logic
- Single source of truth for device counting
- Easier to maintain and test

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-04 17:53:18 -06:00
6aab59dcf5
refactor: centralize LiveView access control checks
Extract duplicate access control logic from multiple LiveView files into
a reusable AccessControl helper module.

**Changes:**
- NEW: lib/towerops_web/live/helpers/access_control.ex
- NEW: test/towerops_web/live/helpers/access_control_test.exs
- Refactor device_live/index.ex to use AccessControl.verify_site_access/2
  and verify_device_access/2
- Refactor device_live/form.ex to use AccessControl.verify_device_access/2
- Refactor alert_live/index.ex to use AccessControl.verify_alert_access/2
- Refactor device_live/show.ex to use AccessControl.verify_device_access/2
- Remove unused Repo aliases from refactored files

**Benefits:**
- Reduces code duplication across 7+ locations
- Centralizes security-critical access checks
- Improves testability (helper module has >90% coverage)
- Consistent error handling across all LiveViews

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-04 17:51:05 -06:00
d16f09666f
snmp v3 ui fixes 2026-02-04 17:41:15 -06:00
dbb2412e89
tcp snmp test 2026-02-04 17:28:14 -06:00
89911bae9c
Device list bug fix 2026-02-04 16:49:17 -06:00
4f936d5549
device edit fix 2026-02-04 16:28:15 -06:00
6689eb27b4
prevent poller fallback when assigned poller is selected 2026-02-04 16:24:19 -06:00
031880c954
fix device page 2026-02-04 16:17:07 -06:00
fc66109f19
Add default organization feature
Features:
- Users can set a default organization in org settings
- First organization created is automatically set as default
- Default org selector only shown if user has 2+ organizations
- Migration auto-sets first org as default for existing users

Database changes:
- Added is_default boolean field to organization_memberships
- Added partial index for efficient default org lookups
- Migration sets oldest org as default for each existing user

UI changes:
- Organization settings page shows default org toggle
- Green badge displayed when org is already default
- Button to set org as default if it's not current default

Backend:
- Organizations.set_default_organization/2 manages defaults
- Organizations.get_default_membership/1 retrieves default
- Auto-set first org as default in create_organization/3
2026-02-04 16:09:43 -06:00
7a1317d0d0
API: Default organization_id to authenticated org when empty
When creating devices via API, organization_id is now properly defaulted
to the authenticated organization's ID even when an empty string is sent.

This fixes Terraform provider compatibility where organization_id may be
sent as "" instead of omitted entirely.

Before: Only checked if key was missing (Map.has_key?)
After: Also handles nil and empty string values
2026-02-04 16:03:20 -06:00
8382b5df6a
make devices site optional and many test fix 2026-02-04 15:05:42 -06:00
1a054fd598
make sites optional 2026-02-04 13:05:32 -06:00
4ef4f4fbf6
handle exceptions gracefully on api endpoints 2026-02-04 12:18:14 -06:00
09f2907ede
Remove debugging logs, fix Mix.env call 2026-02-04 12:10:48 -06:00
c93144cc37
snmp v3 support 2026-02-04 12:02:38 -06:00
3583624e0d
fix: prevent nil boolean error in device edit page
Fixed production bug where visiting the edit page for a device with no
SNMP discovery data would crash with "expected boolean on left-side of
'and', got: nil" error.

The mikrotik_device?/1 function was using && operator which returns nil
when device.snmp_device is nil, instead of returning false. The template
conditional on line 455 requires a proper boolean value.

Changed from:
  device.snmp_device && (...)

To:
  not is_nil(device.snmp_device) and (...)

This ensures the function always returns a boolean (true/false) instead
of potentially returning nil.

Added regression test to verify the page renders correctly when a device
has no SNMP discovery data yet.

Fixes: https://app.honeybadger.io/projects/136860/faults/127120431
2026-02-03 15:32:51 -06:00
ecf6edaf85
update docker compose instructions 2026-02-03 13:00:51 -06:00
c198fdeaa1
add snmp port 2026-02-03 12:51:50 -06:00
88d549cd92
more tests 2026-02-03 12:03:54 -06:00
5b84844e97
doc update 2026-02-03 09:07:06 -06:00
e181c17f78
fix: resolve MikroTik sensor values and empty SNMP communities
Fixes three critical issues affecting agent-based SNMP polling:

1. MikroTik gauge sensors incorrectly showing 10x values (223°C instead of 22.3°C)
   - Root cause: get_int_value() rejected zero values, causing mtxrGaugeUnit
     to be treated as nil and bypassing divisor logic
   - Fixed: Accept zero values and apply correct divisor=10 for temp/voltage/current/power

2. Empty SNMP community strings sent to agents causing authentication failures
   - Root cause: Devices with source="device" but null community weren't falling
     back to organization/site inheritance
   - Fixed: Enhanced resolve_snmp_community() to fall back to inheritance chain
     even when source="device" but community is empty

3. Continuous MikroTik API commands sent every 60s instead of once per 24h
   - Root cause: MikroTik jobs built on every poll cycle, not just discovery
   - Fixed: Only build MikroTik jobs during discovery phase

Migrations update existing data to fix incorrect divisor values and community
source tracking. Added comprehensive debug logging to diagnose future issues.
2026-02-02 17:12:36 -06:00
aaf8c38b78
handle mikrotik ssh 2026-02-02 16:42:18 -06:00
9a60bfec58
feat: migrate user settings and agent management to gettext
Migrates all remaining user settings and agent management flash messages to gettext:

User Settings:
- session_manager.ex: mobile device removal, alert preferences, browser session revocation, revoke all sessions
- totp_manager.ex: device creation, verification, deletion, recovery code generation
- api_token_manager.ex: token creation, deletion, validation errors
- user_auth.ex: policy consent acceptance message

Agent Management:
- agent_live/edit.ex: agent update success
- agent_live/index.ex: agent/cloud poller creation, token regeneration, agent deletion, global default settings

All flash messages now use domain-specific helpers (t_auth, t_equipment) for proper internationalization.

Tests passing: 4165 tests, 0 failures
2026-02-02 13:20:54 -06:00
3633ff1626
more gettext 2026-02-02 13:10:08 -06:00
0d85e85884
feat: migrate all remaining authentication and session flash messages to gettext
Completes the flash message migration by converting all remaining user-facing strings:

**UserAuth.ex changes:**
- All Plug functions: require_sudo_mode, require_authenticated_user, require_superuser
- load_current_organization error messages (3 messages)
- All LiveView on_mount callbacks (8 auth-related messages)
- Policy consent success message

**SessionManager.ex changes:**
- Mobile device session management (2 messages)
- Alert preferences updates (3 messages including conditional)

All messages now use t_auth() for consistent translation in the auth domain.

All tests passing (100 tests).
2026-02-02 13:02:44 -06:00
005235a54a
more gettext 2026-02-02 13:00:27 -06:00
2ef154e4d7
feat: migrate core components to gettext
Migrates consent prompt component strings to gettext for internationalization:
- Updated Policies modal title
- Policy review message
- Policy acceptance checkbox labels (Privacy Policy, Terms of Service)
- Consent disclaimer text
- Accept button text

All strings now use gettext() for translation support.
2026-02-02 12:49:13 -06:00