LEFT | RIGHT |
(no file at all) | |
| 1 package environs |
| 2 |
| 3 import ( |
| 4 "fmt" |
| 5 "io/ioutil" |
| 6 "launchpad.net/juju-core/cert" |
| 7 "launchpad.net/juju-core/environs/config" |
| 8 "os" |
| 9 "path/filepath" |
| 10 "time" |
| 11 ) |
| 12 |
| 13 type CreatedCert bool |
| 14 |
| 15 const ( |
| 16 CertCreated CreatedCert = true |
| 17 CertExists CreatedCert = false |
| 18 ) |
| 19 |
| 20 func WriteCertAndKeyToHome(name string, cert, key []byte) error { |
| 21 // If the $HOME/.juju directory doesn't exist, create it. |
| 22 jujuDir := filepath.Join(os.Getenv("HOME"), ".juju") |
| 23 if err := os.MkdirAll(jujuDir, 0775); err != nil { |
| 24 return err |
| 25 } |
| 26 path := filepath.Join(jujuDir, name) |
| 27 if err := ioutil.WriteFile(path+"-cert.pem", cert, 0644); err != nil { |
| 28 return err |
| 29 } |
| 30 return ioutil.WriteFile(path+"-private-key.pem", key, 0600) |
| 31 } |
| 32 |
| 33 func generateCertificate(environ Environ, writeCertAndKey func(environName strin
g, cert, key []byte) error) error { |
| 34 cfg := environ.Config() |
| 35 caCert, caKey, err := cert.NewCA(environ.Name(), time.Now().UTC().AddDat
e(10, 0, 0)) |
| 36 if err != nil { |
| 37 return err |
| 38 } |
| 39 m := cfg.AllAttrs() |
| 40 m["ca-cert"] = string(caCert) |
| 41 m["ca-private-key"] = string(caKey) |
| 42 cfg, err = config.New(m) |
| 43 if err != nil { |
| 44 return fmt.Errorf("cannot create environment configuration with
new CA: %v", err) |
| 45 } |
| 46 if err := environ.SetConfig(cfg); err != nil { |
| 47 return fmt.Errorf("cannot set environment configuration with CA:
%v", err) |
| 48 } |
| 49 if err := writeCertAndKey(environ.Name(), caCert, caKey); err != nil { |
| 50 return fmt.Errorf("cannot write CA certificate and key: %v", err
) |
| 51 } |
| 52 return nil |
| 53 } |
| 54 |
| 55 // EnsureCertificate makes sure that there is a certificate and private key |
| 56 // for the specified environment. If one does not exist, then a certificate |
| 57 // is generated. |
| 58 func EnsureCertificate(environ Environ, writeCertAndKey func(environName string,
cert, key []byte) error) (CreatedCert, error) { |
| 59 cfg := environ.Config() |
| 60 _, hasCACert := cfg.CACert() |
| 61 _, hasCAKey := cfg.CAPrivateKey() |
| 62 |
| 63 if hasCACert && hasCAKey { |
| 64 // All is good in the world. |
| 65 return CertExists, nil |
| 66 } |
| 67 // It is not possible to create an environment that has a private key, b
ut no certificate. |
| 68 if hasCACert && !hasCAKey { |
| 69 return CertExists, fmt.Errorf("environment configuration with a
certificate but no CA private key") |
| 70 } |
| 71 |
| 72 return CertCreated, generateCertificate(environ, writeCertAndKey) |
| 73 } |
LEFT | RIGHT |