@@ -21,6 +21,7 @@ import (
21
21
22
22
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
23
23
"k8s.io/apimachinery/pkg/runtime/schema"
24
+ "k8s.io/apimachinery/pkg/util/validation"
24
25
"k8s.io/cli-runtime/pkg/resource"
25
26
)
26
27
@@ -45,10 +46,15 @@ func CreateObjMetadata(namespace string, name string, gk schema.GroupKind) (*Obj
45
46
// Namespace can be empty, but name cannot.
46
47
name = strings .TrimSpace (name )
47
48
if name == "" {
48
- return nil , fmt .Errorf ("empty name for inventory object" )
49
+ return nil , fmt .Errorf ("empty name for object" )
50
+ }
51
+ // Manually validate name, since by the time k8s reports the error
52
+ // the invalid name has already been encoded into the inventory object.
53
+ if ! validateNameChars (name ) {
54
+ return nil , fmt .Errorf ("invalid characters in object name: %s" , name )
49
55
}
50
56
if gk .Empty () {
51
- return nil , fmt .Errorf ("empty GroupKind for inventory object" )
57
+ return nil , fmt .Errorf ("empty GroupKind for object" )
52
58
}
53
59
54
60
return & ObjMetadata {
@@ -58,6 +64,23 @@ func CreateObjMetadata(namespace string, name string, gk schema.GroupKind) (*Obj
58
64
}, nil
59
65
}
60
66
67
+ // validateNameChars returns false if the passed name string contains
68
+ // any invalid characters; true otherwise. The allowed characters for
69
+ // a Kubernetes resource name are:
70
+ //
71
+ // Most resource types require a name that can be used as a DNS label name
72
+ // as defined in RFC 1123. This means the name must:
73
+ //
74
+ // * contain no more than 253 characters
75
+ // * contain only lowercase alphanumeric characters, '-'
76
+ // * start with an alphanumeric character
77
+ // * end with an alphanumeric character
78
+ //
79
+ func validateNameChars (name string ) bool {
80
+ errs := validation .IsDNS1123Subdomain (name )
81
+ return len (errs ) == 0
82
+ }
83
+
61
84
// ParseObjMetadata takes a string, splits it into its five fields,
62
85
// and returns a pointer to an ObjMetadata struct storing the
63
86
// five fields. Example inventory string:
0 commit comments