github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/redact.go (about)

     1  // Copyright 2023 LiveKit, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package utils
    16  
    17  import (
    18  	"fmt"
    19  	"regexp"
    20  	"strings"
    21  )
    22  
    23  // rtmp urls must be of format rtmp(s)://{host}(/{path})/{app}/{stream_key}( live=1)
    24  var rtmpRegexp = regexp.MustCompile("^(rtmps?:\\/\\/)(.*\\/)(.*\\/)(\\S*)( live=1)?$")
    25  
    26  func RedactStreamKey(url string) (string, bool) {
    27  	match := rtmpRegexp.FindStringSubmatch(url)
    28  	if len(match) != 6 {
    29  		return url, false
    30  	}
    31  
    32  	match[4] = RedactIdentifier(match[4])
    33  	return strings.Join(match[1:], ""), true
    34  }
    35  
    36  func RedactIdentifier(identifier string) string {
    37  	var prefix, suffix string
    38  	for i := 3; i > 0; i-- {
    39  		if len(identifier) >= i*3 {
    40  			prefix = identifier[:i]
    41  			suffix = identifier[len(identifier)-i:]
    42  			break
    43  		}
    44  	}
    45  
    46  	return fmt.Sprintf("{%s...%s}", prefix, suffix)
    47  }
    48  
    49  func Redact(s, name string) string {
    50  	if s != "" {
    51  		return name
    52  	}
    53  	return ""
    54  }