diff --git a/prometheus_client/openmetrics/parser.py b/prometheus_client/openmetrics/parser.py index ebd6da10..17753648 100644 --- a/prometheus_client/openmetrics/parser.py +++ b/prometheus_client/openmetrics/parser.py @@ -91,6 +91,11 @@ def _parse_timestamp(timestamp): try: # aaaa.bbbb. Nanosecond resolution supported. parts = timestamp.split('.', 1) + if len(parts) != 2 or not parts[1].isdigit(): + # Only fixed-point digits can follow the dot here. A mantissa with + # an exponent (1.5e3) or trailing garbage is not a nanosecond + # fraction: fall through to the float path, which validates it. + raise ValueError(timestamp) sec = int(parts[0]) nsec = int(parts[1][:9].ljust(9, "0")) if sec == 0 and parts[0].startswith('-'): diff --git a/tests/openmetrics/test_parser.py b/tests/openmetrics/test_parser.py index 78b7af83..c5fcd3a4 100644 --- a/tests/openmetrics/test_parser.py +++ b/tests/openmetrics/test_parser.py @@ -664,6 +664,31 @@ def test_timestamps(self): b.add_metric([], 2, timestamp=Timestamp(1234567890, 0)) self.assertEqual([a, b], list(families)) + def test_exponent_timestamps(self): + families = text_string_to_metric_families("""# TYPE a counter +# HELP a help +a_total{foo="1"} 1 1.704067200123e9 +a_total{foo="2"} 1 1.123456789e3 +a_total{foo="3"} 1 -1.704067200123e9 +a_total{foo="4"} 1 0 # {a="b"} 0.5 1.2345e3 +# EOF +""") + a = CounterMetricFamily("a", "help", labels=["foo"]) + a.add_metric(["1"], 1, timestamp=1704067200.123) + a.add_metric(["2"], 1, timestamp=1123.456789) + a.add_metric(["3"], 1, timestamp=-1704067200.123) + a.add_metric(["4"], 1, timestamp=Timestamp(0, 0)) + a.samples[-1] = a.samples[-1]._replace(exemplar=Exemplar({"a": "b"}, 0.5, 1234.5)) + self.assertEqual([a], list(families)) + + def test_invalid_timestamp_after_nanoseconds(self): + with self.assertRaises(ValueError): + list(text_string_to_metric_families("""# TYPE a counter +# HELP a help +a_total 1 1.123456789garbage +# EOF +""")) + def test_hash_in_label_value(self): families = text_string_to_metric_families("""# TYPE a counter # HELP a help