package intake import ( "bytes" "compress/gzip" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "mime" "net/http" collogspb "go.opentelemetry.io/proto/otlp/collector/logs/v1" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) const ( protobufFormat = "application/x-protobuf" jsonFormat = "application/json" // A transcript entry can hold a large tool result, so a request may be // large. This is the most that midden reads, after gzip. maxBody = 256 << 20 ) var errUnsupported = errors.New("unsupported content type") // decode reads an OTLP logs request in protobuf or in JSON, compressed // with gzip or not, and returns it with the format it came in. func decode(r *http.Request) (*collogspb.ExportLogsServiceRequest, string, error) { format, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) if format != protobufFormat && format != jsonFormat { return nil, "", fmt.Errorf("%w %q: send %s or %s", errUnsupported, format, protobufFormat, jsonFormat) } body := io.Reader(r.Body) if r.Header.Get("Content-Encoding") == "gzip" { gz, err := gzip.NewReader(r.Body) if err != nil { return nil, "", fmt.Errorf("reading gzip: %w", err) } defer gz.Close() body = gz } data, err := io.ReadAll(io.LimitReader(body, maxBody+1)) if err != nil { return nil, "", fmt.Errorf("reading the body: %w", err) } if len(data) > maxBody { return nil, "", fmt.Errorf("the body is larger than %d bytes", maxBody) } req := &collogspb.ExportLogsServiceRequest{} if format == protobufFormat { err = proto.Unmarshal(data, req) } else { err = unmarshalJSON(data, req) } if err != nil { return nil, "", fmt.Errorf("decoding OTLP %s: %w", format, err) } return req, format, nil } // unmarshalJSON reads OTLP JSON. OTLP JSON writes trace and span IDs in // hex, and protobuf's JSON mapping reads bytes as base64, so the IDs are // converted before protojson reads them. func unmarshalJSON(data []byte, req *collogspb.ExportLogsServiceRequest) error { decoder := json.NewDecoder(bytes.NewReader(data)) decoder.UseNumber() var tree any if err := decoder.Decode(&tree); err != nil { return err } if err := hexIDsToBase64(tree); err != nil { return err } converted, err := json.Marshal(tree) if err != nil { return err } return protojson.UnmarshalOptions{DiscardUnknown: true}.Unmarshal(converted, req) } func hexIDsToBase64(node any) error { switch n := node.(type) { case map[string]any: for key, value := range n { if s, ok := value.(string); ok && (key == "traceId" || key == "spanId") { raw, err := hex.DecodeString(s) if err != nil { return fmt.Errorf("%s %q is not hex", key, s) } n[key] = base64.StdEncoding.EncodeToString(raw) continue } if err := hexIDsToBase64(value); err != nil { return err } } case []any: for _, value := range n { if err := hexIDsToBase64(value); err != nil { return err } } } return nil }