Commit graph

323 commits

Author SHA1 Message Date
rcourtman
d219d9965d test: Add ValidateSession tests for API package
Add comprehensive tests for the ValidateSession wrapper function covering:
- Non-existent token (returns false)
- Empty token (returns false)
- Valid token (returns true)
- Expired token (returns false)

The ValidateSession function is a simple wrapper around the SessionStore's
ValidateSession method, but having direct tests ensures the wrapper is
exercised and documents its expected behavior.

Coverage: ValidateSession 0% → 100%
2025-12-02 13:22:45 +00:00
rcourtman
ef6a370144 test: Add ensureScope tests for API package
Add comprehensive tests for the ensureScope function covering:
- Empty scope parameter (always allows access)
- No token in context (session-based request, allows access)
- Token with matching scope (allows access)
- Token with multiple scopes including required one (allows access)
- Token missing required scope (rejects with 403)
- Token with empty scopes (defaults to wildcard, allows access)
- Rejection returns proper JSON response format

Coverage: ensureScope 0% → 100%
Coverage: API package 32.1% → 32.2%
2025-12-02 13:19:11 +00:00
rcourtman
d970055532 test: Add RequireAuth tests for API package
Add comprehensive tests for the RequireAuth middleware covering:
- No auth configured (allows access by design)
- API-only mode (rejects requests without token)
- API-only mode (accepts valid X-API-Token)
- Basic auth with invalid credentials
- Basic auth JSON vs plain text error responses
- Valid basic auth (allowed)
- Proxy auth (allowed)
- Proxy auth with invalid secret (rejected)
- Bearer token with basic auth configured (allowed)
- Invalid Bearer token (rejected)

Coverage: RequireAuth 7.1% → 78.6%
Coverage: CheckAuth 66.9% → 69.1%
Coverage: API package 31.9% → 32.1%
2025-12-02 13:09:48 +00:00
rcourtman
1073c511b3 test: Add RequireAdmin tests for API package
Add comprehensive tests for the RequireAdmin middleware covering:
- No auth configured (allows access by design)
- API-only mode (rejects requests without token)
- Basic auth with invalid credentials
- Proxy auth with admin role (allowed)
- Proxy auth with non-admin role (forbidden)
- Proxy auth with invalid secret (unauthorized)
- Proxy auth without role header (defaults to admin)
- Proxy auth with custom role separator
- Proxy auth with spaces in roles (trimmed)
- Basic auth authenticated users (allowed as admin)
- JSON vs plain text error responses based on path/Accept header

Also improves CheckProxyAuth coverage as a side effect.

Coverage: RequireAdmin 20.8% → 87.5%
Coverage: CheckProxyAuth 0.0% → 89.3%
Coverage: API package 30.9% → 31.9%
2025-12-02 13:06:06 +00:00
rcourtman
71e15886ed test: Add isRequestAuthenticated tests for API package
Add comprehensive tests for the isRequestAuthenticated function covering:
- Nil inputs (config, request, both)
- Basic auth (valid, invalid password, invalid username, malformed base64, missing colon)
- API token via X-API-Token header
- API token via Bearer authorization header (case insensitive)
- Invalid/empty/whitespace API tokens
- No auth configured scenarios
- Empty session cookie handling

Coverage: isRequestAuthenticated 26.1% → 82.6%
Coverage: API package 30.7% → 30.9%
2025-12-02 12:59:18 +00:00
rcourtman
cf6149e884 test: Add CheckCSRF tests for API package
Add comprehensive tests for the CheckCSRF function covering:
- Safe methods (GET, HEAD, OPTIONS) bypass
- API token authentication bypass
- Basic auth bypass
- No session cookie handling
- Missing CSRF token rejection with new token issuance
- Invalid CSRF token rejection with new token issuance
- CSRF token from FormValue
- Unsafe methods (POST, PUT, DELETE, PATCH) enforcement

Coverage: CheckCSRF 32.0% → 96.0%
Coverage: API package 30.5% → 30.7%
2025-12-02 12:53:32 +00:00
rcourtman
cd33c577f8 test: Add resolvePublicURL tests for API package
Add comprehensive tests for the resolvePublicURL function covering:
- Configured PublicURL (simple, trailing slashes, ports, whitespace)
- Request-derived URL (HTTP, HTTPS via TLS, X-Forwarded-Proto)
- No host fallback (with/without frontend port)
- Nil request handling

Coverage: resolvePublicURL 12.5% → 100%
Coverage: API package 30.3% → 30.5%
2025-12-02 12:45:04 +00:00
rcourtman
073d5ffa55 fix: Use --ctid instead of --standalone --http-mode in quick-setup command
The quick-setup command for temperature monitoring was generating
--standalone --http-mode which is meant for Docker deployments. This
confused users trying to set up multi-server Proxmox monitoring.

Now uses --ctid which works for both local and remote Proxmox hosts.
The installer detects when the container doesn't exist locally and
installs in "host monitoring only" mode automatically.

If we can determine the actual CTID from the host proxy summary,
we use it; otherwise we show <PULSE_CTID> for the user to replace.

Related to #785
2025-12-02 11:38:47 +00:00
rcourtman
350d21c80d test: Add diagnostics function tests for error handling
Add comprehensive tests for untested diagnostics functions:

- fingerprintPublicKey: 14 test cases covering empty/whitespace input,
  invalid key formats, truncated/malformed keys, and valid ED25519 keys

- countLegacySSHKeys: 8 test cases covering non-existent directories,
  empty directories, files without id_ prefix, multiple key types,
  and directory filtering (subdirectories not counted)

- resolveUserName: 4 test cases covering UID 0 (root), current user,
  non-existent UID fallback, and max uint32 boundary

- resolveGroupName: 4 test cases covering GID 0 (root/wheel), current
  group, non-existent GID fallback, and max uint32 boundary

Coverage: fingerprintPublicKey 0% -> 100%, countLegacySSHKeys 0% -> 100%,
resolveUserName 0% -> 100%, resolveGroupName 0% -> 100%
2025-12-02 03:39:52 +00:00
rcourtman
b053a2848b fix: Update TestPublicURLDetectionUsesForwardedHeaders for proxy hardening
The test was failing after commit d6cbfc23 added security hardening
that requires authentication and trusted proxy configuration for
X-Forwarded-* headers to be read during public URL detection.

- Add API token authentication to the test request
- Configure 127.0.0.1 as trusted proxy for the test
- Add export_test.go with ResetTrustedProxyConfigForTests() to allow
  external tests to reset the trusted proxy configuration
2025-12-02 03:16:52 +00:00
rcourtman
de90519b21 test: Add handleHealth method tests
Add 2 tests for health endpoint:
- POST/PUT/DELETE/PATCH return 405 Method Not Allowed
- HEAD is allowed (same as GET)

Coverage: 50% → 83.3%
2025-12-02 02:09:04 +00:00
rcourtman
5ff69a7e35 test: Add adminBypassEnabled tests
Add 5 tests to cover all branches:
- Not requested (ALLOW_ADMIN_BYPASS != "1")
- Enabled with PULSE_DEV=true
- Enabled with NODE_ENV=development
- Case-insensitive NODE_ENV check
- Declined when outside dev mode

Coverage: 40% → 100%
2025-12-02 01:53:55 +00:00
rcourtman
7ed8ef2074 test: Add loadTrustedProxyCIDRs tests
Cover invalid CIDR, invalid IP, IPv6, and empty entry handling (48% to 100%)
2025-12-02 01:48:41 +00:00
rcourtman
24fbce1281 test: Add LogAuditEvent tests
Cover success and failure logging branches (66.7% to 100%)
2025-12-02 01:46:27 +00:00
rcourtman
8f42156781 test: Add SecurityHeadersWithConfig tests
Cover all CSP/X-Frame-Options embedding configurations (57.1% to 100%)
2025-12-02 01:44:22 +00:00
rcourtman
07997b3516 test: Add filesystem error tests for SessionStore
Cover saveUnsafe (57.9% to 89.5%) and load (55.6% to 74.1%) error paths
2025-12-02 01:40:54 +00:00
rcourtman
21b69607f0 test: Add filesystem error tests for CSRFTokenStore
Cover saveUnsafe (57.9% to 89.5%) and load (50.0% to 67.9%) error paths
2025-12-02 01:38:49 +00:00
rcourtman
999f19beed test: Add filesystem error tests for RecoveryTokenStore.saveUnsafe
Cover MkdirAll, WriteFile, and Rename error paths (46.7% to 86.7%)
2025-12-02 01:36:21 +00:00
rcourtman
b3f88d7a8c test: Add edge case tests for HandleSetupScript
Tests method not allowed, missing type parameter, and invalid host
parameter error paths (71.4% to 79.2% coverage).
2025-12-02 01:11:57 +00:00
rcourtman
7d3de1bbcc test: Add invalid PEM data test for newOIDCHTTPClient
Tests the error path when a CA bundle file contains non-PEM data
(81.8% to 86.4% coverage).
2025-12-02 01:00:06 +00:00
rcourtman
1a595b3b2e test: Add edge cases for UniversalRateLimitMiddleware
Cover nil config initialization and static asset bypass paths.
Coverage: UniversalRateLimitMiddleware 87.5% -> 100%
2025-12-02 00:54:37 +00:00
rcourtman
c57c07f827 test: Add edge case for initializeBootstrapToken error path
Cover loadOrCreateBootstrapToken failure path.
Coverage: initializeBootstrapToken 92% -> 100%
2025-12-02 00:51:44 +00:00
rcourtman
a5f0482d97 test: Add edge cases for HandleLookup error paths
Cover method-not-allowed and missing lookup parameter paths.
Coverage: HandleLookup 88.4% -> 97.7%
2025-12-02 00:49:16 +00:00
rcourtman
6777257a7a test: Add edge cases for normalizeRequestedScopes
- Test blank scope identifier returns error
- Test wildcard-only input returns wildcard scope

Coverage: 89.7% → 96.6% (remaining 3.4% is defensive
unreachable code path)
2025-12-02 00:19:20 +00:00
rcourtman
b5d42f6e2e test: Add edge case for ensureSettingsWriteScope valid scope
Tests the code path when an API token has the settings:write scope,
which allows the operation to proceed.
2025-12-02 00:13:32 +00:00
rcourtman
8597eca010 Fix backup indicator being reset when VMs/Containers are re-polled
UpdateVMsForInstance and UpdateContainersForInstance were replacing
guest data without preserving the LastBackup field that was populated
by SyncGuestBackupTimes. This caused backup indicators to always show
"no backup found" since the LastBackup would be wiped every time
guests were polled (which happens more frequently than backup polling).

Now both functions preserve LastBackup from existing data when the
incoming guest data has a zero value.

Related to #762
2025-12-02 00:12:31 +00:00
rcourtman
9baf99d32a test: Add edge cases for isTrustedProxyIP and GetClientIP
Tests empty string, invalid IP, and IP not matching CIDR for
isTrustedProxyIP. Also adds tests for GetClientIP empty RemoteAddr
and X-Real-IP fallback paths.
2025-12-02 00:09:23 +00:00
rcourtman
02419827b6 test: Add tests for hostAgentSearchCandidates parameter variants
Tests all code paths: strict mode (both params), platform only,
and no params (generic paths).
2025-12-02 00:03:19 +00:00
rcourtman
7407447bbf test: Add edge case for handleServerInfo method not allowed
Tests that POST requests to /api/server/info return 405.
2025-12-02 00:01:17 +00:00
rcourtman
4751f57187 test: Add edge case for capturePublicURLFromRequest nil inputs
Tests the early return paths when router, request, or config are nil.
2025-12-01 23:59:17 +00:00
rcourtman
b9f9077496 test: Add edge case for canCapturePublicURL nil inputs
Tests the early return paths when config or request are nil.
2025-12-01 23:56:59 +00:00
rcourtman
f0688db9af test: Add edge case for recovery token load read error
Tests the error logging path when os.ReadFile fails with an error
other than ErrNotExist. Uses a directory in place of the file.
2025-12-01 23:54:42 +00:00
rcourtman
347d6b1cbb test: Add edge case for writeErrorResponse encode failure
Tests the error logging path when json.Encode fails due to a
write error on the ResponseWriter.
2025-12-01 23:52:21 +00:00
rcourtman
90d81f2217 test: Add edge cases for markAutoRegistered empty inputs
Tests the early return paths when nodeType or nodeName are empty.
2025-12-01 23:50:10 +00:00
rcourtman
3280fad5ae test: Add edge case for clearBootstrapToken remove failure
Tests the warning log path when os.Remove fails with an error other
than ErrNotExist. Uses a directory with contents to trigger ENOTEMPTY.
2025-12-01 23:47:58 +00:00
rcourtman
678c5aac5f test: Add edge cases for initializeBootstrapToken
- Nil router and nil config handling (no panic)
- OIDC enabled clears bootstrap token
Coverage: 80% to 92%.
2025-12-01 23:40:22 +00:00
rcourtman
8c40c7faa3 test: Add panic recovery test for ErrorHandler
Tests that panics in handlers are recovered and return 500.
Coverage: 91.7% to 100%.
2025-12-01 23:37:50 +00:00
rcourtman
d0c2524353 test: Add edge case for handleValidateBootstrapToken invalid JSON
Tests invalid JSON body triggers json.Decode error and returns 400.
Coverage: 90.5% to 100%.
2025-12-01 23:35:40 +00:00
rcourtman
890178acb0 test: Add edge case for RequireScope empty scope
Empty scope should allow all requests through without checking token.
Coverage: 84.6% to 100%.
2025-12-01 23:33:11 +00:00
rcourtman
0fa717a78a test: Add edge case for normalizeNodeHost URL parse error
Control character (null byte) triggers url.Parse error, covering the
'invalid host format' error branch. Coverage: 96.3% to 100%.
2025-12-01 23:28:32 +00:00
rcourtman
08765c7b59 test: Add edge case for DemoModeMiddleware WebSocket POST upgrade
Tests WebSocket upgrade with POST method in demo mode, ensuring the
websocket check branch is exercised after the GET/HEAD/OPTIONS check.
Coverage: 90% to 100%.
2025-12-01 23:24:06 +00:00
rcourtman
a5369ba2cd test: Add test for ErrorHandler empty URL path normalization
Covers the fix for issue #334 where empty path is normalized to '/'.
Coverage: 87.5% to 91.7%.
2025-12-01 23:21:07 +00:00
rcourtman
1fdb15c779 test: Add edge case tests for auth helper functions
- respondMissingScope: nil writer handling (80% to 100%)
- attachAPITokenRecord: nil record handling (80% to 100%)
- getAPITokenRecordFromRequest: wrong type and missing value (87.5% to 100%)
2025-12-01 23:15:04 +00:00
rcourtman
c71fb694bb test: Add edge case test for addQueryParam URL parse error
Add test case for URL containing control character (null byte)
which triggers url.Parse error and returns path unchanged.

Coverage improved from 88.9% to 100%.
2025-12-01 23:08:36 +00:00
rcourtman
37cc97952f test: Add comprehensive test cases for isPrivateIP function
Expand test coverage from 5 cases to 26 cases:
- Public IPv4/IPv6 addresses
- All RFC1918 private ranges (10.x, 172.16-31.x, 192.168.x)
- Loopback addresses (127.x.x.x, ::1)
- Link-local addresses (169.254.x.x, fe80::)
- Link-local multicast (224.0.0.x, ff02::)
- Unique local IPv6 (fc00::/7, fd00::)
- Edge cases: empty string, invalid IP, invalid format
- Addresses with port numbers

Coverage unchanged at 93.8% (remaining 6.2% is defensive
error handling for hardcoded valid CIDRs).
2025-12-01 22:54:56 +00:00
rcourtman
ef380df362 test: Add edge case tests for normalizeNodeHost function
Add 6 new test cases covering previously untested branches:
- Empty host returns error
- Whitespace-only host returns error
- Unknown node type keeps host without port
- Docker node type keeps host without port
- IPv4 address gets default port
- IPv4 with custom port preserved

Coverage improved from 92.6% to 96.3%.
2025-12-01 22:49:29 +00:00
rcourtman
4019b3006b test: Add tests for instance lookup and setup token validation
- Add TestFindInstanceNameByHost (12 test cases):
  - PVE instance lookup by host
  - PBS instance lookup by host
  - Unknown node types return empty
  - Empty config handling

- Add TestValidateSetupToken (8 test cases):
  - Empty token returns false
  - Valid/expired/used setup codes
  - Valid/expired recent setup tokens
  - Non-existent token handling
  - Precedence of setup codes over recent tokens

Both functions now have 100% coverage of their logic paths.
2025-12-01 22:19:30 +00:00
rcourtman
67a351fbd9 test: Add tests for webhook template generation and bootstrap token functions
- Add comprehensive tests for generatePayloadFromTemplateWithService covering:
  - Valid JSON template rendering
  - Invalid template syntax error handling
  - Template execution errors
  - ntfy service (plain text, skips JSON validation)
  - Various services (discord, telegram, pagerduty) JSON validation
  - Template function usage (upper, title)
  - Numeric and boolean values in templates
  - Special characters and empty template edge cases

- Add tests for bootstrapTokenValid covering:
  - Nil router handling
  - Empty hash and empty token cases
  - Valid token validation
  - Invalid token rejection
  - Whitespace trimming

- Add tests for clearBootstrapToken covering:
  - Nil router safety
  - Token file deletion
  - Missing file handling
  - Empty path handling
2025-12-01 22:07:40 +00:00
rcourtman
3233c48986 test: Add tests for API helper functions
- isRecentlyAutoRegistered: expiry logic, cleanup behavior
- clearAutoRegistered: key deletion, empty input handling
- normalizeDockerAgentArch: all arch variants, case handling, trimming
2025-12-01 21:33:45 +00:00
rcourtman
4973eb4c8a test: Improve coverage for cluster config handler functions
- deriveSchemeAndPort: 87.5% → 100%
  - Empty/whitespace string handling
  - Invalid URL parsing fallback
  - Host without port
- ensureHostHasPort: 91.7% → 100%
  - Empty port returns host unchanged
  - Protocol-relative URL handling (//host)
2025-12-01 14:46:00 +00:00