github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/utils/atlas/endpoints.go (about) 1 // Copyright 2023 Gravitational, 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 atlas 16 17 import ( 18 "net/url" 19 "strings" 20 21 "github.com/gravitational/trace" 22 ) 23 24 // IsAtlasEndpoint returns true if the input URI is an MongoDB Atlas endpoint. 25 func IsAtlasEndpoint(endpoint string) bool { 26 return strings.Contains(endpoint, EndpointSuffix) 27 } 28 29 // ParseAtlasEndpoint extracts the database name from the Atlas endpoint. 30 func ParseAtlasEndpoint(endpoint string) (string, error) { 31 // Add a temporary schema to make a valid URL for url.Parse if schema is 32 // not found. 33 if !strings.Contains(endpoint, "://") { 34 endpoint = "schema://" + endpoint 35 } 36 37 parsed, err := url.Parse(endpoint) 38 if err != nil { 39 return "", trace.Wrap(err) 40 } 41 42 parts := strings.Split(parsed.Hostname(), ".") 43 if !IsAtlasEndpoint(endpoint) || len(parts) < 3 { 44 return "", trace.BadParameter("failed to parse %q as Mongo Atlas endpoint", endpoint) 45 } 46 47 return parts[0], nil 48 } 49 50 const ( 51 // EndpointSuffix is the databases endpoint suffix. 52 EndpointSuffix = ".mongodb.net" 53 )