Skip to content

Commit

Permalink
go lint
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianosela committed Jul 11, 2019
1 parent 598b706 commit 4b99fa1
Show file tree
Hide file tree
Showing 22 changed files with 148 additions and 46 deletions.
1 change: 1 addition & 0 deletions aes/cipher.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ type Cipher struct {
stash map[stashKey][]byte
}

// NewCipher is the constructor for a new Cipher object
func NewCipher() Cipher {
return Cipher{
stash: make(map[stashKey][]byte),
Expand Down
14 changes: 14 additions & 0 deletions audit/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import (

"github.com/pkg/errors"

// empty import as per https://godoc.org/github.com/lib/pq
_ "github.com/lib/pq"

"github.com/sirupsen/logrus"
"go.mozilla.org/sops/logging"
"gopkg.in/yaml.v2"
Expand Down Expand Up @@ -67,36 +69,46 @@ type config struct {

var auditors []Auditor

// SubmitEvent handles an event for all auditors
func SubmitEvent(event interface{}) {
for _, auditor := range auditors {
auditor.Handle(event)
}
}

// Register registers a new Auditor in the global auditor list
func Register(auditor Auditor) {
auditors = append(auditors, auditor)
}

// Auditor is notified when noteworthy events happen, for example when a file is encrypted or decrypted.
type Auditor interface {
Handle(event interface{})
}

// DecryptEvent contains fields relevant to a decryption event
type DecryptEvent struct {
File string
}

// EncryptEvent contains fields relevant to an encryption event
type EncryptEvent struct {
File string
}

// RotateEvent contains fields relevant to a key rotation event
type RotateEvent struct {
File string
}

// PostgresAuditor is a Postgres SQL DB implementation of the
// Auditor interface
type PostgresAuditor struct {
DB *sql.DB
}

// NewPostgresAuditor is the constructor for a new PostgresAuditor object
// initialized with the given db connection string
func NewPostgresAuditor(connStr string) (*PostgresAuditor, error) {
db, err := sql.Open("postgres", connStr)
pg := &PostgresAuditor{DB: db}
Expand All @@ -113,6 +125,8 @@ func NewPostgresAuditor(connStr string) (*PostgresAuditor, error) {
return pg, nil
}

// Handle is the PostgresAuditor implementation of the function required by the
// Auditor interface
func (p *PostgresAuditor) Handle(event interface{}) {
u, err := user.Current()
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion azkv/keysource.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func MasterKeysFromURLs(urls string) ([]*MasterKey, error) {
return keys, nil
}

// NewMasterKeyFromResourceID takes an Azure Key Vault key URL and returns a new MasterKey
// NewMasterKeyFromURL takes an Azure Key Vault key URL and returns a new MasterKey
// URL format is {vaultUrl}/keys/{key-name}/{key-version}
func NewMasterKeyFromURL(url string) (*MasterKey, error) {
k := &MasterKey{}
Expand Down
6 changes: 3 additions & 3 deletions azkv/keysource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,16 +92,16 @@ func TestKeyToMap(t *testing.T) {
}, key.ToMap())
}

var azureKeyAcceptanceTestUrl = flag.String("azure-key", "", "URL to Azure Key Vault (note that this can incur real costs!)")
var azureKeyAcceptanceTestURL = flag.String("azure-key", "", "URL to Azure Key Vault (note that this can incur real costs!)")

func TestRoundtrip(t *testing.T) {
if *azureKeyAcceptanceTestUrl == "" {
if *azureKeyAcceptanceTestURL == "" {
t.Skip("Azure URL not provided, skipping acceptance test")
}

input := []byte("test-string")

key, err := NewMasterKeyFromURL(*azureKeyAcceptanceTestUrl)
key, err := NewMasterKeyFromURL(*azureKeyAcceptanceTestURL)
if err != nil {
t.Fatal(err)
}
Expand Down
25 changes: 22 additions & 3 deletions cmd/sops/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@ import (
"gopkg.in/urfave/cli.v1"
)

// ExampleFileEmitter represents actions needed for a struct to be comliant
// with the sops example-file emitter interface
type ExampleFileEmitter interface {
EmitExample() []byte
}

// Store handles marshaling and unmarshaling from SOPS files
type Store interface {
sops.Store
ExampleFileEmitter
Expand Down Expand Up @@ -107,29 +110,37 @@ func LoadEncryptedFile(loader sops.EncryptedFileLoader, inputPath string) (*sops
return &tree, err
}

// NewExitError returns a cli.ExitError given an error (wrapped in a generic interface{})
// and an exit code to represent the failure
func NewExitError(i interface{}, exitCode int) *cli.ExitError {
if userErr, ok := i.(sops.UserError); ok {
return NewExitError(userErr.UserError(), exitCode)
}
return cli.NewExitError(i, exitCode)
}

// IsYAMLFile returns true if a given file path corresponds to a YAML file
func IsYAMLFile(path string) bool {
return strings.HasSuffix(path, ".yaml") || strings.HasSuffix(path, ".yml")
}

// IsJSONFile returns true if a given file path corresponds to a JSON file
func IsJSONFile(path string) bool {
return strings.HasSuffix(path, ".json")
}

// IsEnvFile returns true if a given file path corresponds to a .env file
func IsEnvFile(path string) bool {
return strings.HasSuffix(path, ".env")
}

// IsIniFile returns true if a given file path corresponds to a INI file
func IsIniFile(path string) bool {
return strings.HasSuffix(path, ".ini")
}

// DefaultStoreForPath returns the correct format-specific implementation
// of the Store interface given the path to a file
func DefaultStoreForPath(path string) Store {
if IsYAMLFile(path) {
return &yaml.Store{}
Expand All @@ -143,8 +154,12 @@ func DefaultStoreForPath(path string) Store {
return &json.BinaryStore{}
}

// KMS_ENC_CTX_BUG_FIXED_VERSION represents the SOPS version in which the
// encryption context bug was fixed
const KMS_ENC_CTX_BUG_FIXED_VERSION = "3.3.0"

// DetectKMSEncryptionContextBug returns true if the encryption context bug is detected
// in a given runtime sops.Tree object
func DetectKMSEncryptionContextBug(tree *sops.Tree) (bool, error) {
versionCheck, err := version.AIsNewerThanB(KMS_ENC_CTX_BUG_FIXED_VERSION, tree.Metadata.Version)
if err != nil {
Expand All @@ -161,6 +176,7 @@ func DetectKMSEncryptionContextBug(tree *sops.Tree) (bool, error) {
return false, nil
}

// GetKMSKeyWithEncryptionCtx returns the first KMS key affected by the encryption context bug as well as its location in the key groups.
func GetKMSKeyWithEncryptionCtx(tree *sops.Tree) (keyGroupIndex int, keyIndex int, key *kms.MasterKey) {
for i, kg := range tree.Metadata.KeyGroups {
for n, k := range kg {
Expand All @@ -181,6 +197,7 @@ func GetKMSKeyWithEncryptionCtx(tree *sops.Tree) (keyGroupIndex int, keyIndex in
return 0, 0, nil
}

// GenericDecryptOpts represents decryption options and config
type GenericDecryptOpts struct {
Cipher sops.Cipher
InputStore sops.Store
Expand Down Expand Up @@ -235,10 +252,9 @@ func FixAWSKMSEncryptionContextBug(opts GenericDecryptOpts, tree *sops.Tree) (*s
}
}
if response == "n" {
return nil, fmt.Errorf("Exiting. User responded no.")
} else {
persistFix = true
return nil, fmt.Errorf("Exiting. User responded no")
}
persistFix = true
}

dataKey := []byte{}
Expand Down Expand Up @@ -342,6 +358,7 @@ func RecoverDataKeyFromBuggyKMS(opts GenericDecryptOpts, tree *sops.Tree) []byte
return nil
}

// Diff represents a key diff
type Diff struct {
Common []keys.MasterKey
Added []keys.MasterKey
Expand All @@ -355,6 +372,7 @@ func max(a, b int) int {
return b
}

// DiffKeyGroups returns the list of diffs found in two sops.keyGroup slices
func DiffKeyGroups(ours, theirs []sops.KeyGroup) []Diff {
var diffs []Diff
for i := 0; i < max(len(ours), len(theirs)); i++ {
Expand Down Expand Up @@ -389,6 +407,7 @@ func DiffKeyGroups(ours, theirs []sops.KeyGroup) []Diff {
return diffs
}

// PrettyPrintDiffs prints a slice of Diff objects to stdout
func PrettyPrintDiffs(diffs []Diff) {
for i, diff := range diffs {
color.New(color.Underline).Printf("Group %d\n", i+1)
Expand Down
2 changes: 1 addition & 1 deletion cmd/sops/rotate.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func rotate(opts rotateOpts) ([]byte, error) {
File: tree.FilePath,
})

dataKey, err := common.DecryptTree(common.DecryptTreeOpts{
_, err = common.DecryptTree(common.DecryptTreeOpts{
Cipher: opts.Cipher, IgnoreMac: opts.IgnoreMAC, Tree: tree,
KeyServices: opts.KeyServices,
})
Expand Down
2 changes: 2 additions & 0 deletions cmd/sops/subcommand/publish/publish.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func init() {
log = logging.NewLogger("PUBLISH")
}

// Opts represents publish options and config
type Opts struct {
Interactive bool
Cipher sops.Cipher
Expand All @@ -33,6 +34,7 @@ type Opts struct {
InputStore sops.Store
}

// Run publish operation
func Run(opts Opts) error {
var fileContents []byte
path, err := filepath.Abs(opts.InputPath)
Expand Down
2 changes: 2 additions & 0 deletions cmd/sops/subcommand/updatekeys/updatekeys.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"go.mozilla.org/sops/keyservice"
)

// Opts represents key operation options and config
type Opts struct {
InputPath string
GroupQuorum int
Expand All @@ -20,6 +21,7 @@ type Opts struct {
ConfigPath string
}

// UpdateKeys update the keys for a given file
func UpdateKeys(opts Opts) error {
path, err := filepath.Abs(opts.InputPath)
if err != nil {
Expand Down
4 changes: 4 additions & 0 deletions logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ type TextFormatter struct {
logrus.TextFormatter
}

// Format formats a log entry onto bytes
func (f *TextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
bytes, err := f.TextFormatter.Format(entry)
name := color.New(color.Bold).Sprintf("[%s]", f.LoggerName)
return []byte(fmt.Sprintf("%s\t %s", name, bytes)), err
}

// NewLogger is the constructor for a new Logger object with the given name
func NewLogger(name string) *logrus.Logger {
log := logrus.New()
log.SetLevel(logrus.WarnLevel)
Expand All @@ -33,10 +35,12 @@ func NewLogger(name string) *logrus.Logger {
return log
}

// SetLevel sets the given level for all current Loggers
func SetLevel(level logrus.Level) {
for k := range Loggers {
Loggers[k].SetLevel(level)
}
}

// Loggers is the runtime map of logger name to logger object
var Loggers map[string]*logrus.Logger
4 changes: 4 additions & 0 deletions publish/gcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,23 @@ import (
"cloud.google.com/go/storage"
)

// GCSDestination represents the Google Cloud Storage destination
type GCSDestination struct {
gcsBucket string
gcsPrefix string
}

// NewGCSDestination is the constructor for a new Google Cloud Storage destination
func NewGCSDestination(gcsBucket string, gcsPrefix string) *GCSDestination {
return &GCSDestination{gcsBucket, gcsPrefix}
}

// Path returns a the GCS path for a file within this GCS Destination
func (gcsd *GCSDestination) Path(fileName string) string {
return fmt.Sprintf("gcs://%s/%s%s", gcsd.gcsBucket, gcsd.gcsPrefix, fileName)
}

// Upload uploads contents to a new file in GCS
func (gcsd *GCSDestination) Upload(fileContents []byte, fileName string) error {
ctx := context.Background()
client, err := storage.NewClient(ctx)
Expand Down
2 changes: 2 additions & 0 deletions publish/publish.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package publish

// Destination represents actions which all destination types
// must implement in order to be used by SOPS
type Destination interface {
Upload(fileContents []byte, fileName string) error
Path(fileName string) string
Expand Down
4 changes: 4 additions & 0 deletions publish/s3.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,23 @@ import (
"github.com/aws/aws-sdk-go/service/s3"
)

// S3Destination is the AWS S3 implementation of the Destination interface
type S3Destination struct {
s3Bucket string
s3Prefix string
}

// NewS3Destination is the constructor for a new S3 Destination
func NewS3Destination(s3Bucket string, s3Prefix string) *S3Destination {
return &S3Destination{s3Bucket, s3Prefix}
}

// Path returns the S3 path of a file in an S3 Destination (bucket)
func (s3d *S3Destination) Path(fileName string) string {
return fmt.Sprintf("s3://%s/%s%s", s3d.s3Bucket, s3d.s3Prefix, fileName)
}

// Upload uploads contents to a new file in an S3 Destination (bucket)
func (s3d *S3Destination) Upload(fileContents []byte, fileName string) error {
sess := session.Must(session.NewSession())
svc := s3.New(sess)
Expand Down
Loading

0 comments on commit 4b99fa1

Please sign in to comment.