package pi import ( "encoding/json" "strings" ) // Redacted stands where a launch's key was. const Redacted = "[redacted]" // Redactor takes a launch's key out of what the harness says (a step can // read the key, connectors spec ยง2.1, so it can echo it): every string // the runner logs or reports from Pi passes through it. Stream handles // text that arrives in pieces, holding back an end that could be the // start of the key. type Redactor struct { forms []string pending string } // NewRedactor redacts key, as itself and as it appears inside JSON. func NewRedactor(key string) *Redactor { r := &Redactor{} if key == "" { return r } r.forms = []string{key} if raw, err := json.Marshal(key); err == nil { if quoted := string(raw[1 : len(raw)-1]); quoted != key { r.forms = append(r.forms, quoted) } } return r } // Redact replaces every whole occurrence. func (r *Redactor) Redact(s string) string { for _, f := range r.forms { s = strings.ReplaceAll(s, f, Redacted) } return s } // RedactJSON redacts a JSON document's text (the key inside a string // value keeps it valid JSON). func (r *Redactor) RedactJSON(raw json.RawMessage) json.RawMessage { return json.RawMessage(r.Redact(string(raw))) } // Stream takes the next piece of a text and returns what can be shown // now: everything but an end that could still become the key. func (r *Redactor) Stream(piece string) string { if len(r.forms) == 0 { return piece } s := r.Redact(r.pending + piece) hold := 0 for _, f := range r.forms { for k := min(len(f)-1, len(s)); k > hold; k-- { if strings.HasSuffix(s, f[:k]) { hold = k break } } } r.pending = s[len(s)-hold:] return s[:len(s)-hold] } // Flush returns what Stream held back, once the text has ended. func (r *Redactor) Flush() string { s := r.pending r.pending = "" return s }