github.com/demonoid81/containerd@v1.3.4/namespaces/validate.go (about) 1 /* 2 Copyright The containerd Authors. 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 namespaces provides tools for working with namespaces across 18 // containerd. 19 // 20 // Namespaces collect resources such as containers and images, into a unique 21 // identifier space. This means that two applications can use the same 22 // identifiers and not conflict while using containerd. 23 // 24 // This package can be used to ensure that client and server functions 25 // correctly store the namespace on the context. 26 package namespaces 27 28 import ( 29 "regexp" 30 31 "github.com/containerd/containerd/errdefs" 32 "github.com/pkg/errors" 33 ) 34 35 const ( 36 maxLength = 76 37 alpha = `[A-Za-z]` 38 alphanum = `[A-Za-z0-9]+` 39 label = alpha + alphanum + `(:?[-]+` + alpha + alphanum + `)*` 40 ) 41 42 var ( 43 // namespaceRe validates that a namespace matches valid identifiers. 44 // 45 // Rules for domains, defined in RFC 1035, section 2.3.1, are used for 46 // namespaces. 47 namespaceRe = regexp.MustCompile(reAnchor(label + reGroup("[.]"+reGroup(label)) + "*")) 48 ) 49 50 // Validate returns nil if the string s is a valid namespace. 51 // 52 // To allow such namespace identifiers to be used across various contexts 53 // safely, the character set has been restricted to that defined for domains in 54 // RFC 1035, section 2.3.1. This will make namespace identifiers safe for use 55 // across networks, filesystems and other media. 56 // 57 // The identifier specification departs from RFC 1035 in that it allows 58 // "labels" to start with number and only enforces a total length restriction 59 // of 76 characters. 60 // 61 // While the character set may be expanded in the future, namespace identifiers 62 // are guaranteed to be safely used as filesystem path components. 63 // 64 // For the most part, this doesn't need to be called directly when using the 65 // context-oriented functions. 66 func Validate(s string) error { 67 if len(s) > maxLength { 68 return errors.Wrapf(errdefs.ErrInvalidArgument, "namespace %q greater than maximum length (%d characters)", s, maxLength) 69 } 70 71 if !namespaceRe.MatchString(s) { 72 return errors.Wrapf(errdefs.ErrInvalidArgument, "namespace %q must match %v", s, namespaceRe) 73 } 74 return nil 75 } 76 77 func reGroup(s string) string { 78 return `(?:` + s + `)` 79 } 80 81 func reAnchor(s string) string { 82 return `^` + s + `$` 83 }