sigs.k8s.io/cluster-api-provider-aws@v1.5.5/pkg/internal/mime/mime.go (about) 1 /* 2 Copyright 2020 The Kubernetes 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 mime 18 19 import ( 20 "bytes" 21 "fmt" 22 "html/template" 23 "mime/multipart" 24 "net/textproto" 25 "strings" 26 ) 27 28 const ( 29 includePart = "file:///etc/secret-userdata.txt\n" 30 ) 31 32 var ( 33 includeType = textproto.MIMEHeader{ 34 "content-type": {"text/x-include-url"}, 35 } 36 37 boothookType = textproto.MIMEHeader{ 38 "content-type": {"text/cloud-boothook"}, 39 } 40 41 multipartHeader = strings.Join([]string{ 42 "MIME-Version: 1.0", 43 "Content-Type: multipart/mixed; boundary=\"%s\"", 44 "\n", 45 }, "\n") 46 ) 47 48 type scriptVariables struct { 49 SecretPrefix string 50 Chunks int32 51 Region string 52 Endpoint string 53 } 54 55 // GenerateInitDocument renders a given template, applies MIME properties 56 // and returns a series of byte chunks which put together represent a UserData 57 // script. 58 func GenerateInitDocument(secretPrefix string, chunks int32, region string, endpoint string, secretFetchScript string) ([]byte, error) { 59 var secretFetchTemplate = template.Must(template.New("secret-fetch-script").Parse(secretFetchScript)) 60 61 var buf bytes.Buffer 62 mpWriter := multipart.NewWriter(&buf) 63 buf.WriteString(fmt.Sprintf(multipartHeader, mpWriter.Boundary())) 64 scriptWriter, err := mpWriter.CreatePart(boothookType) 65 if err != nil { 66 return []byte{}, err 67 } 68 69 scriptVariables := scriptVariables{ 70 SecretPrefix: secretPrefix, 71 Chunks: chunks, 72 Region: region, 73 Endpoint: endpoint, 74 } 75 76 var scriptBuf bytes.Buffer 77 if err := secretFetchTemplate.Execute(&scriptBuf, scriptVariables); err != nil { 78 return []byte{}, err 79 } 80 _, err = scriptWriter.Write(scriptBuf.Bytes()) 81 if err != nil { 82 return []byte{}, err 83 } 84 85 includeWriter, err := mpWriter.CreatePart(includeType) 86 if err != nil { 87 return []byte{}, err 88 } 89 90 _, err = includeWriter.Write([]byte(includePart)) 91 if err != nil { 92 return []byte{}, err 93 } 94 95 if err := mpWriter.Close(); err != nil { 96 return []byte{}, err 97 } 98 99 return buf.Bytes(), nil 100 }