logging: StructuredLogHandler writes invalid JSON when trace or span_id contains " or \

Ouverte Adaptée aux débutants
#19,099 0 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 2 jours

Personne n'a encore pris cette issue.

Évaluation

Difficulté
2/5
Temps estimé
1-3 heures
Accessibilité débutants
68/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Active
Stack technique
python
Domaine
backend

Piste de recherche

L’issue indique packages/google-cloud-logging/google/cloud/logging_v2/handlers/structured_log.py et handlers.py ; commence par lire comment StructuredLogHandler formate et filtre les valeurs de trace et de span. Reproduis l’échec avec l’exemple fourni de filter() et format(), puis vérifie les tests pertinents du handler. Le travail est terminé lorsque la sortie formatée peut être analysée comme JSON et conserve les chaînes de trace et de span contenant des guillemets ou des barres obliques inverses.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

Determine this is the right repository
  • I determined this is the correct repository in which to report this bug.
Summary of the issue

StructuredLogHandler writes invalid JSON when a trace or span id contains " or \. Its format string puts %(_trace_str)s and %(_span_id_str)s inside JSON quotes (structured_log.py#L33), and the filter copies the raw values (handlers.py#L111) without JSON escaping. The handler's own X-Cloud-Trace-Context parser accepts only [\w-]+ (_helpers.py#L195), so the default path is safe. Values set explicitly (extra={"trace": ...}, a logging filter, a framework integration) go into the line as-is, and Cloud Logging receives one broken text line instead of a structured entry.

Expected: valid JSON with both strings preserved. Actual: json.loads fails (Expecting ',' delimiter for the quote, Invalid \escape for the backslash).

API client name and version

google-cloud-logging 3.17.0 (also 3.12.1)

Reproduction steps: code

No client, credentials or network: only filter() and format() run.

"""Explicit trace/span strings must round-trip through structured JSON logging."""
import json
import logging
import sys
import traceback
from importlib.metadata import version

control = True
try:
    print("google-cloud-logging", version("google-cloud-logging"), flush=True)
    from google.cloud.logging_v2.handlers import StructuredLogHandler

    handler = StructuredLogHandler()

    def encode(trace_value, span_value):
        record = logging.LogRecord("repro", logging.INFO, "repro.py", 1, "hello", (), None)
        record.trace = trace_value
        record.span_id = span_value
        assert handler.filter(record)
        return handler.format(record)  # No emit(), client, credentials, or network.

    trace_key = "logging.googleapis.com/trace"
    span_key = "logging.googleapis.com/spanId"
    decoded = json.loads(encode("projects/p/traces/abc", "123"))
    assert decoded[trace_key] == "projects/p/traces/abc" and decoded[span_key] == "123"
    print("CONTROL PASSED: plain trace/span values round-trip through valid JSON")
    control = False
    failures = []
    for label, trace_value, span_value in (
        ("trace quote", 'projects/p/traces/a"b', "123"),
        ("span backslash", "projects/p/traces/abc", r"bad\span"),
    ):
        try:
            decoded = json.loads(encode(trace_value, span_value))
        except json.JSONDecodeError as error:
            failures.append(f"{label}: {error.msg}")
        else:
            if decoded[trace_key] != trace_value or decoded[span_key] != span_value:
                failures.append(f"{label}: value corrupted")
    handler.close()
    prefix = "BUG REPRODUCED: " if failures else "NOT REPRODUCED: "
    print(prefix + f"escaping failures={failures}; expected valid JSON preserving both strings")
except Exception:
    traceback.print_exc()
    if control:
        print("CONTROL FAILED")
    sys.exit(2 if control else 1)

Output:

google-cloud-logging 3.17.0
CONTROL PASSED: plain trace/span values round-trip through valid JSON
BUG REPRODUCED: escaping failures=["trace quote: Expecting ',' delimiter", 'span backslash: Invalid \\escape']; expected valid JSON preserving both strings
OS & version + platform

Linux

Python environment

Python 3.11

Additional context

Escaping these two fields like the message (json.dumps(value)[1:-1]) would fix it, or validating them against the same pattern the header parser uses.

Langage dominant
Python
Étoiles
5.4k
Forks
1.8k
Merge moyen
2 j 20 h
PR mergées (30 j)
140

Préparer son environnement

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de googleapis/google-cloud-python

Toutes les issues de googleapis/google-cloud-python

Issues similaires

Plus d'issues Python

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.