trustgraph icon indicating copy to clipboard operation
trustgraph copied to clipboard

Unsafe string split when parsing Prometheus metric labels in ontology monitoring

Open cybermaggedon opened this issue 6 months ago • 2 comments

Description

In trustgraph-flow/trustgraph/query/ontology/monitoring.py (line 478):

cache_type = metric_name.split('cache_type=')[1].split(',')[0].split('}')[0]

Problem

If a metric name in the counters dict doesn't contain the substring `cache_type=`, the `split()` returns a single-element list and `[1]` raises `IndexError`.

The guard on line 477 (`if 'cache_type=' in metric_name`) currently prevents this, but the parsing itself is fragile — any refactoring that moves or removes the guard exposes the crash. The chained-split approach is also hard to read.

Suggested fix

Please PR against the latest release/vX.Y branch.

Use a small helper or regex to extract label values safely:

def _extract_label(metric_name, label):
    """Extract a Prometheus-style label value from a metric name, or None."""
    prefix = f'{label}="'
    if prefix not in metric_name:
        return None
    return metric_name.split(prefix)[1].split('"')[0]

Or keep inline but add a guard:

parts = metric_name.split('cache_type=')
if len(parts) < 2:
    continue
cache_type = parts[1].split(',')[0].split('}')[0]

What you'll learn

How TrustGraph's ontology query engine collects and reports internal performance metrics, and safe patterns for parsing structured strings.

cybermaggedon avatar May 07 '26 09:05 cybermaggedon

I can take this.

I’ll replace the chained split with a safe label extractor and add coverage for metrics with and without cache_type.

jmolz avatar May 22 '26 14:05 jmolz

Fixed by #948

cybermaggedon avatar May 26 '26 12:05 cybermaggedon