1/*
2Copyright 2015 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package versioned
18
19import (
20	"crypto/tls"
21	"fmt"
22	"io/ioutil"
23
24	"k8s.io/api/core/v1"
25	"k8s.io/apimachinery/pkg/runtime"
26	"k8s.io/kubectl/pkg/generate"
27	"k8s.io/kubectl/pkg/util/hash"
28)
29
30// SecretForTLSGeneratorV1 supports stable generation of a TLS secret.
31type SecretForTLSGeneratorV1 struct {
32	// Name is the name of this TLS secret.
33	Name string
34	// Key is the path to the user's private key.
35	Key string
36	// Cert is the path to the user's public key certificate.
37	Cert string
38	// AppendHash; if true, derive a hash from the Secret and append it to the name
39	AppendHash bool
40}
41
42// Ensure it supports the generator pattern that uses parameter injection
43var _ generate.Generator = &SecretForTLSGeneratorV1{}
44
45// Ensure it supports the generator pattern that uses parameters specified during construction
46var _ generate.StructuredGenerator = &SecretForTLSGeneratorV1{}
47
48// Generate returns a secret using the specified parameters
49func (s SecretForTLSGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
50	err := generate.ValidateParams(s.ParamNames(), genericParams)
51	if err != nil {
52		return nil, err
53	}
54	delegate := &SecretForTLSGeneratorV1{}
55	hashParam, found := genericParams["append-hash"]
56	if found {
57		hashBool, isBool := hashParam.(bool)
58		if !isBool {
59			return nil, fmt.Errorf("expected bool, found :%v", hashParam)
60		}
61		delegate.AppendHash = hashBool
62		delete(genericParams, "append-hash")
63	}
64	params := map[string]string{}
65	for key, value := range genericParams {
66		strVal, isString := value.(string)
67		if !isString {
68			return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
69		}
70		params[key] = strVal
71	}
72	delegate.Name = params["name"]
73	delegate.Key = params["key"]
74	delegate.Cert = params["cert"]
75	return delegate.StructuredGenerate()
76}
77
78// StructuredGenerate outputs a secret object using the configured fields
79func (s SecretForTLSGeneratorV1) StructuredGenerate() (runtime.Object, error) {
80	if err := s.validate(); err != nil {
81		return nil, err
82	}
83	tlsCrt, err := readFile(s.Cert)
84	if err != nil {
85		return nil, err
86	}
87	tlsKey, err := readFile(s.Key)
88	if err != nil {
89		return nil, err
90	}
91
92	if _, err := tls.X509KeyPair(tlsCrt, tlsKey); err != nil {
93		return nil, fmt.Errorf("failed to load key pair %v", err)
94	}
95	// TODO: Add more validation.
96	// 1. If the certificate contains intermediates, it is a valid chain.
97	// 2. Format etc.
98
99	secret := &v1.Secret{}
100	secret.Name = s.Name
101	secret.Type = v1.SecretTypeTLS
102	secret.Data = map[string][]byte{}
103	secret.Data[v1.TLSCertKey] = []byte(tlsCrt)
104	secret.Data[v1.TLSPrivateKeyKey] = []byte(tlsKey)
105	if s.AppendHash {
106		h, err := hash.SecretHash(secret)
107		if err != nil {
108			return nil, err
109		}
110		secret.Name = fmt.Sprintf("%s-%s", secret.Name, h)
111	}
112	return secret, nil
113}
114
115// readFile just reads a file into a byte array.
116func readFile(file string) ([]byte, error) {
117	b, err := ioutil.ReadFile(file)
118	if err != nil {
119		return []byte{}, fmt.Errorf("Cannot read file %v, %v", file, err)
120	}
121	return b, nil
122}
123
124// ParamNames returns the set of supported input parameters when using the parameter injection generator pattern
125func (s SecretForTLSGeneratorV1) ParamNames() []generate.GeneratorParam {
126	return []generate.GeneratorParam{
127		{Name: "name", Required: true},
128		{Name: "key", Required: true},
129		{Name: "cert", Required: true},
130		{Name: "append-hash", Required: false},
131	}
132}
133
134// validate validates required fields are set to support structured generation
135func (s SecretForTLSGeneratorV1) validate() error {
136	// TODO: This is not strictly necessary. We can generate a self signed cert
137	// if no key/cert is given. The only requirement is that we either get both
138	// or none. See test/e2e/ingress_utils for self signed cert generation.
139	if len(s.Key) == 0 {
140		return fmt.Errorf("key must be specified")
141	}
142	if len(s.Cert) == 0 {
143		return fmt.Errorf("certificate must be specified")
144	}
145	return nil
146}
147