Commit graph

117 commits

Author SHA1 Message Date
a2d96f8e6e
Implement hierarchical agent assignment for SNMP polling
Add three-level agent assignment hierarchy (Equipment > Site > Organization)
allowing flexible agent deployment strategies. Agents now receive only equipment
assigned to them through direct assignment or inheritance from site/organization
defaults.

Key changes:
- Add agent_token_id to Sites table with migration
- Implement get_effective_agent_token/1 for hierarchical resolution
- Add list_agent_polling_targets/1 to return polling targets per agent
- Update API config endpoint to use hierarchical polling targets
- Add agent assignment UI to equipment, site, and organization forms
- Show agent source (direct/site/org/none) in equipment form
- Add equipment count column to agent list
- Update terminology from "poll from server" to "cloud polling"

Tests:
- Add 8 comprehensive tests for list_agent_polling_targets/1
- Add end-to-end test for hierarchical config endpoint
- All 775 tests passing
2026-01-14 08:38:50 -06:00
b8bd952681
agent token changes 2026-01-13 13:43:43 -06:00
aa62cc7349
Move Create Agent buttons below input field
- Changed form layout from horizontal to vertical
- Agent name input now on its own line
- Create Agent and Cancel buttons on line below with gap-3 spacing
2026-01-13 13:22:18 -06:00
f9b575816a
Fix database ownership issues in agent auth tests
- Update AgentAuth plug to use synchronous heartbeat updates in test env
- Refactor async heartbeat logic to reduce nesting (Credo)
- Remove Process.sleep from tests (no longer needed with sync updates)

This fixes 'owner exited' database errors in the test suite by avoiding
async Task spawns during tests, which caused DB connection ownership
conflicts with Ecto's sandbox mode.
2026-01-13 13:16:54 -06:00
9ec14b7785
Add Agents navigation link to authenticated layout 2026-01-13 13:14:23 -06:00
3eb95b5f90
Streamline login flow and fix test failures
Login flow improvements:
- Remove "Welcome back!" flash message on successful login
- Auto-login users clicking magic links without confirmation prompt
- Always use "remember me" for magic link logins
- Fix Accounts.login_user_by_magic_link/1 to handle invalid token format

Test fixes:
- Add @tag :integration to Ping tests (require actual system ping)
- Add halt() calls to UserAuth.start_impersonation error paths

Users now go directly to their intended destination after clicking a
magic link, with no interruption for "log in and stay logged in" choice.
2026-01-13 13:08:24 -06:00
11bc5dec4a
no post login page 2026-01-13 12:27:17 -06:00
3068f944fb
Add TimescaleDB aggregate tests, implement on-demand calculation
- Updated Monitoring module to calculate hourly/daily stats on-demand from monitoring_checks table
- Removed TimescaleDB continuous aggregate dependency (disabled due to licensing)
- Enabled all previously skipped TimescaleDB tests with proper test data
- Fixed UUID encoding for SQL queries using Ecto.UUID.dump!
- Fixed Decimal handling in uptime percentage calculation
- Added test for get_uptime_percentage with nil checks
- Monitoring module now at 100% coverage
2026-01-13 08:09:12 -06:00
36175be74e
fix dialyzer and credo 2026-01-11 15:01:57 -06:00
5e1a97fcb3
fix tests 2026-01-11 14:58:55 -06:00
3ef04f261f
protobufs 2026-01-09 17:33:01 -06:00
cf77949527
add remote agent setup 2026-01-09 13:15:31 -06:00
4f924ba9a7
add passkey 2026-01-09 12:26:32 -06:00
9228d4a758
add navigation bar to login and registration pages 2026-01-08 09:45:51 -06:00
96bd8b3829
add MIB-based validation and generic profile tests
- Add MIB files from LibreNMS in priv/mibs/ for reference
- Create MibParser module to validate OIDs against official MIB definitions
- Add MIB validation tests to ensure hardcoded OIDs match MIB specs
- Refactor SNMP tests to be generic/behavior-focused instead of vendor-specific
- Remove vendor-specific test files (cisco_test, net_snmp_test)
- All 104 tests passing with automated OID validation
2026-01-08 08:57:21 -06:00
d8e29abf09
more tests and logging around email 2026-01-06 16:00:41 -06:00
c3303cc194
moar tests 2026-01-06 15:43:54 -06:00
23a0ba68b9
separate out marketing layouts 2026-01-06 14:46:39 -06:00
b3d2b95200
fix logo 2026-01-06 14:44:05 -06:00
41dcf3084f
add error pages 2026-01-06 14:37:48 -06:00
3b9fffdd07
add marketing site 2026-01-06 14:34:48 -06:00
7b1aa087d2
Add detailed context to SNMP error logs for better diagnostics
Enhance SNMP error logging to include:
- Target IP address
- SNMP version (v1/v2c)
- Timeout value in milliseconds
- OID being queried

Before:
  [warning] SNMP GET failed for "1.3.6.1.2.1.2.2.1.10.15729368": :timeout

After:
  [warning] SNMP GET failed for 192.168.1.1 (v2c, timeout: 5000ms) OID "1.3.6.1.2.1.2.2.1.10.15729368": :timeout

This makes it much easier to diagnose SNMP issues by immediately knowing which
device is timing out and what the network configuration is.

Updated all SNMP operations: GET, WALK, and GET-BULK.
2026-01-06 14:00:14 -06:00
fd317770fe
Fix health check logging with dynamic log level in endpoint
Use Plug.Telemetry's dynamic log level feature to disable logging for
/health requests. This is the proper Phoenix way to exclude specific
endpoints from request logs.

- Add log_level/1 function to endpoint that returns false for /health
- Configure Plug.Telemetry to use dynamic log level
- Remove log: false from router (handled by endpoint now)

This prevents Kubernetes health probe spam in application logs.
2026-01-06 13:57:32 -06:00
673ad13db8
Fix exit impersonation redirect to go to default org equipment page
When exiting impersonation, now redirects to the superuser's default
organization's equipment list page instead of /admin. Falls back to /orgs
if the superuser has no organizations.
2026-01-06 13:55:57 -06:00
139a42531f
Refactor credo issues: reduce complexity and nesting depth
- Refactor check_threshold_violation: extract threshold checks into separate functions (complexity 10→~3)
- Refactor load_sensor_chart_data: extract helper functions to reduce nesting
- Refactor save_equipment: extract SNMP discovery logic into helpers
- Refactor poll_sensors: extract error handling and result processing
- Refactor handle_status_change: extract equipment down/up handlers
- Refactor mount_current_scope: extract session scope building
- Refactor load_traffic_chart_data: extract aggregation and calculation helpers
- Refactor load_overall_traffic_chart_data: similar pattern to traffic chart
- Refactor load_sensor_chart_data in equipment_live/show: extract dataset builders
- Refactor discover_storage_sensors: extract storage sensor building
- Refactor perform_poll: extract device polling logic into separate functions

All 254 tests passing. Credo reports no issues.
2026-01-06 13:55:16 -06:00
02e0744c3c
Disable logging for health check endpoint
- Add log: false option to /health route to prevent K8s probe spam in logs
- Remove incorrect logger filter configuration from runtime.exs
2026-01-06 13:43:57 -06:00
e02c2d2b8f
Fix impersonation crash when session IDs are nil
Critical bug fix: fetch_current_scope_for_user and mount_current_scope
were calling Accounts.get_user(nil) when impersonating session flag was
true but superuser_id or target_user_id were nil.

This caused FunctionClauseError crashes for all logged-out users if they
had stale impersonation session data.

Changes:
- Check if both superuser_id and target_user_id exist before calling get_user
- Clear invalid impersonation state if IDs are missing
- Apply fix to both fetch_current_scope_for_user (controllers) and
  mount_current_scope (LiveViews)

This ensures graceful handling of corrupted/partial session state.
2026-01-06 13:32:17 -06:00
7df6e8b3b4
Redirect users to default org equipment page on login
Changed signed_in_path to redirect users to their default organization's
equipment page instead of the organization list.

Behavior:
- If user has organizations, redirect to first org's equipment page
- First org is determined by most recently joined (membership.inserted_at)
- If user has no organizations, redirect to /orgs to create one

This provides a better UX by landing users directly at their equipment
list instead of requiring an extra click through the org selector.
2026-01-06 13:30:07 -06:00
152c308b68
Add input validation for port numbers and SNMP testing
Security improvements to prevent potential issues:

1. Port Validation (normalize_port):
   - Validate port range is 1-65535
   - Use Integer.parse instead of String.to_integer to prevent crashes
   - Return default port 161 for any invalid input

2. SNMP Test Validation (validate_test_snmp_input):
   - Validate IP address format before allowing SNMP tests
   - Require non-empty community string
   - Prevent network scanning with invalid/missing IPs
   - Return clear error messages for validation failures

These changes ensure user input is properly validated and prevent:
- Integer overflow/underflow with ports
- Process crashes from invalid input
- Unauthorized network scanning via SNMP test feature
- SNMP requests with missing credentials
2026-01-06 13:28:30 -06:00
806b293ead
Fix impersonation to show correct user data and banner
Two issues were preventing impersonation from working correctly:

1. Templates were not passing current_scope to Layouts.authenticated,
   so the impersonation banner never displayed.

2. fetch_current_scope_for_user was looking up the user from the
   session token, which always pointed to the superuser. This caused
   the superuser to see their own organizations and equipment instead
   of the impersonated user's data.

Changes:
- Pass current_scope={@current_scope} to all Layouts.authenticated calls
- Store target_user_id in session during impersonation
- Fetch target user directly from database using target_user_id
- Update both fetch_current_scope_for_user (for controllers) and
  mount_current_scope (for LiveViews) to properly handle impersonation
- Clean up target_user_id from session when impersonation ends

Now when a superuser impersonates a user, they correctly see:
- The impersonation banner at the top with exit link
- The target user's organizations and equipment
- All data scoped to the impersonated user
2026-01-06 13:22:13 -06:00
a1e163d3ee
Add dialyzer type specs to refactored functions
Added comprehensive type specifications to all recently refactored
functions to improve type safety and enable dialyzer checking:

PollerWorker:
- detect_sensor_changes/3
- extract_thresholds/1
- detect_and_log_changes/4

EquipmentLive.Form:
- extract_snmp_config/1
- normalize_port/1
- test_snmp_connection/1

EquipmentLive.Show:
- seconds_to_weeks/1, seconds_to_days/1
- seconds_to_hours/1, seconds_to_minutes/1
- format_time_part/2

All specs use proper Elixir types and handle nil cases appropriately.
2026-01-06 13:12:55 -06:00
fb4da2df6d
Refactor handle_event SNMP test to reduce complexity
Extracted SNMP configuration extraction and connection testing
into separate helper functions, reducing cyclomatic complexity
from 11 to ~5.

- extract_snmp_config/1: Consolidates form data and params
- normalize_port/1: Handles port type conversion
- test_snmp_connection/1: Performs test and formats result

This makes the handle_event callback simpler and each concern
easier to test independently.
2026-01-06 13:11:07 -06:00
b328dfb96e
Refactor complex functions to reduce cyclomatic complexity
Refactored three highly complex functions to improve code maintainability:

1. PollerWorker.detect_sensor_changes (complexity 33 -> ~9):
   - Extracted threshold checking logic into separate functions
   - Split event creation into focused helper functions
   - Reduced nesting by using pipe operator pattern

2. PollerWorker.detect_and_log_changes (complexity 16 -> ~5):
   - Created separate functions for each interface change type
   - Extracted event building logic into dedicated functions
   - Improved readability with clear function names

3. EquipmentLive.Show.format_duration (complexity 13 -> ~5):
   - Extracted time unit conversion into separate functions
   - Simplified pluralization logic with pattern matching
   - Reduced nested conditionals

These changes make the code easier to test, maintain, and understand
while preserving all existing functionality.
2026-01-06 13:09:51 -06:00
77b41e0b24
Fix poller worker to use debug level for missing SNMP OIDs
The poller was re-logging SNMP errors from Client.get as warnings,
even though the client now logs them at debug level. Updated the
poller to also use debug level for expected errors like :no_such_object.

This completes the fix to reduce SNMP logging noise for devices
that don't support certain MIB objects.
2026-01-06 13:05:22 -06:00
20101201c6
Fix admin layout to use proper Phoenix component pattern
The admin layout was incorrectly defined as a separate .html.heex file
using @inner_content. Phoenix components should use render_slot(@inner_block).

Moved admin layout definition into layouts.ex as a proper function
component, matching the pattern used by app/1 and authenticated/1 layouts.
2026-01-06 13:04:22 -06:00
354e500405
Reduce SNMP logging noise for missing OIDs
Changed SNMP Client to use debug level for expected errors
(:no_such_object, :no_such_instance, :end_of_mib_view) and
only use warning level for actual communication errors.

This prevents log spam when polling interfaces that don't
support certain MIB objects, which is normal behavior.
2026-01-06 13:02:08 -06:00
837e2ea13f
Fix CSRF token error in impersonation banner
Replace raw HTML form with Phoenix .link helper using method="delete" to properly handle CSRF token in LiveView context. This fixes the UndefinedFunctionError when accessing /admin route.
2026-01-06 12:58:17 -06:00
a3cd43d2c2
Fix credo warnings and software design suggestions
Replace expensive length/1 comparisons with direct list comparisons or Enum.empty?/1 checks (13 instances in source code and tests). Add module aliases for Phoenix.HTML.Form and Towerops.Accounts.Scope to reduce nested module references.

Changes:
- Replace length(list) > 0 with list != [] or refute Enum.empty?(list)
- Add Phoenix.HTML.Form alias in CoreComponents
- Add Towerops.Accounts.Scope alias in ConnCase test helper

This eliminates all credo warnings and software design suggestions.
2026-01-06 12:55:22 -06:00
853d548f82
Add superuser system with user impersonation for admin support
Implement comprehensive admin interface allowing designated superusers to view all users and organizations, impersonate users for debugging, and perform administrative operations. All superuser actions are tracked in audit logs for compliance.

Features:
- Superuser authentication with dedicated admin routes at /admin
- User impersonation with session state preservation
- Admin dashboard with system statistics
- User and organization management interfaces
- Comprehensive audit logging with IP tracking
- Visual impersonation banner with exit capability
- Security controls preventing self-impersonation and superuser-to-superuser impersonation

Database:
- Add is_superuser boolean field to users table
- Create audit_logs table for tracking sensitive operations
- Set graham@mcintire.me as initial superuser
2026-01-06 12:50:10 -06:00
f29282d9dc
Fix compiler warnings in equipment monitor
- Prefix unused alert variables with underscore
- Remove unused test_env?/0 function

All warnings resolved, compilation clean with --warnings-as-errors
2026-01-05 14:37:03 -06:00
d5905cea73
Change storage display from chart to sensor list
- Display storage sensors as a list similar to temperature/voltage
- Show individual disk/partition usage with current values
- Link to graph view from sensor names
- More consistent with other sensor displays
2026-01-05 14:08:00 -06:00
bf301aa5fc
Enhance MikroTik discovery with comprehensive sensor support
Based on MikroTik MIB analysis, added discovery for:

Device Information:
- Board name, display name, build time

Health Sensors - Voltages:
- Core voltage, 3.3V/5V/12V supplies, input voltage

Health Sensors - Temperatures:
- Sensor chip, CPU, board, system, processor temperatures

Health Sensors - Power & Cooling:
- Power consumption (W), current draw (mA)
- Processor frequency (MHz)
- Active fan status, fan speeds (RPM)
- Power supply state, backup PSU state

POE Monitoring (per port):
- Voltage, current, power consumption
- Automatically discovers all POE-enabled ports

Optical/SFP Monitoring (per interface):
- Temperature, voltage
- TX/RX optical power levels (dBm)
- Supports fiber transceivers and SFP modules

All sensors include proper units, divisors, and descriptive names.
2026-01-05 14:06:46 -06:00
6c631cbe26
Add sensor value change tracking and threshold monitoring
- Add new event types: sensor_threshold_warning, sensor_threshold_critical, sensor_threshold_normal, sensor_value_spike, sensor_value_drop
- Implement sensor change detection in PollerWorker
- Track threshold violations (warning/critical high/low)
- Detect value spikes/drops for percentage sensors (30% change)
- Track return to normal from threshold violations
- Store threshold config in sensor metadata
- Update sensor last_value and last_checked_at on each poll
- Broadcast sensor events via PubSub for real-time logging
2026-01-05 14:01:35 -06:00
7ea79afea1
disable alert emails 2026-01-05 13:51:26 -06:00
be3a588e40
Fix boolean attribute rendering for traffic graph 2026-01-05 13:48:59 -06:00
ce7988b10d
Show traffic as mirrored bar chart with outbound above and inbound below zero axis 2026-01-05 13:40:13 -06:00
b6abe23493
Format traffic values in Mbps/Gbps and fix column layout 2026-01-05 13:38:07 -06:00
a57dfd2e26
Move traffic graph below device info and add zero axis line 2026-01-05 13:36:54 -06:00
703dfcf58c
Fix Float.round error in traffic graph calculations 2026-01-05 13:34:54 -06:00
2212bf9134
Make traffic graph header clickable and add dedicated graph page 2026-01-05 13:33:32 -06:00