/* Copyright 2021 Gravitational, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package utils import ( "encoding/hex" "fmt" "strings" "github.com/gravitational/trace" "github.com/gravitational/teleport/api/constants" ) // EncodeClusterName encodes cluster name in the SNI hostname func EncodeClusterName(clusterName string) string { // hex is used to hide "." that will prevent wildcard *. entry to match return fmt.Sprintf("%v.%v", hex.EncodeToString([]byte(clusterName)), constants.APIDomain) } // DecodeClusterName decodes cluster name, returns NotFound // if no cluster name is encoded (empty subdomain), // so servers can detect cases when no server name passed // returns BadParameter if encoding does not match func DecodeClusterName(serverName string) (string, error) { if serverName == constants.APIDomain { return "", trace.NotFound("no cluster name is encoded") } const suffix = "." + constants.APIDomain if !strings.HasSuffix(serverName, suffix) { return "", trace.NotFound("no cluster name is encoded") } clusterName := strings.TrimSuffix(serverName, suffix) decoded, err := hex.DecodeString(clusterName) if err != nil { return "", trace.BadParameter("failed to decode cluster name: %v", err) } return string(decoded), nil }