github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/utils/cluster.go (about) 1 /* 2 Copyright 2021 Gravitational, Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package utils 18 19 import ( 20 "encoding/hex" 21 "fmt" 22 "strings" 23 24 "github.com/gravitational/trace" 25 26 "github.com/gravitational/teleport/api/constants" 27 ) 28 29 // EncodeClusterName encodes cluster name in the SNI hostname 30 func EncodeClusterName(clusterName string) string { 31 // hex is used to hide "." that will prevent wildcard *. entry to match 32 return fmt.Sprintf("%v.%v", hex.EncodeToString([]byte(clusterName)), constants.APIDomain) 33 } 34 35 // DecodeClusterName decodes cluster name, returns NotFound 36 // if no cluster name is encoded (empty subdomain), 37 // so servers can detect cases when no server name passed 38 // returns BadParameter if encoding does not match 39 func DecodeClusterName(serverName string) (string, error) { 40 if serverName == constants.APIDomain { 41 return "", trace.NotFound("no cluster name is encoded") 42 } 43 const suffix = "." + constants.APIDomain 44 if !strings.HasSuffix(serverName, suffix) { 45 return "", trace.NotFound("no cluster name is encoded") 46 } 47 clusterName := strings.TrimSuffix(serverName, suffix) 48 49 decoded, err := hex.DecodeString(clusterName) 50 if err != nil { 51 return "", trace.BadParameter("failed to decode cluster name: %v", err) 52 } 53 return string(decoded), nil 54 }