github.com/tooploox/oya@v0.0.21-0.20230524103240-1cda1861aad6/cmd/internal/secrets.go (about)

     1  package internal
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  
     9  	"github.com/pkg/errors"
    10  	"github.com/tooploox/oya/pkg/secrets"
    11  )
    12  
    13  var ErrUnsupportedType = errors.New("Unsupported type")
    14  
    15  func SecretsInit(typ, email, name, desc, format string, stdout, stderr io.Writer) error {
    16  	if typ != "pgp" {
    17  		return ErrUnsupportedType
    18  	}
    19  
    20  	keyPair, err := secrets.Init(email, name, desc)
    21  	if err != nil {
    22  		return err
    23  	}
    24  
    25  	if err = secrets.GeneratePGPSopsYaml(keyPair); err != nil {
    26  		return err
    27  	}
    28  
    29  	if err = secrets.ImportPGPKeypair(keyPair); err != nil {
    30  		return err
    31  	}
    32  
    33  	if format == "json" {
    34  		b, err := json.MarshalIndent(keyPair, "", "  ")
    35  		if err != nil {
    36  			return err
    37  		}
    38  		stdout.Write(b)
    39  	} else {
    40  		fmt.Fprintf(stdout, "Generated a new PGP key (%q).\n", email)
    41  		fmt.Fprintf(stdout, "Fingerprint: %v\n", keyPair.Fingerprint)
    42  		fmt.Fprintf(stdout, "Imported the generated PGP key into GPG.\n")
    43  		fmt.Fprintf(stdout, "Generated .sops.yaml referencing the new key.\n")
    44  	}
    45  
    46  	return nil
    47  }
    48  
    49  func SecretsView(path string, stdout, stderr io.Writer) error {
    50  	output, found, err := secrets.Decrypt(path)
    51  	if err != nil {
    52  		return err
    53  	}
    54  	if !found {
    55  		return errors.Errorf("secret file %q not found", path)
    56  	}
    57  	stdout.Write(output)
    58  	return nil
    59  }
    60  
    61  func SecretsEdit(filename string, stdout, stderr io.Writer) error {
    62  	cmd := secrets.ViewCmd(filename)
    63  	cmd.Stdin = os.Stdin
    64  	cmd.Stdout = stdout
    65  	cmd.Stderr = stderr
    66  	return cmd.Run()
    67  }
    68  
    69  func SecretsEncrypt(path string, stdout, stderr io.Writer) error {
    70  	if err := secrets.Encrypt(path, path); err != nil {
    71  		return err
    72  	}
    73  	return nil
    74  }