220 Commits
Author SHA1 Message Date
TheWitness 2780258e7c Add 'Deepness' dark emerald-green theme to develop (with billboard overload CSS) (#8206)
* Add 'Deepness' theme to develop; midwinter billboard + deviceStatus hook

Forward-ports the Deepness theme (1.2.x #8202 + #8205) to develop as one change: the full include/themes/deepness/ theme (emerald-dark :root palette, Paw layout/top-tab JS, full billboard.js 3.13 overload CSS, dark widget CSS), the themes allowlist entry, the i18n_themes name, the midwinter billboard overload rules, and the shared 'deviceStatus' hook class in get_colored_device_status() that the theme styles as status pills. Paper-plane is intentionally untouched (worked separately). The lib/html.php favicon/arrow tweaks from 1.2.x are omitted - develop handles those via get_md5_include_icon()/get_theme_paths() and the theme's own .actionsDropdownArrow CSS.

* deepness: align main.js with Paw parent (drop stale host_id autocomplete & graphDrillDown, fix search-icon/handler leaks)

* deepness: drop bundled billboard.css (obsolete per-theme file; central include/css/billboard.css + main.css .bb overloads cover it)

* i18n: add 'Deepness' theme name to cacti.pot translation template

* Deepness: apply php-cs-fixer formatting and refresh sink inventory baseline

php-cs-fixer fixes the single-quote and // comment style in the deepness theme index.php/rrdtheme.php files, and the sink inventory baseline records the header_redirect sinks in the new deepness index.php files.

* tests: stop the boost upgrade integration test leaking IN_CACTI_INSTALL

BoostProcessTableUpgradeIntegrationTest defined IN_CACTI_INSTALL at file (collection) scope, so it was set for the whole shared pest process and made CactiErrorHandler() take its install-mode early-return. That broke CactiErrorHandlerSuppressionTest ('an enabled level is logged...' expected false, got true) in the pest coverage gate and the locked integration job. The upgrade files required here do not check the constant at load time (only lib/database.php does, at runtime inside its schema probes), so define it in beforeEach after the DB connects instead -- it is never set at collection time and, with no DB in CI, the test skips without defining it. Full pest suite: 2664 passed, 0 failed.
2026-10-07 14:16:56 -04:00
TheWitness 7de50e8fa5 Widen form_checkbox_cell() $id parameter to mixed (#8198)
Callers pass the row id straight from query results, which may be an int as
well as a string.  Declaring the second parameter as string forced an implicit
scalar coercion and was inconsistent with the sibling cell helpers
(form_selectable_cell(), form_selectable_ecell()) that already type $id as
mixed.  Accept mixed and update the docblock to match.
2026-10-06 14:21:41 -04:00
TheWitness 41e6d9e033 security: consolidate verified GHSA fixes for develop (batch 4) (#8145)
* security: consolidate verified GHSA fixes for develop (batch 4)

Develop counterparts of the 1.2.x batch-4 fixes in #8144, re-verified against
current develop HEAD.

- GHSA-4rmr-wvjq-qxc2: include/auth.php Basic Auth and guest branches fall
  through to the per-page realm check instead of returning early.
- GHSA-j67j-wpm4-9g3x: the pre-dispatch update_policy branch in user_admin.php
  and user_group_admin.php requires a CSRF-token POST. The denylist -> allowlist
  redesign is tracked for 1.3 in #8143.
- GHSA-2p3x-f5jm-rg6p: the View-Graphs -> poller RCE chain is broken by the
  realm check (4rmr), the update_policy guard (j67j) and shell-free webhits (x5pw).
- GHSA-x5pw-cg7j-mj4r: scripts/webhits.pl runs wc through a shell-free list-form open.
- GHSA-9737-rqh3-h7fh: names interpolated into raise_message() now use __esc()
  across the UI; URL- and HTML-bearing messages are excluded.
- GHSA-9x9h-2577-9w86: the colordropdown input is built as a node and the label
  is no longer round-tripped through parseHTML (the list item already used
  createTextNode on develop).
- GHSA-h96j-8xhc-2p3w: remote_agent.php authorizes on $_SERVER['REMOTE_ADDR'],
  not get_client_addr(), which honours client-settable proxy headers.

Regression guards under tests/Unit/Security/{Auth,Csrf,Xss,ShellInjection}.
php -l, check-changelog.py and the sink/architectural baselines all pass.

* chore: reference PR #8145 on the batch-4 1.3.0-dev CHANGELOG entries

* security: resolve develop merge - keep id-only xmlerror unescaped (matches #8141 h745 test)

* security(GHSA-j67j): use REQUEST_METHOD POST guard instead of raw \ (hardening-pattern-guard)

* security(GHSA-9737): fix review findings - drop double-encoding in __esc, escape missed name sinks, correct plugins format-arg count
2026-10-02 13:10:42 -04:00
TheWitnessandTheWitness 3ab4c69fb7 PHPStan Level 8 - Phase 1 Conversion (#8135)
* PHPStan Level 8 - Phase 1 Conversion

Reduces the real (no-baseline) PHPStan level 8 error count from ~2,724 to 425
and regenerates phpstan-baseline.neon accordingly (8,941 -> 1,921 lines).

Core type-safety changes
- lib/database.php: narrow db_fetch_row()/db_fetch_row_prepared() to return
  array (was bool|array) and db_fetch_assoc()/db_fetch_assoc_prepared() to
  return array (was mixed); the _prepared workers coerce the connection-failure
  path to an empty array so the declared type is honest. empty()/cacti_sizeof()
  checks are unaffected.
- lib/database.php: narrow $db_conn guards from is_object() to instanceof PDO in
  the transaction/quote/insert-id helpers so the PDO calls resolve.
- lib/mib_cache.php: the fluent MibCache methods mib()/object()/table()/row()
  now return self instead of a bare object so chained calls type-check.

Type-safety casts and guards (mechanical, behaviour-preserving)
- Cast string|false/|null builtin results feeding string parameters
  (json_decode, base64_encode, trim, htmle, preg_replace, explode, etc.).
- Cast int|string / int|false values feeding int id/pid parameters.
- Guard resource|false fopen()/popen() handles before fwrite/fclose/fread, and
  wrap foreach over array|false/list|false results with `?: []`.

Genuine bugs found and fixed
- cli/add_tree.php / lib/api_tree.php: site tree nodes could not be created via
  the CLI - the --site-id option was never parsed, $nodeTypes had no 'site'
  entry (passing null to api_tree_item_save(int $type) -> TypeError), and
  api_tree_item_save() never persisted site_id. All three fixed.
- tree.php: leaves_exist() is typed : int but returned db_fetch_assoc_prepared()
  (an array of rows) for a SELECT COUNT(*); now uses db_fetch_cell_prepared()
  and returns the scalar count.
- lib/mib_cache.php: $entries_per_object was a float (division / ceil) used as
  an array key (PHP 8.1 implicit float-to-int key deprecation); now cast to int.

Config
- .phpstan.neon: add notIdentical.alwaysTrue and booleanAnd.alwaysFalse to the
  existing always-true/false ignore family (same "PHPStan gets confused"
  dynamic-constant cause already covered by identical.alwaysTrue,
  notEqual.alwaysTrue, booleanAnd.leftAlwaysTrue, etc.).
- phpstan-baseline.neon: regenerated; the remaining 425 entries are the
  untouched long tail for Phase 2.

* Remove redundant @phpstan-ignore comments

Follow-up cleanup for the level 8 Phase 1 work. Removes 14 inline
@phpstan-ignore comments that no longer suppress any reported error:

- cli/repair_database.php: `@phpstan-ignore booleanAnd.alwaysFalse` is now
  covered by the global booleanAnd.alwaysFalse ignore added to .phpstan.neon.
- 13 others (host.php, include/global.php, include/session.php,
  lib/api_automation.php x2, lib/functions.php x2, lib/html_utility.php x2,
  lib/installer.php, lib/package.php, lib/reports.php, lib/rrd.php) no longer
  match any reported error after the type-safety fixes (e.g. the
  db_fetch_row_prepared() return-type narrowing removed the offset-assign
  errors the api_automation ignores were suppressing).

Verified with reportUnmatchedIgnoredErrors enabled: 0 unmatched ignores
remain and the full level 8 run still reports 0 errors.

* ci: satisfy validator ratchet and refresh security sink baselines

- lib/api_tree.php: give the new tree-item site_id a real numeric
  constraint ('^[-0-9]+$', matching html_reports.php) instead of an
  empty regex, so the validator constraint ratchet passes without
  bumping its baseline.
- tests/security/baselines: refresh the three sink/hotspot signatures
  whose code text changed from the (string) casts added in this branch
  (lib/poller.php setsid, cli/rrdresize.php json_encode, lib/import.php
  simplexml_load_string).

* ci(js): allow DOMPurify 3.4.16 and update sync_js pin test

The dependabot bump (#8134) moved package.json/package-lock.json to
DOMPurify 3.4.16 on develop but left tests/js/sync_js.test.mjs pinned to
3.4.15, so the PR merge commit fails the 'DOMPurify is pinned' contract.
Bring package.json/package-lock.json to 3.4.16 (matching develop) and
update the pin test to expect 3.4.16.

* test: update sql.php null-handling assertion for the (string) cast

This branch changed scripts/sql.php from trim(\ ?? '') to
trim((string) \) (the phpstan-safe form that coerces both null and
false from shell_exec()). Update SqlScriptsTest's null-return assertion
to match the new cast instead of the removed '?? ''.

* fix: address Copilot review - ownership IDs, fopen guards, mib_cache bound

- chown()/chgrp(): pass integer UID/GID from fileowner()/filegroup()
  (guarding the false lookup) instead of string-casting them, which made
  them resolve account/group names like '1001' and fail. Covers
  lib/api_device.php, lib/boost.php and poller_maintenance.php (x2).
- fopen() failure now short-circuits instead of reporting success:
  lib/package.php returns false, lib/clog_webapi.php and utilities.php
  render an error, and snmpagent_mibcachechild.php skips the cache write
  and sentinel unlink so a concurrent writer's lock is preserved.
- lib/mib_cache.php: keep the float quotient as the loop bound and cast
  only the array offset, so a non-even entries/columns split no longer
  truncates the loop and drops a cached row.

* revert: keep db_fetch_* returning false on error; baseline Level 8 instead

Per review, restoring the intentional fail-safe: db_fetch_row[_prepared]()
return bool|array and db_fetch_assoc[_prepared]() return mixed again, so a
genuine SQL error (not just a missing connection) is signalled as false and
the === false checks in cdef_is_in_use(), boost_process_* and aggregate.php
work as before. Dropped the is_array() ? : [] coercion.

Level 8 stays green by regenerating phpstan-baseline.neon to capture the
re-introduced bool|array/mixed call-site errors (the ~1,850 the narrowing
had eliminated). Tightening those callers to drop them from the baseline is
Phase 2 work.

---------

Co-authored-by: TheWitness <copilot@users.noreply.github.com>
2026-10-02 10:08:56 -04:00
TheWitnessandcopilot-swe-agent 2d516ca0a9 security: consolidate additional verified GHSA fixes for develop (batch 2) (#8065)
* security: contain data source paths within the RRA directory (GHSA-9qff-xccr-rrc5)

* security: escape executable path in exec_background on non-win32 (GHSA-cv7j-p6fh-j4q7)

* security: stop disabled accounts authenticating via remember-me cookie and revoke on disable (GHSA-pqrp-v752-mc4f)

* security: prefer base_url over client Host for the force_https redirect (GHSA-3466-fp7g-c9rf)

* changelog: add fragments for GHSA-9qff-xccr-rrc5, GHSA-cv7j-p6fh-j4q7, GHSA-pqrp-v752-mc4f, GHSA-3466-fp7g-c9rf

* security: address review findings on GHSA batch 2 (develop)

- lib/dsstats.php, poller_maintenance.php: route through
  get_data_source_path() instead of expanding data_source_path directly,
  so the RRA containment check applies to these consumers too (GHSA-9qff)
- lib/functions.php: data_source_path_within_rra() now also validates
  the realpath of each existing ancestor segment, closing a symlink
  pivot that the purely lexical check missed (GHSA-9qff)
- include/global.php: fail closed instead of falling back to SERVER_NAME
  when base_url is unset/invalid, removing the residual open-redirect
  path (GHSA-3466)
- lib/html_utility.php: cacti_force_https_host()/
  cacti_build_https_redirect_url() now parse a scheme-less base_url
  (matching lib/reports.php's own normalization) and preserve a
  configured non-default port instead of silently dropping it (GHSA-3466)
- tests: move DataSourcePathContainmentTest.php into
  tests/Unit/Security/PathTraversal/, and switch its fixtures from a
  fictional CACTI_PATH_RRA path to a real temp directory so the new
  realpath()-based checks (including a symlink-pivot regression case)
  can actually run

* test: fix CACTI_PATH_RRA constant collision in DataSourcePathContainmentTest

CI showed 2 failures: RrdProxyProtocolTest.php runs earlier in the same
Pest process and already defines CACTI_PATH_RRA to a fictional,
non-existent '/var/lib/cacti/rra', so our own definition guard never
ran and realpath(CACTI_PATH_RRA) returned false for every assertion,
failing the two tests that expect containment to be true.

Now ensure the directory backing CACTI_PATH_RRA actually exists on
disk regardless of who defined the constant first, and gracefully
skip only the fixture-dependent assertions if this process can't
create it (e.g. no permission on a system path).

* test: refresh sink inventory baseline for exec_background rename

5fbe90fb4 renamed \ to \ in lib/poller.php's
exec() calls (GHSA-cv7j-p6fh-j4q7) but never regenerated the tracked
sink inventory, so the 'sink and architectural hotspot guard' CI check
has been failing on this branch since that commit. Regenerated via
tests/security/build_sink_inventory.sh | tr -d '\r' | LC_ALL=C sort;
diff confirms only those two lines changed.

* fix: address CI failures on GHSA batch 2 (develop)

- lib/auth.php: verify the remember-me token before revoking a disabled
  account's cache row, so a forged token no longer triggers a database
  write (fixes AuthSystemRegressionIntegrationTest)
- apply php-cs-fixer coding standard fixes (comment style, phpdoc
  alignment, list-to-short-array syntax) flagged by the locked
  integration check
- refresh the architectural hotspots baseline for the exec_background
  safe_filename rename

* fix: update PHPStan baseline for reordered check_auth_cookie and get_data_source_path

- lib/auth.php: reordering the disabled-account check after the token
  match moved one 'enabled' offset access to a new line, bumping the
  file's expected occurrence count from 3 to 4
- lib/functions.php: the GHSA-9qff-xccr-rrc5 containment log line reads
  \['data_source_path'], a genuinely new array|bool access
  not previously tracked

---------

Co-authored-by: copilot-swe-agent <copilot-swe-agent[bot]@users.noreply.github.com>
2026-09-24 10:06:01 -04:00
Thomas Vincent 08c02d3322 security: resolve open code scanning alerts (#8003)
* security: resolve open code scanning alerts

* test(security): constrain SQL helper sanitizer

* fix(security): address follow-up review
2026-09-06 08:41:47 -07:00
Thomas Vincent 21708ab599 security: stop trusting Host for HTTPS redirects (#7833)
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
2026-08-29 16:01:36 -07:00
Thomas VincentandTheWitness b5be61ab68 fix: keep lib/html_utility.php PHP 8.0-parseable after DsstatsMeasure enum (#7518)
* fix(html_utility): replace DsstatsMeasure enum with PHP 8.0-safe consts

The DsstatsMeasure backed enum added in e96d791e2b uses PHP 8.1 syntax,
which fails to parse under Rocky Linux 9's stock PHP 8.0.30 and breaks
the weekly Rocky Linux compatibility check. Since lib/html_utility.php
is required by include/global.php, the parse error takes down the
whole application on a genuinely stock Rocky 9 install.

Replace the enum with a DSSTATS_MEASURES const array plus a
DSSTATS_MEASURE_DEFAULT const, keeping the same single-source-of-truth
property for the Assert\Choice choices list and the fallback default.
Verified against a real rockylinux:9 container running PHP 8.0.30 (the
exact binary the CI workflow installs), and confirmed the const-based
version produces identical output to the enum version across the
existing regression suite.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* docs: fix the CHANGELOG entry number and placement

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

---------

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Co-authored-by: TheWitness <thewitness@cacti.net>
2026-08-05 09:58:11 -04:00
Thomas VincentandTheWitness e96d791e2b fix(auth): validate measure/order before ORDER BY concatenation in get_allowed_graphs() (#7438)
* fix(auth): validate measure/order before ORDER BY concatenation in get_allowed_graphs()

get_allowed_graphs() built its dsstats ORDER BY clause by concatenating
$sql_order['measure'] and $sql_order['order'] directly into SQL. Both
values trace back to unfiltered request variables (grv('measure'),
grv('graph_order')) at several call sites in html_graph.php and
html_tree.php, none of which register the vars in a filter array.
Reachable pre-auth via graph_view.php when dsstats_enable and the guest
account are on.

Add get_dsstats_order_string() in lib/html_utility.php, next to the
existing sort_column/sort_direction validator get_order_string(), and
have get_allowed_graphs() call it instead of trusting the raw array.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* refactor(auth): validate dsstats measure/order via CactiValidator + backed enum

get_dsstats_order_string() used a hand-rolled in_array() whitelist instead
of this codebase's established CactiValidator/Symfony Assert pattern
(~334 existing call sites). Adds a DsstatsMeasure backed enum as the
single source of truth for legal measure values, feeding an
Assert\Choice constraint checked via CactiValidator::isValid() (not
validateInput(), which writes to $_SESSION and isn't appropriate for
this pure helper).

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix: guard dsstats order/measure against array input and missing require

Addresses Copilot review: require html_utility.php where
get_dsstats_order_string() is called from lib/auth.php, and reject
non-scalar measure/order values before validating/concatenating them.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* test(auth): add integration coverage for dsstats ORDER BY fragment build

Exercises get_dsstats_order_string() together with dsstats_get_best_partition()
and db_qstr(), the other real functions get_allowed_graphs() calls on the
same path, reproducing the JOIN + ORDER BY fragment it concatenates.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* style(auth): order use import before require_once in html_utility.php

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

---------

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Co-authored-by: TheWitness <thewitness@cacti.net>
2026-07-31 16:15:34 -07:00
00e318e2ee security: normalize sort direction at ORDER BY read time (#7310)
* security: normalize sort direction at ORDER BY read time

Force stored sort_direction to ASC/DESC in both update_order_string() read loops so a session poisoned before the write-time fix cannot inject SQL.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: TheWitness <thewitness@cacti.net>
2026-07-13 15:33:01 -04:00
b2bf39b8dc fix(sqli): sanitize sort_column and enforce sort_direction in ORDER BY clauses (#7162)
* fix: correct grammar and possessive errors in English source strings (batch 2) (#1)

* fix: correct grammar and possessive errors in English source strings (batch 2)

Seven errors found via cacti.pot audit:

- automation_networks.php: "senders name" → "sender\'s name" (line 839)
- automation_networks.php: "senders Email" → "sender\'s Email" (line 848)
- automation_templates.php: "devices sysDescr" → "device\'s sysDescr" (line 1060)
- automation_templates.php: "devices sysName" → "device\'s sysName" (line 1067)
- automation_templates.php: "devices sysOid" → "device\'s sysOid" (line 1074)
- data_templates.php: garbled "it either it value...critical data Data Query" →
  "its value...Data Query" (line 903)
- package_repos.php: "Package Repositorites" → "Package Repositories" (line 436)

All changes are to UI description strings inside __() / __esc() calls.
cacti.pot should be regenerated via build_gettext.sh after merge.

* fix: correct grammar and possessive errors in English source strings (batch 2)

Seven errors found via cacti.pot audit:

- automation_networks.php: "senders name" → "sender\'s name" (line 839)
- automation_networks.php: "senders Email" → "sender\'s Email" (line 848)
- automation_templates.php: "devices sysDescr" → "device\'s sysDescr" (line 1060)
- automation_templates.php: "devices sysName" → "device\'s sysName" (line 1067)
- automation_templates.php: "devices sysOid" → "device\'s sysOid" (line 1074)
- data_templates.php: garbled string → "its value...Data Query" (line 903)
- package_repos.php: "Package Repositorites" → "Package Repositories" (line 436)

All changes are to UI description strings inside __() / __esc() calls.
cacti.pot should be regenerated via build_gettext.sh after merge.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

---------

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* ci: add dependabot config with npm and github-actions

* ci: add CodeQL (JS/TS, excludes PHP) with workflow_dispatch

* ci: update CodeQL for javascript-typescript, python

* fix(ci): use specific runner labels, fix codeql concurrency

* Improve IPv6 support in RRDtool proxy and ping utilities (#2)

* Improve IPv6 support in RRDtool proxy and ping utilities

- Fix RRDtool proxy to dynamically detect IPv6 addresses and use
  AF_INET6 sockets instead of hardcoded AF_INET (IPv4-only), enabling
  connections to IPv6 RRDtool proxy servers including backup servers
- Strip brackets from IPv6 addresses before passing to socket_connect
- Properly close failed sockets before creating new ones for failover
- Replace fragile str_contains(':') IPv6 detection in ping with
  filter_var(FILTER_FLAG_IPV6) for more robust address validation

https://claude.ai/code/session_01SbuDigvAkYvPKvdcougsdo

* Fix JS code quality: implicit globals, deprecated APIs, loose equality

- Add var declarations to prevent implicit globals in install.js
  (element, enabled, button, buttonCheck)
- Remove console.log debug output left in production (install.js)
- Replace deprecated jQuery .unbind() with .off() (layout.js)
- Fix "depreciated" typo to "deprecated" in deprecation warnings
- Convert == / != to === / !== for null, boolean, string, typeof,
  and numeric comparisons across install.js and realtime.js

https://claude.ai/code/session_01SbuDigvAkYvPKvdcougsdo

* Replace deprecated jQuery shorthand event methods in layout.js

Replace .click(), .keyup(), .keydown(), .mousedown(), .mouseenter(),
.mouseleave(), .submit(), .resize() with .on() equivalents. Replace
.focus(), .change() trigger calls with .trigger(). These shorthands
were deprecated in jQuery 3.5.

https://claude.ai/code/session_01SbuDigvAkYvPKvdcougsdo

* Replace deprecated jQuery methods in realtime.js

Replace .bind() with .on() and .change() trigger calls with
.trigger('change'). .bind() was deprecated in jQuery 3.0 and
shorthand triggers in jQuery 3.5.

https://claude.ai/code/session_01SbuDigvAkYvPKvdcougsdo

* Replace deprecated jQuery methods in install.js and fix ===/!== errors

Replace .click(), .change(), .focus() with .on()/.trigger() equivalents.
Also fix !=== and ==== operators that were incorrectly introduced by a
prior replace-all of == to === within existing !== and === expressions.

https://claude.ai/code/session_01SbuDigvAkYvPKvdcougsdo

* Restore == null where needed to catch both null and undefined

In JavaScript, == null matches both null and undefined, which is an
intentional idiom. The prior === null conversion broke cases where
values come from jQuery .val(), .data(), $.urlParam(), or object
property access that may return undefined rather than null. Revert
those specific cases while keeping === null where variables are
explicitly initialized to null.

https://claude.ai/code/session_01SbuDigvAkYvPKvdcougsdo

* Replace deprecated jQuery methods in all theme main.js files

Replace .unbind().click() with .off('click').on('click'), convert
.hover() to .on('mouseenter').on('mouseleave'), replace .change(),
.scroll(), .click() shorthands with .on() equivalents, and .blur()
with .trigger('blur') across all 10 theme files.

https://claude.ai/code/session_01SbuDigvAkYvPKvdcougsdo

* Convert string concatenation to template literals

Replace 'str' + var + 'str' patterns with ES6 template literals
in realtime.js and install.js. Improves readability especially for
URL construction and HTML building. Also replace $.parseJSON() with
native JSON.parse() in realtime.js.

https://claude.ai/code/session_01SbuDigvAkYvPKvdcougsdo

* Convert var to const for single-assignment variables

Replace var with const where the variable is assigned once and never
reassigned within its scope, in install.js and realtime.js. Keeps var
for variables that are conditionally reassigned (e.g. size, url).

https://claude.ai/code/session_01SbuDigvAkYvPKvdcougsdo

---------

Co-authored-by: Claude <noreply@anthropic.com>

* fix(sqli): sanitize sort_column and enforce sort_direction in ORDER BY clauses

Closes GHSA-q9xg-p762-9jm3 and GHSA-72vr-jr4v-55vf.

- Add sanitize_sql_column() to lib/functions.php stripping all chars
  outside [a-zA-Z0-9_().] from user-supplied column names
- Apply sanitize_sql_column() at every ORDER BY concatenation in
  api_automation.php and html_reports.php
- Enforce direction to literal ASC/DESC in html_reports.php,
  api_automation.php, and html_utility.php (update_order_string,
  get_order_string)
- Add tests/Unit/SafeSortTest.php with 22 stub-based regression tests

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(docs): move sanitize_sql_column above sanitize_search_string docblock

The sanitize_search_string docblock was orphaned after sanitize_sql_column
was inserted between it and the function body. Reorder so each function
follows its own docblock directly.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(sqli): escape apostrophes in automation_templates and harden sort_direction in display_matching_hosts

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(sqli): restore allowlist guard, sanitize session keys, add sanitize_sql_column default

Restore the preg_match allowlist guard in get_order_string() that was
removed by the PR, re-opening the ORDER BY injection surface. When the
request var is empty after sanitization, return '' rather than building
a malformed ORDER BY clause.

Sanitize sort_column before storing as SESSION array key in
update_order_string() and add read-time guard in the inplace loop that
rebuilds ORDER BY from stored keys.

Add $default parameter to sanitize_sql_column() so callers get a safe
fallback instead of an empty string that produces 'ORDER BY  ASC'.

Fix inconsistent INET_ATON substitution in display_matching_hosts().

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* Improve sanitize_sql_column function

Fix regex to sanitize SQL column names properly.

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: TheWitness <thewitness@cacti.net>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-24 16:54:42 -04:00
Thomas VincentandTheWitness 20298c6cd6 fix(defensive): harden helper library input and output handling (#7197)
* fix(defensive): harden helper library input and output handling

lib/html_utility.php: update_order_string() wrote sort_direction from
the request directly into the session without enforcing ASC/DESC.
Normalise to strtoupper and allowlist-check before every session write;
default to ASC for any unrecognised value.

lib/functions.php:
- sanitize_uri(): add protocol-relative URL guard (leading '//' after
  ltrim). The function stripped most dangerous chars but had no entry
  for '//', which browsers treat as a scheme-relative redirect target.
- is_valid_pathname(): the regex allows literal dots so '../..' passed
  validation. Reject any path containing '..' before the regex check.

lib/database.php: db_qstr() fallback (no PDO connection) was missing
\x1a (Ctrl+Z) from its escape map. PDO quote() handles it; the fallback
now matches.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(defensive): correct hardening edge cases flagged in review

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(defensive): reject control-char redirect and drive-relative traversal

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* ci: ignore phpstan function.alreadyNarrowedType identifier

Clears the level 6 alreadyNarrowedType error on lib/data_query.php:2591 that
develop currently emits, matching the sibling narrowing identifiers already ignored.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

---------

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Co-authored-by: TheWitness <thewitness@cacti.net>
2026-06-24 10:41:39 -04:00
Sean Mancini 96beca48e4 Fix:Regex delimiter in html_utility (#7222)
* Fix for regex delimiter

Fix validation issues in validate_store_request_vars function

- Fixed regex delimiter issue in FILTER_VALIDATE_REGEXP validation
  * Added automatic delimiter wrapping for regex patterns
  * Ensures patterns like '^pattern$' become '/^pattern$/'

- Added special handling for graph_template_id validation
  * Allows -1 value which is used to represent "all templates"
  * Prevents validation errors when -1 is passed as a value

- Maintained all existing functionality while fixing these issues
- Improved code organization and readability

* Update html_utility.php

csfixer update
2026-06-23 20:40:59 -07:00
TheWitnessandCopilot 2810342f65 fix: Simplify redirect handling in Cacti and Fix Multi-Sort (#6955) (#6978)
* fix: Simplify redirect handling in Cacti and Fix Multi-Sort (#6955)

* fix: Simplify redirect handling in Cacti

* fix: Slight improvements from Copilot review

* fix: Fix for compatibility

* fix: Fix small syntax error

* fix: Remove comments

* fix: Make the query case insensitive

* fix: Encode the reference url

* fix: More copilot review comments

* fix: More copilot comments

* fix: Double semicolon

* fix: Missed one commit

* fix: Encode the correct url

* Update lib/html_utility.php

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix: Add additional checks

* fix: Fix order string updates for multiple sort

* fix: Add a sanitization function and do further checks

* fix:Switch to local variables

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Refactor authentication method check in auth.php

* Fix HTML encoding in goBack variable assignment

* Change get_order_string_page parameter to false

* Apply suggestion from @Copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Fix error message capitalization for aggregate graph

* Apply suggestion from @Copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Apply suggestion from @Copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Apply suggestion from @Copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Fix goBack link formatting in permission_denied.php

* Update lib/html_utility.php

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Add type hints to sanitize_uri and validation functions

* Fix comment formatting in validate_redirect_url

* Fix header location formatting in auth.php

* fix: Fixing PSR Issues with remote agent

* fix: Additional psr comments

* fix: More psr comments

* fix: PHPStan Issues

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-05 10:56:17 -04:00
TheWitness 89c5ab2443 Fix: incorrect type in lib/html_utility.php and display_help format (#6887) 2026-03-24 09:46:09 -04:00
Thomas VincentandTheWitness 76b2b693a0 fix: resolve shellcheck and actionlint issues (#6876)
* fix: shellcheck fixes, codespell config, and actionlint config

- Add .github/actionlint.yaml with no-shellcheck to disable
  false positives in run: blocks
- Update .codespell.cfg to skip third-party assets, themes,
  mock data; add intentional words to ignore list
- Fix shellcheck issues in all shell scripts: quoting, egrep
  to grep -E, glob iteration, bare redirects, SIGKILL trap

Does not touch workflow YAML files (handled in #6874).

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* hardening: move to argument array pattern for shell execution (#6854)

* docs: update exec_background docblock for string|array param types

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* docs: add PHPDoc to __rrd_execute for PHPStan

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix: resolve php-cs-fixer formatting issues

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* revert: remove oauth2.php fix (moved to standalone PR #6886)

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* chore: remove files that belong in other PRs

- Revert lib/poller.php and lib/rrd.php arg-array changes (belong in PR #6855)
- Remove ArgArrayHardeningTest.php (belongs in PR #6855)
- Revert vendor/composer updates (should be a separate PR)

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* chore: remove composer.lock from tracking

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

---------

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Co-authored-by: TheWitness <thewitness@cacti.net>
2026-03-24 08:10:13 -04:00
TheWitness 3ff22323d4 Allow form_selectable_cell to more easily port (#6583) 2026-01-30 08:04:00 -05:00
TheWitness 27919c50d7 Updating Copyrights to 2026 (#6578) 2026-01-28 16:11:10 -05:00
TheWitnessandCopilot b993471579 Fix #6539 - Allow Standard Cacti Log Files to be Rotated on Demand,PHPdoc, and Typing (#6540)
* Fix #6539 - Allow Standard Cacti Log Files to be Rotated on Demand from the Cacti UI

* QA: php-cs-fixer updates and documentation for lib/database.php

* QA: Update .gitignore for composer files

* QA: Update .gitignore for composer files

* QA: Back off .gitignore change its duplicated

* QA: Fix typing of db_has_permissions

* QA: Fixing typing issue in db_format_index_create

* Update lib/clog_webapi.php

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* QA: Fix additional code issues

* QA: Applying more defaults to add device

* QA: Fix at the database layer

* QA: Fixes based upon automated testing

* QA: Fix at the database layer

* QA: After new SQL checking

* QA: Skip MacTrack oui database download warnings

* QA: Fixing type issue

* QA: Recommendation from Copilot

* QA: Recommendation from Copilot

* QA: Recommendation from Copilot

* QA: Recommendation from Copilot

* QA: Some minor changes to avoid errors in testing

* QA: Unused variable

* QA: Recommendation from Copilot

* QA: Recommendation from Copilot

* QA: Recommendation from Copilot

* QA: Minor introduced code defect

* QA: Adding some unifying space around concatination

* QA: Consistent comments and new function alias'

* QA: Multi-line comment corrections

* QA: Fix SQL Style

* QA: Missed one function alias

* QA: PHPStan Level 2 and PHPDoc fixes

* QA: PHPStan Level 2 and PHPDoc Fixes

* QA: PHPStan Level 6 Fixes

* QA: Fix lib/xml.php to PHPStan Level 6

* QA: Wrong grep -v

* PHPStan Level 6 for lib/vdef.php

* PHPStan Level 8 for lib/time.php

* QA: Raise PHPStan to Level 6 for lib/database.php

* QA: Remove @deprecated tag from grv()

* QA: Switch to htmle() alias over html_escape()

* QA: More addressing PHPStan issues at Level 6

* QA: Change recommended by Copilot for Readability

* QA: More PHPStan fixes

* QA: More PHPStan fixes

* QA: More PHPStan fixes for lib/utility.php

* QA: More PHPStan fixes at Level 6

* QA: Raise PHPStan to Level 6 More Functions

* QA: Raise PHPStan to Level 6 More Functions

* QA: Raise PHPStan to Level 6 More Functions

* QA: Raise PHPStan to Level 6 More Functions

* QA: Raise PHPStan to Level 6 More Functions

* QA: More PHPStan fixes at Level 6

* QA: Raise PHPStan to Level 6 More Functions

* QA: Raise PHPStan to Level 6 More Functions

* QA: More PHPStan fixes at Level 6

* QA: More PHPStan fixes at Level 6

* QA: Raise PHPStan to Level 6 More Functions

* QA: Raise PHPStan to Level 6 More Functions

* QA: More PHPStan fixes at Level 6

* QA: Raise PHPStan to Level 6 More Functions

* QA: Raise PHPStan to Level 6 More Functions

* QA: More PHPStan fixes at Level 6

* QA: Raise PHPStan to Level 6 More Functions

* QA: Raise PHPStan to Level 6 More Functions

* QA: More PHPStan fixes at Level 6

* QA: More PHPStan fixes at Level 6

* QA: More PHPStan fixes at Level 6

* QA: Raise PHPStan to Level 6 More Functions

* QA: More PHPStan fixes at Level 6

* QA: Some phpseclib3 fixups to update to latest

* QA: More fixups for graphing for magic strings

* QA: More PHPStan fixes at Level 6

* QA: Fixing order string type on get_allowed_graphs()

* QA: Fixing improper use of print

* QA: Optimization of color_templates

* QA: Copilot recommendation

* QA: Copilot recommendation

* QA: Copilot recommendation

* QA: Copilot recommendation

* QA: Copilot recommendation

* QA: Copilot recommendation

* QA: Copilot recommendation

* QA: Copilot recommendation

* QA: Raise PHPStan to Level 6 More Functions

* QA: Issues insalling Cacti

* QA: Issues insalling Cacti

* QA: Issues insalling Cacti

* QA: Issues insalling Cacti

* QA: Issues insalling Cacti

* QA: Issues testing Cacti

* QA: Copilot recommendation

* QA: More PHPStan fixes at Level 6

* QA: More PHPStan fixes at Level 6

* QA: More PHPStan fixes at Level 6

* QA: More PHPStan fixes at Level 6

* QA: More PHPStan fixes at Level 6

* QA: Installer failing

* Undo ownership changes to remove tar errors

* QA: Updates after php-cs-fixer

* QA: Adding code checks to syntax checking

* QA Change syntax flow language

* QA: Reduce the number of cures

* QA: Use sequentional option

* Change runner to self-hosted for check job

* Fix typo in OS version in workflow file

* Add Git installation step in workflow

Added step to install Git if not already installed.

* Add '-y' flag to apt-get install and update commands

Updated apt-get commands to include '-y' for automatic confirmation.

* Change workflow OS version to 'ubuntu-latest'

Updated the workflow to use 'ubuntu-latest' instead of 'ubuntu:latest' and modified the 'runs-on' configuration.

* Remove sequential option from phpcsfixer script

* Remove PHPCS fixer step from workflow

Removed PHP coding standards check from workflow.

* Move code checks to before plugins

Moving these core checks to before the plugins are installed as we really want to check only the base Cacti here.

* Add Composer validation and caching to start of workflow

* QA: Addressing PHPStan additional

* QA: Restore composer lock file

* QA: Addressing PHPStan additional

* QA: Addressing PHPStan additional

* QA: Complete LDAP Project

* QA: php-cs-fixer doing it's thing

* QA: Syntax is already happening in PHPStan

* QA: The md5 function no longer exists

* QA: Update after ldap changes

* QA: Undo that last password hack

* QA: Attempting to switch to MariaDB 11.8

* QA: Attempting to switch to MariaDB 11.8

* QA: Resolving some issues with PHP8.4

* QA: Resolving some issues with PHP8.4

* QA: Add PHP8.5 to the matrix

* QA: Removing PHP8.5 due to dependency issues

* QA: Add the DB version to the testing output

* QA: Switch back to MySQL for the moment

* QA: More fidelity in reporting

* QA: The pipe must be mixed

* QA: Moving audit_schema.php changes from 1.2.x

* QA: Moving audit_schema.php changes from 1.2.x

* QA: Restore mysql monitoring

* QA: php-cs-fixer issues

* QA: Attempt to roll back to MariaDB 10.6

* QA: Attempt to fix check_all_pages.sh

* QA: Make installer functional again

* QA: Fix installer php-cs-fixer issues

* QA: Type to a string

* QA: Get the database version correctly

* QA: Fix issue with reports in check_all_pages.sh

* QA: Check the server version in the right place

* Feature: Support SHA256 as a new hash for passwords

* QA: Function definition and return typing audit

* QA: Refinement of form types

* QA: Refinement of form types

* QA: Consistency of comments

* QA: Issues with php-cs-fixer and more comments

* QA: More typing issues

* QA: php-cs-fixer on merge conflict resolution

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-01-25 10:13:56 -05:00
Browniebraun 1627c7a150 Font Awesome Icons to Tabler Icons migration 2025-12-16 20:27:05 +01:00
Jimmy Conner ae80474037 More PHPDoc and function parameter type declaring 2025-11-19 01:11:30 -06:00
TheWitness b9334a15d9 QA: Updates for files for php-cs-fixer and some php-doc changes 2025-11-18 21:01:15 -05:00
TheWitness be662c8124 Fixing: #6292 - Fatal Validation Errors due to Plugin Defects
Fatal validation errors occur if a request variable default value is null
2025-07-28 15:29:38 -04:00
TheWitness 6df94e90cb Fix: #6283 - Divide by Zero if the $rows variable is not set 2025-07-10 20:48:01 -04:00
TheWitness 18a37e0d88 QA: Allow null input strings 2025-04-07 20:29:42 -04:00
TheWitness cdf0d5f27e Fixing more PHPStan Issues 2025-03-23 15:16:09 -04:00
TheWitness 685d4b9357 Start addressing PHPStan Issues 2025-03-23 14:09:11 -04:00
TheWitness d2624514cc Restore parts of lib/rrd.php move/rename a function 2025-03-23 10:23:11 -04:00
TheWitness 91899e3d23 Fix: #6191 - Natural Sorting of Hostname Column
Adding Natural sorting options for Hostname
2025-03-22 08:59:53 -04:00
TheWitness 70fcea0872 Remove debugging 2025-03-09 20:07:15 -04:00
TheWitness 11b0f4a016 Clear Check All Pages Warnings 2025-03-09 18:24:07 -04:00
TheWitness 2c779273f9 Copyright Updates and PHP-CS-Fixer updates 2025-03-09 14:34:19 -04:00
Jimmy ConnerandTheWitness 65ab16f5cf Start converting to newer PHP Syntax and Functions (#6103)
* Add Rector

* Add Rector

* Fix "Cashed" misspelling

Also harmonize the phrase with the one below it

* Fix implode error in db_table_create

Only relevant when multiple primary keys

* Fix auth issue, parentheses in the wrong location

Was causing too many arguments to be sent to cacti_sizeof which only take 1, instead of get_allowed_devices.

* Fix issue with session_var not properly using class variable

* Fix pass by reference error in get_allowed_devices

get_allowed_devices has a pass by reference on the "total_rows" field.  It is used in several places to pass the total_rows back to a counter.  Here though, we are passing a number directly to the function, which errors out with "Uncaught Error: get_allowed_devices(): Argument #4 ($total_rows) cannot be passed by reference".  So we will just place a dummy variable in front to catch the pass.

This wasn't caught before because the previous parentheses issue.

* Fix undefined variable "field_array" in html_filter

* Fix undefined function 'get_nfilter_filter_request_var'

* Fix undefined variable 'resizable'

I corrected the function parameter, as that was technically the incorrect spelling

* Fix invalid variable $user_id

* Fix undefined vars in spikekill class

* Fix copy and paste error

Oops

* Forgot to use the dummy variables

* Add missing $

Oops

* Start converting to newer PHP Syntax and Functions

* Test fixing the workflow by install composer

* Lets not valid the composer file right now
Seems we have a few things to fix it in

* Validate composer

* Lite formating changes

* lite formatting

* lite formatting

* lite format changes

* lite format changes

* lite format changes

* lite format changes

* lite format changes

* lite format changes

* lite format changes

* lite format changes

---------

Co-authored-by: TheWitness <thewitness@cacti.net>
2025-02-23 15:14:54 -05:00
TheWitness fb05ea4a45 QA: Restore inline tooltip help links 2025-02-19 16:59:51 -05:00
Browniebraun d88d3acd30 reverting FontAwesome till better solution has been identified. 2025-01-15 23:04:14 +01:00
Browniebraun 5be7d7f18b Migrating icons from FontAwesome to Tabler 2025-01-05 20:58:36 +01:00
TheWitness fa8dd0df0c QA: Make adjustments when header topology changes
* If a developer is making table layout changes, clear the users setting to prevent visibility issues.
2025-01-03 07:29:46 -05:00
TheWitness f5ea29493f QA: When you push the clear button, clear the hidden columns
* This is a bit of a workaround for the moment.
2024-12-27 20:59:35 -05:00
TheWitness ef3d27f8cf QA: Migrate Remaining Automation to Filter Class + Fixes
* All Automation Sections are not using Filter Class
* Fixed some bugs relative to display
* Enhanced the form_get_table_id() function to handle tabs + action
* Finished migrating Tree rules to show matching items as a sub-tab
* Some tab relabeling
2024-12-23 17:53:24 -05:00
TheWitness a733eb2af3 QA: One more visibility change 2024-12-15 20:38:57 -05:00
TheWitness ddaf5a190e QA: Set the correct column attribute 2024-12-15 20:34:28 -05:00
TheWitness 0aa69ba165 QA: Column visibility changes 2024-12-15 20:02:07 -05:00
TheWitness db8c290d89 QA: Changes in Support of #1401
* This is some pre-work to supporting column visibility enhancements already in place in MidWinter.
* This change should allow generalized support of column visibility storing the settings in the database.
2024-12-15 19:30:33 -05:00
Jimmy Conner ad07471bb1 Lots of PHPDoc formatting and cleanup
Lots more to go
2024-12-09 02:50:06 -06:00
Linegod c3b176780f typos 2024-11-24 23:22:15 -06:00
TheWitness 57b720885a QA: Fixing multi-sort display issues 2024-11-15 17:47:45 -05:00
TheWitness e2f443c5cf QA: Documentation and alignment 2024-11-04 14:29:04 -05:00
TheWitness a54d46c85c Fixing #470 from Thold
Making Cacti compatible with https://github.com/Cacti/plugin_thold/issues/470
2024-04-06 15:24:28 -04:00
TheWitness d667f41d73 Fixing #5696 - Chinese encoding does not decode correctly
When inputting Chinese to search for graphics, garbled characters appear.
2024-04-05 14:44:31 -04:00
TheWitness 1aa72d24c9 QA: Update Copyright to 2024 2024-02-03 14:18:57 -05:00