Commit graph

284 commits

Author SHA1 Message Date
f2cd3488ee
fix heartbeat validation rejecting git-describe version strings
the version regex only allowed [a-zA-Z0-9.] in semver suffixes,
which rejected hyphens from git-describe output (e.g. 0.1.0-5-gabcdef0).
this caused every heartbeat to fail validation, preventing last_seen_at
from updating, which led to agent status showing "warning" and eventual
channel disconnect after 360s.

also accept bare git SHAs and short identifiers like "dev".
2026-02-11 11:31:19 -06:00
c5d8d73a0c
add row_link to table component for proper anchor tags
Replace phx-click JS.navigate with real <.link navigate> elements
on table rows so users can Ctrl+Click to open in new tabs, use
right-click context menus, and navigate via keyboard. Adds row_link
attr to <.table> core component and applies it to all agent tables.
Converts device list custom table from phx-click to inner links.
2026-02-11 08:46:03 -06:00
77cf289058
Add real-time device list with PubSub and LiveView streams
Broadcast org-scoped PubSub events from Devices context mutations
(create, update, delete, status change). Convert DeviceLive.Index
from assigns to streams with flat row items. Subscribe on mount so
the device list updates automatically across browser tabs.
2026-02-10 17:38:58 -06:00
4d73e77f3a
Add 404-based brute force protection system
Implements automated detection and blocking of IPs exhibiting scanning behavior (5+ unique 404s within 1 minute).

Key features:
- Progressive ban escalation (5 min → 1 hour → permanent)
- CIDR range and exact IP whitelisting
- Redis-backed 404 path tracking with 60s TTL
- Cloudflare WAF integration for permanent bans
- Admin UI for whitelist and blocked IP management
- Oban cron jobs for cleanup (expired bans, stale violations)
- ETS caching for whitelist performance

Components:
- Plug: ToweropsWeb.Plugs.BruteForceProtection
- Context: Towerops.Security.BruteForce
- Schemas: IpBlock, IpWhitelist
- Workers: CloudflareBanWorker, ExpiredBanCleanupWorker, StaleViolationCleanupWorker
- Admin UI: /admin/security (superuser only)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 16:31:48 -06:00
c7df6a8569
Add CI-triggered mass agent update webhook
POST /api/v1/webhooks/agent-release triggers all connected agents
to self-update via their existing WebSocket channels. Authenticated
with a shared secret (AGENT_WEBHOOK_SECRET env var).

- Add ReleaseChecker.invalidate_cache/0 for fresh GitHub fetch
- Add Agents.list_updatable_agents/0 (enabled + seen < 10min)
- Add Agents.broadcast_mass_update/0 orchestration function
- Add WebhookAuth plug with timing-safe secret comparison
- Add AgentReleaseWebhookController with :webhook pipeline
- Configure AGENT_WEBHOOK_SECRET in dev/test/runtime configs
2026-02-10 13:40:32 -06:00
fbce65070a
Add agent restart and self-update commands
Add server-initiated restart and self-update capabilities for remote
agents. Restart broadcasts on the lifecycle PubSub topic causing the
agent to exit cleanly for Docker to restart. Self-update fetches the
latest release from GitHub, finds the matching binary for the agent's
architecture, and sends the download URL with SHA256 checksum.

- Add restart_agent/1 and update_agent/3 to Agents context
- Handle :restart_requested and :update_requested in AgentChannel
- Add superuser-only Restart and Update buttons on agent show page
- Add ReleaseChecker module for GitHub Releases API with 5-min cache
- Add arch field to AgentHeartbeat protobuf for architecture detection
- Store arch in agent metadata from heartbeat
2026-02-10 13:06:10 -06:00
c066399e18
Allow superadmins to view and edit any agent regardless of org
The admin agents page links to /agents/:id but the show and edit
pages were scoped to the current user's organization, causing 404s
for agents belonging to other orgs.
2026-02-10 12:19:20 -06:00
c1fca6276a
Add real-time updates to admin agents page via PubSub
Broadcast agent lifecycle events (created/deleted) on a separate
"admin:agents" topic so the admin page updates dynamically when
agents are added or removed from any organization.
2026-02-10 11:20:51 -06:00
183f2a89ac
Add admin agents page at /admin/agents
Superuser-only page showing all agents across all organizations
and cloud pollers in a single table with live-ticking timestamps
and real-time status updates via PubSub.
2026-02-10 10:56:10 -06:00
95eafd0c47
routeros fixes and latency rounding 2026-02-09 17:30:06 -06:00
4cfab3b1ee
Reliability improvements: agent channel, polling, discovery, batch ops
- Add Task.Supervisor for supervised background tasks in agent channel
- Discovery worker retries transient failures (max 3 attempts)
- Log silent polling timeouts with named task identification
- Track errors in batch ARP/MAC upserts instead of silently ignoring
- Discovery gracefully degrades on interface/sensor timeout (partial results)
- Synchronous job dispatch on agent join to prevent race condition
- Surface SNMP result, monitoring check, and backup processing errors
- Atomic delete-stale + upsert for neighbors/ARP/MAC (transaction)
- Discovery transaction timeout (60s) with duration logging
- Heartbeat timeout detection (5min) closes stale agent channels
- Live poll timeout (60s) notifies waiting LiveView on expiry
- Disconnect agent channel when token is disabled or deleted
- Debounce rapid assignment changes to prevent redundant job dispatches
- Sensor index deduplication via YAML index template substitution
2026-02-09 16:28:12 -06:00
3b8e1ea639
Reliability improvements: Task.Supervisor, discovery retries, polling visibility
- Add Towerops.TaskSupervisor to supervision tree, replace bare spawn/1
  in agent channel with supervised tasks for polling data processing
- Change DiscoveryWorker from max_attempts: 1 to 3 with retryable error
  classification (transient errors retry, permanent errors discard)
- Name all 9 parallel polling tasks and log timeouts/crashes instead of
  silently dropping results via Stream.run()
- Add tests for TaskSupervisor presence and error classification
2026-02-09 16:05:30 -06:00
2911a3c17d
test fixes 2026-02-09 15:30:52 -06:00
a50c8e6314
Use datestamp as agent version 2026-02-09 13:51:32 -06:00
623fe07081
wip 2026-02-09 12:44:37 -06:00
cedbc5abd1
fix: resolve critical data loss and protobuf schema bugs (Phase 1)
This commit addresses Phase 1 (CRITICAL - Data Loss Prevention) issues
from the comprehensive bugs and inconsistencies analysis.

CRITICAL FIXES:

1. Protobuf Schema Inconsistencies
   - Added missing job_id field (field 5) to SnmpResult message
   - Fixed AgentError message structure (job_id, message, timestamp)
   - Removed obsolete transport field from SnmpDevice struct
   - Regenerated protobuf code with protoc-gen-elixir
   - Prevents crashes when agent sends SNMP results or errors

2. Interface/Sensor Discovery Timeout Data Loss
   - Changed timeout behavior to return error instead of empty list
   - Prevents deletion of ALL existing interfaces/sensors on slow networks
   - Discovery fails gracefully instead of destroying historical data
   - Addresses commit 7a57f7c sensor discovery pipeline data loss issue

3. Polling Offset Schedule Mismatch
   - Fixed schedule_next_poll() to use offset only (not interval + offset)
   - Maintains consistent polling intervals across all executions
   - Prevents load bunching that offset was designed to prevent
   - Example: 300s interval with offset=94s now consistently polls every 5m

4. Always Reschedule Race Condition
   - Added should_continue_polling?() and should_continue_monitoring?()
   - Only reschedule if device is still enabled and should be polled by Phoenix
   - Prevents zombie jobs from continuing to poll disabled/deleted/reassigned devices
   - Stops race condition where stop_polling() is bypassed by in-flight jobs

Files Changed:
- priv/proto/agent.proto
- lib/towerops/proto/agent.pb.ex (regenerated)
- lib/towerops_web/channels/agent_channel.ex
- lib/towerops/snmp/discovery.ex
- lib/towerops/workers/device_poller_worker.ex
- lib/towerops/workers/device_monitor_worker.ex
- test/towerops/workers/device_poller_worker_test.exs

Test Results: All passing
- device_poller_worker_test.exs: 8 tests, 0 failures
- device_monitor_worker_test.exs: 3 tests, 0 failures
- discovery_test.exs: 13 tests, 0 failures

Remaining Phases:
- Phase 2 (HIGH): 8 data integrity issues
- Phase 3 (MEDIUM): 10 reliability issues
- Phase 4 (LOW): 3 cleanup issues

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-09 09:16:03 -06:00
3931a9c14a
more tests and fixes 2026-02-07 11:50:18 -06:00
3eb3d4890e
Merge branch 'feature/job-monitoring-dashboard'
# Conflicts:
#	lib/towerops/workers/device_poller_worker.ex
#	lib/towerops/workers/discovery_worker.ex
2026-02-06 19:01:08 -06:00
137d7c83ec
test: add comprehensive integration tests for monitoring dashboard
Added integration tests for real-time updates and metrics display.
Also fixed dialyzer warnings in worker event broadcasting by removing
unreachable error handling branches.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:41:08 -06:00
bb9e6f0b0c
feat: create MonitoringLive base structure with PubSub subscription
Add LiveView for real-time job monitoring dashboard:
- Subscribe to job:lifecycle PubSub topic for live updates
- Display health metrics (completed, failed, avg duration, active jobs)
- Show active operations with real-time updates
- Display problems section (stuck/failed job counts)
- Add router entry under /admin/monitoring

Tests verify PubSub subscription and basic rendering.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 18:27:40 -06:00
9f30d366b1 feat: add PubSub event broadcasting for job lifecycle
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:36:34 -06:00
9b0b000263
feat: add health metrics calculation module
Create JobMonitoring.Metrics module with calculate_all/0 to provide
comprehensive metrics including execution counts, success rates,
queue depths, and average execution times.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:31:27 -06:00
adbaeef83d
feat: add failed jobs and recent completions queries
Add list_failed_jobs/0 to return retryable and cancelled jobs
and list_recent_completions/1 to return completed, cancelled,
or discarded jobs with configurable limit.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:29:19 -06:00
a3cbf7f412
test: add edge case tests for stuck job detection 2026-02-06 16:27:12 -06:00
d845f372d0
feat: add stuck job detection with per-worker thresholds
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:21:23 -06:00
b2cc622036
test: add missing assertions for ordering and worker filtering 2026-02-06 16:17:26 -06:00
35c7328831
feat: add JobMonitoring context with list_active_jobs query
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 16:15:18 -06:00
d03ad72aec
Increase max OID values limit from 1,000 to 50,000
Fixes discovery failures on enterprise network devices with many
interfaces and routing table entries.

Issue:
Discovery was failing with "too_many_oids - OID values map exceeds
1000 entries" on SNMPv3 devices. Enterprise routers/switches during
discovery can easily return 10k-50k OIDs from:
- 100+ interfaces with 20-30 OIDs each
- System info, routing tables, ARP tables, neighbor tables
- Various MIB objects

The original limit of 1,000 was too restrictive for real-world devices
while still being intended as DoS protection.

Changes:
- Increase @max_oid_values from 1,000 to 50,000
- Update test to generate 50,100 OIDs (exceeds new limit)
- Add comment explaining why limit is set to 50k

This maintains DoS protection (prevents multi-million OID attacks)
while accommodating realistic device discovery scenarios.

All tests passing (5578 tests, 0 failures).
2026-02-06 10:41:30 -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
e363fbc691
Implement MacAddress and SnmpOid custom Ecto types
Continues the pattern of using custom Ecto types to create rich domain objects
and avoid primitive obsession. Adds two new custom types following the
established pattern from IPAddress.

## MacAddress Custom Type

Provides structured MAC address handling with:
- Multiple input format support (colon, hyphen, dot-separated, compact)
- Normalization to colon-separated lowercase (canonical format)
- SNMP binary format conversion (6-byte binary)
- Format conversion helpers (:colon, :hyphen, :dot, :compact)
- Comprehensive validation and error handling

### Supported Formats
- Colon: `00:11:22:33:44:55`
- Hyphen: `00-11-22-33-44-55`
- Dot (Cisco): `0011.2233.4455`
- Compact: `001122334455`
- SNMP binary: `<<0, 17, 34, 51, 68, 85>>`

All formats normalize to lowercase colon-separated format for consistency.

## SnmpOid Custom Type

Provides structured SNMP OID handling with:
- OID format validation (numeric and named)
- Normalization to dotted-decimal with leading dot
- OID resolution via SnmpKit (named → numeric)
- Helper functions (parent, child_of?, append)
- Integer list representation support

### Supported Formats
- Dotted-decimal: `.1.3.6.1.2.1.1.1.0`
- Numeric (no leading dot): `1.3.6.1.2.1.1.1.0`
- Named OID: `sysDescr.0` (with automatic resolution)
- Integer list: `[1, 3, 6, 1, 2, 1, 1, 1, 0]`

## Benefits

- **Type Safety**: Structured data with validation at cast time
- **Normalization**: Consistent storage format regardless of input
- **Rich API**: Helper functions for common operations
- **Zero Migration Cost**: No database changes needed
- **Better Errors**: Clear validation errors instead of DB constraint violations
- **Domain Modeling**: Code works with %MacAddress{} and %SnmpOid{} instead of strings

## Database Storage

Both types store as VARCHAR in the database:
- MacAddress: VARCHAR(17) - colon-separated format
- SnmpOid: VARCHAR(255) - dotted-decimal format with leading dot

## Test Coverage

Added comprehensive test suites:
- MacAddress: 47 tests covering all formats, roundtrips, edge cases
- SnmpOid: 49 tests covering OID operations, validation, helpers
- All 96 tests passing 

## Usage Example

```elixir
# Before (primitive obsession)
field :mac_address, :string
field :sensor_oid, :string

# After (rich domain types)
field :mac_address, Towerops.EctoTypes.MacAddress
field :sensor_oid, Towerops.EctoTypes.SnmpOid

# Usage
changeset
|> cast(attrs, [:mac_address, :sensor_oid])
# Validation happens automatically in cast/1
```

Files:
- lib/towerops/ecto_types/mac_address.ex (330 lines)
- lib/towerops/ecto_types/snmp_oid.ex (340 lines)
- test/towerops/ecto_types/mac_address_test.exs (380 lines)
- test/towerops/ecto_types/snmp_oid_test.exs (390 lines)
2026-02-06 09:41:54 -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
27950de26e
test: expand MIB.Compiler tests (46.15%)
Added 34 comprehensive tests covering:
- compile_string/2 - String compilation (7 tests)
- compile/2 - File compilation (2 tests)
- Integration with Parser (1 test)
- compile_all/2 - Batch compilation (4 tests)
- load_compiled/1 - Load compiled MIBs (3 tests)
- Compile options (validate, format, output_dir, optimize, etc.) (8 tests)
- Error handling (syntax errors, missing files, parse errors) (3 tests)
- Symbol table construction (2 tests)
- Dependency extraction (deduplication, single/multiple) (4 tests)
- Compiled MIB structure validation (2 tests)

All tests tagged @moduletag :yecc_required (excluded by default).
Tests use temporary directories for file I/O.Coverage: 46.15% (unchanged - tests excluded)
Total tests: 1,514 (all passing, 72 excluded)
2026-02-06 09:12:26 -06:00
b653932879
test: expand MIB.Parser tests (8.66% → 9.96%)
Added 80+ comprehensive tests covering:
- init_parser/0 - Parser initialization (2 tests)
- tokenize/1 - MIB tokenization (11 tests)
- parse/1 - MIB parsing (6 tests)
- parse_tokens/1 - Pre-tokenized parsing (3 tests)
- mibdirs/1 - Directory batch parsing (4 tests)
- Hex atom conversion and integration (3 tests)
- Error handling for malformed MIBs (4 tests)
- MIB structure parsing (MODULE-IDENTITY, TEXTUAL-CONVENTION, etc.) (4 tests)
- Complex MIB features (IMPORTS, SEQUENCE, INDEX, SIZE, ranges) (5 tests)
- Description cleaning edge cases (3 tests)
- Edge cases (large files, long identifiers, nested OIDs) (4 tests)
- Real-world MIB patterns (SNMPv2, tables, various syntax types) (7 tests)

Most parse tests tagged @tag :yecc_required (excluded by default).
Tokenize tests run without yecc dependency.
Coverage: 8.66% → 9.96% (+1.3%)
Total tests: 1,480 (all passing, 38 excluded)
2026-02-06 09:09:28 -06:00
055bef4cd7
Add comprehensive tests for MIB module (45 tests)
Create new test file for MIB facade module with tests for:
- compile/2 (16 tests) - file paths, all options, error handling
- compile_string/2 (11 tests, @tag :yecc_required) - MIB content parsing
- load_compiled/1 (7 tests) - loading compiled MIB files
- compile_all/2 (13 tests) - batch compilation with dependency order
- Option validation (3 tests) - handling invalid option keys
- Return value structure (4 tests) - tuple format verification
- Error handling (4 tests) - graceful handling of invalid inputs
- Default options (3 tests) - behavior with and without options

Tests verify proper delegation to Compiler module and
correct error handling for file operations.

Note: compile_string tests tagged with :yecc_required since
they depend on yecc parser generator being available.

Coverage: 1,419 → 1,464 tests, 45 passing

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 09:01:49 -06:00
b42ac8f999
Expand PDU.V3Encoder tests (22 new tests)
Improve coverage from 37.97% to 40.64% with tests for:
- PDU types in SNMPv3 messages (get_next, get_response, set, getbulk)
- Context engine ID and context name (empty, non-empty, both)
- Message max size variations (minimum 484, custom values)
- Multiple varbinds in v3 messages
- Error responses with various error_status values (0-5)
- Reportable flag variations (true/false)
- USM security model
- All SNMP value types (counter64, gauge32, ip_address, opaque, oid)
- Exception values (no_such_object, no_such_instance, end_of_mib_view)
- Message ID edge cases (0, max 2147483647)
- Discovery message consistency

Tests verify message encoding completes without crashes
even when V3 security processing is involved.

Coverage: 1,391 → 1,419 tests, all passing

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 08:57:48 -06:00
14ec708e93
Add comprehensive tests for PDU.Encoder (87 tests)
Improve coverage from 43.82% to 75.84% with tests for:
- Message encoding (SNMPv1, v2c, v3 delegation)
- PDU encoding (all PDU types: get, getnext, response, set, getbulk)
- Varbind encoding (explicit types, auto types, all SNMP value types)
- Integer encoding edge cases (zero, small, large, negative)
- Counter32/Gauge32/Timeticks (min/max values)
- Counter64 (0 to 18446744073709551615)
- String encoding (empty, short, long, special chars, binary)
- OID encoding (simple, large subids, very large subids, long OIDs)
- Bulk request encoding (non_repeaters, max_repetitions)
- Exception values (no_such_object, no_such_instance, end_of_mib_view)
- Length encoding edge cases (short, medium, long form)
- Error handling (invalid formats, missing fields)
- Complete integration tests (GET/GETNEXT/SET/GETBULK)

Coverage: 1,304 → 1,391 tests, all passing

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 08:53:52 -06:00
07977bc16f
test: add comprehensive tests for MIB.SnmpTokenizer
Added complete test coverage for MIB.SnmpTokenizer module (32.93% -> target higher):

**Tokenization Tests:**
- Empty input handling
- Simple MIB header (DEFINITIONS, BEGIN, END)
- Reserved word recognition (30+ SMI keywords tested)
- Identifier tokenization (lowercase atoms, uppercase variables)
- Number tokenization (integers, negative numbers, leading zeros, large numbers)
- String tokenization with quotes
- Special characters (::=, {}, (), commas, semicolons, dots)
- OID notation
- Complete OBJECT-TYPE definitions
- Access modifiers (read-only, read-write, not-accessible, read-create)
- SMI types (INTEGER, OCTET STRING, Counter32, Gauge32, TimeTicks, IpAddress)
- Hyphenated keywords (OBJECT-TYPE, MAX-ACCESS, MODULE-IDENTITY, etc.)

**Format and Syntax:**
- Whitespace handling (spaces, tabs, newlines)
- Comment handling (-- comments)
- Multiline input
- Line number tracking
- Token order preservation
- Complex MIB structures (IMPORTS, MODULE-IDENTITY, etc.)
- SIZE constraints
- SEQUENCE OF notation

**Error Handling:**
- format_error/1 for illegal characters
- Unterminated string errors
- Unterminated quote errors
- Unknown error formatting

**Edge Cases:**
- Very long identifiers (up to 200 chars)
- Many tokens (100+ identifiers)
- Deeply nested braces
- Mixed case keywords (case-sensitive)
- Empty strings
- Consecutive operators
- Tabs and mixed whitespace
- Numbers with leading zeros
- Very large numbers

**Reserved Word Coverage:**
- All common SMI/SMIv2 reserved words tested
- Distinction between reserved words and similar identifiers
- Case-sensitive recognition

40 new tests added
Test count: 1,264 -> 1,304 (all passing)
2026-02-06 08:45:23 -06:00
42895fea8f
test: add comprehensive tests for MIB.Error
Added complete test coverage for MIB.Error module (16.13% -> target 100%):

**Error Creation:**
- All supported error types (syntax, semantic, import, type, constraint, etc.)
- Error creation with line and column information
- Error creation with context maps
- Suggestion generation for common mistakes

**Error Types Tested:**
- unexpected_token with various combinations (expected/actual/value)
- unexpected_eof with expected values
- unterminated_string
- invalid_number and invalid_identifier
- file_not_found with path
- import_error with symbol and module
- duplicate_definition with name
- Generic error types

**Suggestion Generation:**
- MAX-ACCESS vs ACCESS typo
- deprecated 'mandatory' vs 'current'
- OBJECT-TYPE vs OBJECT-IDENTITY confusion
- Unterminated string hints
- File not found with RFC/MIB name detection
- Import error dependency hints

**Error Formatting:**
- Format with/without line and column
- Format with/without suggestions
- Multiple suggestion formatting
- Edge cases (nil values, empty strings, non-standard types)

**Edge Cases:**
- All nil fields
- Large line numbers
- Zero/negative line/column values
- Various context data types
- Mixed token value types
- Empty options handling

53 new tests added
Test count: 1,211 -> 1,264 (all passing)
2026-02-06 08:38:33 -06:00
82b4dbdf28
test: add comprehensive tests for PDU.Constants and MIB.Logger
Added complete test coverage for two low-coverage modules:

**PDU.Constants (11.65% -> target 100%)**:
- Error status code accessors and conversions
- SNMPv3 constants (USM security model, max message size)
- PDU type constants and tag conversion (get, getnext, response, set, getbulk)
- Data type constants and tag conversion (all SNMP types)
- SNMP version normalization (:v1, :v2c, :v3)
- OID normalization (list and string formats)
- SNMPv3 message flags encoding/decoding
- Default message flags for security levels
- Error status code/atom conversion
- Roundtrip encoding/decoding verification
- 43 new tests

**MIB.Logger (11.11% -> target 100%)**:
- Compilation lifecycle logging (start, success, error, warning, complete)
- Batch compilation logging (start, progress, success, error)
- Parse progress and import resolution logging
- Code generation and tokenization statistics
- Dependency order and performance metrics
- Vendor quirk handling
- Warning logging with context
- Error type extraction and aggregation
- 40 new tests

Total: 83 new tests added
Test count: 1,128 -> 1,211 (all passing)
2026-02-06 08:36:20 -06:00
35ee87952f
test: expand Types module test coverage
Added comprehensive test coverage for previously untested functionality:

- IP address parsing (valid IPs, invalid inputs, IPv6 rejection)
- Zero-filling behavior for incomplete IPs (Erlang :inet standard)
- Type inference for all SNMP types (integers, strings, lists, booleans, nulls)
- Value decoding for all SNMP types (strings, integers, IPs, OIDs, exceptions)
- Value encoding with type inference and validation controls
- Unsigned32 validation (valid ranges, overflow, underflow)
- Coercion edge cases (IP addresses, unsigned32, octet_string, OIDs, booleans)

Fixes:
- Corrected type inference expectation for large integers (returns :unsigned32)
- Fixed boolean assertion to use equality check instead of pattern match
- Documented :inet.parse_address zero-fill behavior for incomplete IPs

Total: 97 tests, all passing
2026-02-05 17:24:10 -06:00
76d70dd3f4
Add comprehensive test coverage for SNMPkit modules
Added test suites for previously untested SNMPkit modules:

- ErrorHandler: Circuit breaker, retry logic, error classification (88.70% coverage)
- MIB.AST: AST node creation, validation, pretty printing (100% coverage)
- MIB.Preprocessor: MIB preprocessing, enumeration simplification (48.28% coverage)
- MIB.Utilities: OID resolution, type validation, error handling (85.60% coverage)
- PDU.V3Encoder: SNMPv3 message encoding/decoding (36.90% coverage)

All 1090 tests passing with no failures.
2026-02-05 17:03:41 -06:00
4e9a533106
Fix SNMPkit tests and add coverage for bang methods
Fixed 2 failing tests in HostParser that were using unreliable hostname resolution. Changed tests to use malformed IP addresses that will always fail validation consistently.

Added tests for SnmpKit.SNMP bang methods (get_bulk!, bulk_walk!) which have actual implementation logic beyond delegation.

All 954 SNMPkit tests now pass (0 failures).
2026-02-05 16:46:36 -06:00
8ee39a2d36
Add comprehensive tests for API authentication and authorization
Implemented tests for critical security modules with significant coverage improvements:
- ApiAuth plug: 0% → 100% (12 tests)
- Permissions module: 0% → 85% (32 tests)
- Devices API controller: 0% → 95% (22 tests)

Enhanced test fixtures to support membership roles and device creation with proper organization scoping.
2026-02-05 16:39:01 -06:00
c3d952148e
fix test warnings and failures
- Remove unused Ecto.Query import from device_poller_worker_test
- Update route paths from /orgs/:slug to /dashboard after navigation refactor
- Fix HostParser tests to match actual hostname resolution behavior
- Update UserAuth redirect assertions to expect /dashboard instead of /devices
- Fix DashboardLiveTest missing organization context
- Fix OrgLive.NewTest to verify organization creation correctly

All 4850 tests now passing with zero failures and zero warnings.
2026-02-05 15:24:41 -06:00
5342be99db
fix device count 2026-02-05 15:04:34 -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