Files
vault/internal/observability/event/node_formatter_audit_jsonx.go
Peter Wilson 71a6e1e3fa VAULT-17081: audit formatter node (JSONx) (#21762)
* JSONX audit format events
2023-07-12 11:53:47 +01:00

75 lines
2.1 KiB
Go

// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package event
import (
"context"
"fmt"
"github.com/hashicorp/eventlogger"
"github.com/jefferai/jsonx"
)
var _ eventlogger.Node = (*AuditFormatterJSONx)(nil)
// AuditFormatterJSONx represents a formatter node which will Process JSON to JSONx format.
type AuditFormatterJSONx struct {
format auditFormat
}
// NewAuditFormatterJSONx creates a formatter node which can be used to format
// incoming events to JSONx.
// This formatter node requires that a AuditFormatterJSON node exists earlier
// in the pipeline and will attempt to access the JSON encoded data stored by that
// formatter node.
func NewAuditFormatterJSONx() *AuditFormatterJSONx {
return &AuditFormatterJSONx{format: AuditFormatJSONx}
}
// Reopen is a no-op for this formatter node.
func (_ *AuditFormatterJSONx) Reopen() error {
return nil
}
// Type describes the type of this node.
func (_ *AuditFormatterJSONx) Type() eventlogger.NodeType {
return eventlogger.NodeTypeFormatter
}
// Process will attempt to retrieve pre-formatted JSON stored within the event
// and re-encode the data to JSONx.
func (f *AuditFormatterJSONx) Process(ctx context.Context, e *eventlogger.Event) (*eventlogger.Event, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
const op = "event.(AuditFormatterJSONx).Process"
if e == nil {
return nil, fmt.Errorf("%s: event is nil: %w", op, ErrInvalidParameter)
}
// We expect that JSON has already been parsed for this event.
jsonBytes, ok := e.Format(AuditFormatJSON.String())
if !ok {
return nil, fmt.Errorf("%s: pre-formatted JSON required but not found: %w", op, ErrInvalidParameter)
}
if jsonBytes == nil {
return nil, fmt.Errorf("%s: pre-formatted JSON required but was nil: %w", op, ErrInvalidParameter)
}
xmlBytes, err := jsonx.EncodeJSONBytes(jsonBytes)
if err != nil {
return nil, fmt.Errorf("%s: unable to encode JSONx using JSON data: %w", op, err)
}
if xmlBytes == nil {
return nil, fmt.Errorf("%s: encoded JSONx was nil: %w", op, err)
}
e.FormattedAs(f.format.String(), xmlBytes)
return e, nil
}