diff --git a/cmd/cfg-envelope.go b/cmd/cfg-envelope.go index 5bbab2c..6d6eb11 100644 --- a/cmd/cfg-envelope.go +++ b/cmd/cfg-envelope.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/AlecAivazis/survey/v2" + "github.com/safing/jess" ) diff --git a/cmd/cfg-signet.go b/cmd/cfg-signet.go index 0de6db9..9ef217e 100644 --- a/cmd/cfg-signet.go +++ b/cmd/cfg-signet.go @@ -6,6 +6,7 @@ import ( "time" "github.com/AlecAivazis/survey/v2" + "github.com/safing/jess" "github.com/safing/jess/tools" ) diff --git a/cmd/cfg-tools.go b/cmd/cfg-tools.go index 7d3a1bb..b61b9ff 100644 --- a/cmd/cfg-tools.go +++ b/cmd/cfg-tools.go @@ -4,11 +4,10 @@ import ( "fmt" "strings" - "github.com/safing/jess/hashtools" - - "github.com/safing/jess/tools" - "github.com/AlecAivazis/survey/v2" + + "github.com/safing/jess/hashtools" + "github.com/safing/jess/tools" ) func pickTools(toolNames []string, promptMsg string) ([]string, error) { //nolint:unused,deadcode // TODO diff --git a/cmd/cmd-close.go b/cmd/cmd-close.go index a97ca7e..a3c788d 100644 --- a/cmd/cmd-close.go +++ b/cmd/cmd-close.go @@ -82,7 +82,7 @@ var ( return nil } } else if !os.IsNotExist(err) { - return fmt.Errorf("failed to access output file: %s", err) + return fmt.Errorf("failed to access output file: %w", err) } } @@ -114,7 +114,11 @@ var ( if outputFilename == "-" { file = os.Stdout } else { - file, err = os.OpenFile(outputFilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) + file, err = os.OpenFile( + outputFilename, + os.O_WRONLY|os.O_CREATE|os.O_TRUNC, + 0644, //nolint:gofumpt // gofumpt is ignorant of octal numbers. + ) if err != nil { return err } diff --git a/cmd/cmd-configure.go b/cmd/cmd-configure.go index 6828c4d..7907270 100644 --- a/cmd/cmd-configure.go +++ b/cmd/cmd-configure.go @@ -3,11 +3,10 @@ package main import ( "errors" - "github.com/safing/jess/truststores" + "github.com/spf13/cobra" "github.com/safing/jess" - - "github.com/spf13/cobra" + "github.com/safing/jess/truststores" ) func init() { @@ -34,7 +33,7 @@ var configureCmd = &cobra.Command{ // get envelope from trust store envelope, err := trustStore.GetEnvelope(envelopeName) - if err != nil && err != jess.ErrEnvelopeNotFound { + if err != nil && !errors.Is(err, jess.ErrEnvelopeNotFound) { return err } diff --git a/cmd/cmd-manage.go b/cmd/cmd-manage.go index 4af56bf..6685de4 100644 --- a/cmd/cmd-manage.go +++ b/cmd/cmd-manage.go @@ -6,8 +6,9 @@ import ( "strings" "github.com/AlecAivazis/survey/v2" - "github.com/safing/jess" "github.com/spf13/cobra" + + "github.com/safing/jess" ) const ( @@ -94,7 +95,7 @@ func manageSignets() error { case "Delete": err = trustStore.DeleteSignet(selectedSignet.ID, selectedSignet.Public) if err != nil { - return nil + return err } case "Back to list": continue diff --git a/cmd/cmd-open.go b/cmd/cmd-open.go index 97fedae..fc61306 100644 --- a/cmd/cmd-open.go +++ b/cmd/cmd-open.go @@ -8,11 +8,10 @@ import ( "os" "strings" - "github.com/safing/portbase/container" + "github.com/spf13/cobra" "github.com/safing/jess" - - "github.com/spf13/cobra" + "github.com/safing/portbase/container" ) func init() { @@ -73,7 +72,7 @@ var ( return nil } } else if !os.IsNotExist(err) { - return fmt.Errorf("failed to access output file: %s", err) + return fmt.Errorf("failed to access output file: %w", err) } } @@ -105,7 +104,11 @@ var ( if outputFilename == "-" { file = os.Stdout } else { - file, err = os.OpenFile(outputFilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) + file, err = os.OpenFile( + outputFilename, + os.O_WRONLY|os.O_CREATE|os.O_TRUNC, + 0644, //nolint:gofumpt // gofumpt is ignorant of octal numbers. + ) if err != nil { return err } diff --git a/cmd/cmd-verify.go b/cmd/cmd-verify.go index f53311d..6e36ad5 100644 --- a/cmd/cmd-verify.go +++ b/cmd/cmd-verify.go @@ -6,11 +6,10 @@ import ( "io/ioutil" "os" - "github.com/safing/portbase/container" + "github.com/spf13/cobra" "github.com/safing/jess" - - "github.com/spf13/cobra" + "github.com/safing/portbase/container" ) func init() { diff --git a/cmd/format.go b/cmd/format.go index d5b2b50..7c2ccca 100644 --- a/cmd/format.go +++ b/cmd/format.go @@ -3,6 +3,7 @@ package main import ( "bufio" "bytes" + "errors" "fmt" "strings" "text/tabwriter" @@ -111,7 +112,7 @@ func formatSignetSecurityLevel(signet *jess.Signet) string { securityLevel, err := tool.StaticLogic.SecurityLevel(signet) if err != nil { - if err == tools.ErrProtected { + if errors.Is(err, tools.ErrProtected) { return "[protected]" } return failPlaceholder diff --git a/cmd/main.go b/cmd/main.go index fbab954..2027948 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -5,15 +5,12 @@ import ( "fmt" "os" - "github.com/safing/jess/truststores" - - "github.com/safing/jess" - "github.com/spf13/cobra" - "github.com/safing/portbase/info" - // import all tools + "github.com/safing/jess" _ "github.com/safing/jess/tools/all" + "github.com/safing/jess/truststores" + "github.com/safing/portbase/info" ) const ( diff --git a/cmd/password.go b/cmd/password.go index ecc9692..3d95b5e 100644 --- a/cmd/password.go +++ b/cmd/password.go @@ -2,7 +2,7 @@ package main import ( "bufio" - "crypto/sha1" //nolint:gosec // required for HIBP API + "crypto/sha1" "encoding/hex" "errors" "fmt" @@ -10,9 +10,9 @@ import ( "net/http" "strings" - "github.com/safing/jess" - "github.com/AlecAivazis/survey/v2" + + "github.com/safing/jess" ) func registerPasswordCallbacks() { @@ -115,7 +115,7 @@ func checkForWeakPassword(pw string) error { // request hash list resp, err := http.Get(fmt.Sprintf("https://api.pwnedpasswords.com/range/%s", prefix)) if err != nil { - return fmt.Errorf("failed to contact HIBP service: %s", err) + return fmt.Errorf("failed to contact HIBP service: %w", err) } defer resp.Body.Close() @@ -139,7 +139,7 @@ func checkForWeakPassword(pw string) error { } // fmt.Printf("checked %d leaked passwords\n", cnt) if err := scanner.Err(); err != nil { - return fmt.Errorf("failed to read HIBP response: %s", err) + return fmt.Errorf("failed to read HIBP response: %w", err) } return nil diff --git a/cmd/password_test.go b/cmd/password_test.go index 341ec6f..b6b5898 100644 --- a/cmd/password_test.go +++ b/cmd/password_test.go @@ -6,6 +6,8 @@ import ( //nolint:unused,deadcode // tested manually func testCfWP(t *testing.T, password string, expectedError string) { + t.Helper() + var errMsg string err := checkForWeakPassword(password) if err != nil { @@ -17,7 +19,9 @@ func testCfWP(t *testing.T, password string, expectedError string) { } func TestCheckForWeakPassword(t *testing.T) { - // TODO: only run these manually, es they actually require the live HIBP API. + t.Parallel() + + // TODO: only run these manually, as they actually require the live HIBP API. // testCfWP(t, "asdfasdfasdf", "") // testCfWP(t, "mfJLiQH9O9V9zXYrkNeYvGLvE14HcPyW7/sWWGfBX2nBU7c", "") } diff --git a/core-wire.go b/core-wire.go index ddfd285..1d70fa6 100644 --- a/core-wire.go +++ b/core-wire.go @@ -26,7 +26,7 @@ func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error { case wireStateInit: // client keyMaterial, err = w.session.setupClosingKeyMaterial(letter) if err != nil { - return fmt.Errorf("failed to setup initial sending handshake key material: %s", err) + return fmt.Errorf("failed to setup initial sending handshake key material: %w", err) } fallthrough @@ -34,12 +34,12 @@ func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error { if w.msgNo == 0 || (!w.server && w.reKeyNeeded()) { err = w.generateLocalKeyExchangeSignets(letter) if err != nil { - return fmt.Errorf("failed to generate local key exchange signets for initiating handshake: %s", err) + return fmt.Errorf("failed to generate local key exchange signets for initiating handshake: %w", err) } err = w.generateLocalKeyEncapsulationSignets(letter) if err != nil { - return fmt.Errorf("failed to generate local key encapsulation signets for initiating handshake: %s", err) + return fmt.Errorf("failed to generate local key encapsulation signets for initiating handshake: %w", err) } w.handshakeState = wireStateAwaitKey @@ -49,7 +49,7 @@ func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error { err = w.generateLocalKeyExchangeSignets(letter) if err != nil { - return fmt.Errorf("failed to generate local key exchange signets for completing handshake: %s", err) + return fmt.Errorf("failed to generate local key exchange signets for completing handshake: %w", err) } // debugging: @@ -67,17 +67,17 @@ func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error { keyMaterial, err = w.makeSharedKeys(keyMaterial) if err != nil { - return fmt.Errorf("failed to create shared keys for completing handshake: %s", err) + return fmt.Errorf("failed to create shared keys for completing handshake: %w", err) } err = w.generateLocalKeyEncapsulationSignets(letter) if err != nil { - return fmt.Errorf("failed to generate local key encapsulation signets for completing handshake: %s", err) + return fmt.Errorf("failed to generate local key encapsulation signets for completing handshake: %w", err) } keyMaterial, err = w.makeAndEncapsulateNewKeys(letter, keyMaterial) if err != nil { - return fmt.Errorf("failed to encapsulate keys for completing handshake: %s", err) + return fmt.Errorf("failed to encapsulate keys for completing handshake: %w", err) } w.newKeyMaterial = copyKeyMaterial(keyMaterial) @@ -102,13 +102,13 @@ func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error { // init KDF err = w.session.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...) if err != nil { - return fmt.Errorf("failed to init %s kdf: %s", w.session.kdf.Info().Name, err) + return fmt.Errorf("failed to init %s kdf: %w", w.session.kdf.Info().Name, err) } // derive new carryover key err = w.session.kdf.DeriveKeyWriteTo(w.sendKeyCarryover) if err != nil { - return fmt.Errorf("failed to iterate session key with %s: %s", w.session.kdf.Info().Name, err) + return fmt.Errorf("failed to iterate session key with %s: %w", w.session.kdf.Info().Name, err) } if w.msgNo == 0 { // copy initial sendkey to recvkey @@ -137,7 +137,7 @@ func (w *WireSession) recvHandshakeAndInitKDF(letter *Letter) error { case wireStateInit: // server keyMaterial, err = w.session.setupOpeningKeyMaterial(letter) if err != nil { - return fmt.Errorf("failed to setup initial receiving handshake key material: %s", err) + return fmt.Errorf("failed to setup initial receiving handshake key material: %w", err) } fallthrough @@ -246,13 +246,13 @@ func (w *WireSession) recvHandshakeAndInitKDF(letter *Letter) error { // init KDF err = w.session.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...) if err != nil { - return fmt.Errorf("failed to init %s kdf: %s", w.session.kdf.Info().Name, err) + return fmt.Errorf("failed to init %s kdf: %w", w.session.kdf.Info().Name, err) } // derive new carryover key err = w.session.kdf.DeriveKeyWriteTo(w.recvKeyCarryover) if err != nil { - return fmt.Errorf("failed to iterate session key with %s: %s", w.session.kdf.Info().Name, err) + return fmt.Errorf("failed to iterate session key with %s: %w", w.session.kdf.Info().Name, err) } if w.msgNo == 0 { // copy initial recvkey to sendkey @@ -456,11 +456,11 @@ func (w *WireSession) burnEphemeralKeys() error { } func copyKeyMaterial(keyMaterial [][]byte) [][]byte { - new := make([][]byte, len(keyMaterial)) + copied := make([][]byte, len(keyMaterial)) for index, part := range keyMaterial { - newPart := make([]byte, len(part)) - copy(newPart, part) - new[index] = newPart + copiedPart := make([]byte, len(part)) + copy(copiedPart, part) + copied[index] = copiedPart } - return new + return copied } diff --git a/core-wire_test.go b/core-wire_test.go index 698a84b..a2e0f51 100644 --- a/core-wire_test.go +++ b/core-wire_test.go @@ -9,6 +9,8 @@ import ( ) func TestWire(t *testing.T) { + t.Parallel() + wireReKeyAfterMsgs = 100 // current suites recommendation @@ -21,6 +23,8 @@ func TestWire(t *testing.T) { } func testWireCorrespondence(t *testing.T, suite *Suite, testData string) { + t.Helper() + wtr := &wireTestRange{t: t} wtr.init(suite, testData) fmt.Printf("\n\nsimulating %v\n", suite.ID) diff --git a/core.go b/core.go index ad3acb6..188d71e 100644 --- a/core.go +++ b/core.go @@ -28,14 +28,14 @@ func (s *Session) Close(data []byte) (*Letter, error) { //nolint:gocognit data = copiedData } - ///////////////// + // ============== // key management - ///////////////// + // ============== // create nonce nonce, err := RandomBytes(s.NonceSize()) if err != nil { - return nil, fmt.Errorf("failed to get nonce: %s", err) + return nil, fmt.Errorf("failed to get nonce: %w", err) } letter.Nonce = nonce @@ -57,13 +57,13 @@ func (s *Session) Close(data []byte) (*Letter, error) { //nolint:gocognit // init KDF err = s.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...) if err != nil { - return nil, fmt.Errorf("failed to init %s kdf: %s", s.kdf.Info().Name, err) + return nil, fmt.Errorf("failed to init %s kdf: %w", s.kdf.Info().Name, err) } } - ///////////// + // ========== // encryption - ///////////// + // ========== // setup tools err = s.setup() @@ -76,7 +76,7 @@ func (s *Session) Close(data []byte) (*Letter, error) { //nolint:gocognit for _, tool := range s.ciphers { data, err = tool.Encrypt(data) if err != nil { - return nil, fmt.Errorf("failed to encrypt with %s: %s", tool.Info().Name, err) + return nil, fmt.Errorf("failed to encrypt with %s: %w", tool.Info().Name, err) } } @@ -89,7 +89,7 @@ func (s *Session) Close(data []byte) (*Letter, error) { //nolint:gocognit for _, tool := range s.integratedCiphers { data, err = tool.AuthenticatedEncrypt(data, associatedData) if err != nil { - return nil, fmt.Errorf("failed to auth-encrypt with %s: %s", tool.Info().Name, err) + return nil, fmt.Errorf("failed to auth-encrypt with %s: %w", tool.Info().Name, err) } } @@ -109,7 +109,7 @@ func (s *Session) Close(data []byte) (*Letter, error) { //nolint:gocognit for _, tool := range s.macs { mac, err := tool.MAC(data, associatedData) if err != nil { - return nil, fmt.Errorf("failed to calculate MAC with %s: %s", tool.Info().Name, err) + return nil, fmt.Errorf("failed to calculate MAC with %s: %w", tool.Info().Name, err) } allMacs.Append(mac) } @@ -144,7 +144,7 @@ func (s *Session) Close(data []byte) (*Letter, error) { //nolint:gocognit err = s.envelope.LoopSenders(tool.Info().Name, func(signet *Signet) error { sig, err := tool.Sign(data, associatedSigningData, signet) if err != nil { - return fmt.Errorf("failed to sign with %s: %s", tool.Info().Name, err) + return fmt.Errorf("failed to sign with %s: %w", tool.Info().Name, err) } letter.Signatures = append(letter.Signatures, &Seal{ @@ -180,9 +180,9 @@ func (s *Session) Open(letter *Letter) ([]byte, error) { //nolint:gocognit,gocyc return nil, fmt.Errorf("unsupported letter version: %d", letter.Version) } - ///////// + // ====== // verify - ///////// + // ====== // TODO: signature verification is run before tool setup. Currently, this is ok, but might change in the future. This might break additional signing algorithms that actually need setup. @@ -219,7 +219,7 @@ func (s *Session) Open(letter *Letter) ([]byte, error) { //nolint:gocognit,gocyc err = s.envelope.LoopSenders(tool.Info().Name, func(signet *Signet) error { err := tool.Verify(data, associatedSigningData, letter.Signatures[sigIndex].Value, signet) if err != nil { - return fmt.Errorf("failed to verify signature (%s) with ID %s: %s", tool.Info().Name, letter.Signatures[sigIndex].ID, err) + return fmt.Errorf("failed to verify signature (%s) with ID %s: %w", tool.Info().Name, letter.Signatures[sigIndex].ID, err) } sigIndex++ @@ -240,9 +240,9 @@ func (s *Session) Open(letter *Letter) ([]byte, error) { //nolint:gocognit,gocyc return data, nil } - ///////////////// + // ============== // key management - ///////////////// + // ============== // key establishment if s.wire != nil { @@ -259,13 +259,13 @@ func (s *Session) Open(letter *Letter) ([]byte, error) { //nolint:gocognit,gocyc // init KDF err = s.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...) if err != nil { - return nil, fmt.Errorf("failed to init %s kdf: %s", s.kdf.Info().Name, err) + return nil, fmt.Errorf("failed to init %s kdf: %w", s.kdf.Info().Name, err) } } - ///////////// + // ========== // decryption - ///////////// + // ========== // setup tools err = s.setup() @@ -291,7 +291,7 @@ func (s *Session) Open(letter *Letter) ([]byte, error) { //nolint:gocognit,gocyc for _, tool := range s.macs { mac, err := tool.MAC(data, associatedData) if err != nil { - return nil, fmt.Errorf("failed to calculate MAC with %s: %s", tool.Info().Name, err) + return nil, fmt.Errorf("failed to calculate MAC with %s: %w", tool.Info().Name, err) } allMacs.Append(mac) } @@ -334,9 +334,9 @@ func (s *Session) Verify(letter *Letter) error { return fmt.Errorf("unsupported letter version: %d", letter.Version) } - ///////// + // ====== // verify - ///////// + // ====== // TODO: signature verification is run before tool setup. Currently, this is ok, but might change in the future. This might break additional signing algorithms that actually need setup. @@ -373,7 +373,7 @@ func (s *Session) Verify(letter *Letter) error { err = s.envelope.LoopSenders(tool.Info().Name, func(signet *Signet) error { err := tool.Verify(data, associatedSigningData, letter.Signatures[sigIndex].Value, signet) if err != nil { - return fmt.Errorf("failed to verify signature (%s) with ID %s: %s", tool.Info().Name, letter.Signatures[sigIndex].ID, err) + return fmt.Errorf("failed to verify signature (%s) with ID %s: %w", tool.Info().Name, letter.Signatures[sigIndex].ID, err) } sigIndex++ @@ -413,7 +413,7 @@ func (s *Session) setupClosingKeyMaterial(letter *Letter) ([][]byte, error) { } pwKey, err := s.passDerivator.DeriveKeyFromPassword(signet.Key, letter.Nonce) if err != nil { - return fmt.Errorf("failed to get derive key from password with %s: %s", s.passDerivator.Info().Name, err) + return fmt.Errorf("failed to get derive key from password with %s: %w", s.passDerivator.Info().Name, err) } letter.Keys = append(letter.Keys, &Seal{ Scheme: SignetSchemePassword, @@ -436,23 +436,23 @@ func (s *Session) setupClosingKeyMaterial(letter *Letter) ([][]byte, error) { senderSignet := NewSignetBase(tool.Definition()) err := senderSignet.GenerateKey() if err != nil { - return fmt.Errorf("failed to generate new sender signet for %s: %s", tool.Info().Name, err) + return fmt.Errorf("failed to generate new sender signet for %s: %w", tool.Info().Name, err) } // create exchange and add to letter exchKey, err := tool.MakeSharedKey(senderSignet, recipient) if err != nil { - return fmt.Errorf("failed to make managed key with %s: %s", tool.Info().Name, err) + return fmt.Errorf("failed to make managed key with %s: %w", tool.Info().Name, err) } // add to letter senderRcpt, err := senderSignet.AsRecipient() // convert to public signet if err != nil { - return fmt.Errorf("failed to get public sender signet for %s: %s", tool.Info().Name, err) + return fmt.Errorf("failed to get public sender signet for %s: %w", tool.Info().Name, err) } err = senderRcpt.StoreKey() if err != nil { - return fmt.Errorf("failed to serialize sender public key for %s: %s", tool.Info().Name, err) + return fmt.Errorf("failed to serialize sender public key for %s: %w", tool.Info().Name, err) } letter.Keys = append(letter.Keys, &Seal{ ID: recipient.ID, @@ -492,13 +492,13 @@ func (s *Session) setupClosingKeyMaterial(letter *Letter) ([][]byte, error) { // generate new key newKey, err := RandomBytes(tool.Helper().DefaultSymmetricKeySize()) if err != nil { - return fmt.Errorf("failed to generate new key for %s: %s", tool.Info().Name, err) + return fmt.Errorf("failed to generate new key for %s: %w", tool.Info().Name, err) } // encapsulate key wrappedKey, err := tool.EncapsulateKey(newKey, recipient) if err != nil { - return fmt.Errorf("failed to encapsulate key with %s: %s", tool.Info().Name, err) + return fmt.Errorf("failed to encapsulate key with %s: %w", tool.Info().Name, err) } // add to letter @@ -553,7 +553,7 @@ func (s *Session) setupOpeningKeyMaterial(letter *Letter) ([][]byte, error) { } pwKey, err := s.passDerivator.DeriveKeyFromPassword(signet.Key, letter.Nonce) if err != nil { - return fmt.Errorf("failed to get derive key from password with %s: %s", s.passDerivator.Info().Name, err) + return fmt.Errorf("failed to get derive key from password with %s: %w", s.passDerivator.Info().Name, err) } keyMaterial = append(keyMaterial, pwKey) @@ -579,7 +579,7 @@ func (s *Session) setupOpeningKeyMaterial(letter *Letter) ([][]byte, error) { // load key err := peerSignet.LoadKey() if err != nil { - return fmt.Errorf("failed to load ephermal signet for key exchange: %s", err) + return fmt.Errorf("failed to load ephermal signet for key exchange: %w", err) } // save to state if s.wire != nil { @@ -592,7 +592,7 @@ func (s *Session) setupOpeningKeyMaterial(letter *Letter) ([][]byte, error) { // make shared key exchKey, err := tool.MakeSharedKey(signet, peerSignet) if err != nil { - return fmt.Errorf("failed to make shared key with %s: %s", tool.Info().Name, err) + return fmt.Errorf("failed to make shared key with %s: %w", tool.Info().Name, err) } // add key @@ -638,7 +638,7 @@ func (s *Session) setup() error { for _, tool := range s.toolsWithState { err := tool.Setup() if err != nil { - return fmt.Errorf("failed to run tool %s setup: %s", tool.Info().Name, err) + return fmt.Errorf("failed to run tool %s setup: %w", tool.Info().Name, err) } } @@ -651,7 +651,7 @@ func (s *Session) reset() error { for _, tool := range s.toolsWithState { err := tool.Reset() if err != nil { - return fmt.Errorf("failed to run tool %s reset: %s", tool.Info().Name, err) + return fmt.Errorf("failed to run tool %s reset: %w", tool.Info().Name, err) } } @@ -662,7 +662,7 @@ func (s *Session) feedManagedHashers(managedHashers map[string]*managedHasher, d for _, mngdHasher := range managedHashers { n, err := mngdHasher.hash.Write(data) if err != nil { - return fmt.Errorf("failed to write data to managed hasher %s: %s", mngdHasher.tool.Name, err) + return fmt.Errorf("failed to write data to managed hasher %s: %w", mngdHasher.tool.Name, err) } if n != len(data) { return fmt.Errorf("failed to fully write data to managed hasher %s", mngdHasher.tool.Name) @@ -670,7 +670,7 @@ func (s *Session) feedManagedHashers(managedHashers map[string]*managedHasher, d n, err = mngdHasher.hash.Write(associatedData) if err != nil { - return fmt.Errorf("failed to write associated data to managed hasher %s: %s", mngdHasher.tool.Name, err) + return fmt.Errorf("failed to write associated data to managed hasher %s: %w", mngdHasher.tool.Name, err) } if n != len(associatedData) { return fmt.Errorf("failed to fully write associated data to managed hasher %s", mngdHasher.tool.Name) diff --git a/core_test.go b/core_test.go index 6c86b2e..e79046c 100644 --- a/core_test.go +++ b/core_test.go @@ -46,6 +46,8 @@ var ( ) func tErrorf(t *testing.T, msg string, args ...interface{}) { + t.Helper() + t.Errorf(msg, args...) if runTestsInDebugStyleActive { debugStyleErrorCnt++ @@ -120,14 +122,17 @@ func init() { } func TestCoreBasic(t *testing.T) { + t.Parallel() + for _, suite := range Suites() { testStorage(t, suite) } } -//nolint:gocognit +// TestCoreAllCombinations tests all tools in all combinations and every tool +// should be tested when placed before and after every other tool. func TestCoreAllCombinations(t *testing.T) { - // This shall test all tools in all combinations and every tool should be tested when placed before and after every other tool. + t.Parallel() // skip in short tests and when not running comprehensive if testing.Short() || !runComprehensiveTestsActive { @@ -221,6 +226,8 @@ func TestCoreAllCombinations(t *testing.T) { } func testStorage(t *testing.T, suite *Suite) (detectedInvalid bool) { + t.Helper() + // t.Logf("testing storage with %s", suite.ID) e, err := setupEnvelopeAndTrustStore(t, suite) @@ -291,6 +298,8 @@ func testStorage(t *testing.T, suite *Suite) (detectedInvalid bool) { //nolint:gocognit,gocyclo func setupEnvelopeAndTrustStore(t *testing.T, suite *Suite) (*Envelope, error) { + t.Helper() + // check if suite is registered if suite.ID == "" { // register as test suite @@ -456,6 +465,8 @@ func testInvalidToolset(e *Envelope, whyInvalid string) error { } func getOrMakeSignet(t *testing.T, tool tools.ToolLogic, recipient bool, signetID string) (*Signet, error) { + t.Helper() + // check if signet already exists signet, err := testTrustStore.GetSignet(signetID, recipient) if err == nil { @@ -468,24 +479,24 @@ func getOrMakeSignet(t *testing.T, tool tools.ToolLogic, recipient bool, signetI } // create new signet - new := NewSignetBase(tool.Definition()) - new.ID = signetID + newSignet := NewSignetBase(tool.Definition()) + newSignet.ID = signetID // generate signet and log time taken start := time.Now() - err = tool.GenerateKey(new) + err = tool.GenerateKey(newSignet) if err != nil { return nil, err } - t.Logf("generated %s signet %s in %s", new.Scheme, new.ID, time.Since(start)) + t.Logf("generated %s signet %s in %s", newSignet.Scheme, newSignet.ID, time.Since(start)) // store signet - err = testTrustStore.StoreSignet(new) + err = testTrustStore.StoreSignet(newSignet) if err != nil { return nil, err } // store recipient - newRcpt, err := new.AsRecipient() + newRcpt, err := newSignet.AsRecipient() if err != nil { return nil, err } @@ -498,7 +509,7 @@ func getOrMakeSignet(t *testing.T, tool tools.ToolLogic, recipient bool, signetI if recipient { return newRcpt, nil } - return new, nil + return newSignet, nil } // generateCombinations returns all possible combinations of the given []string slice. diff --git a/defaults.go b/defaults.go index 796432e..f8fcb35 100644 --- a/defaults.go +++ b/defaults.go @@ -1,7 +1,7 @@ package jess var ( - // must be var in order decrease for testing for better speed + // Must be var in order decrease for testing for better speed. defaultSecurityLevel = 128 minimumSecurityLevel = 0 diff --git a/envelope.go b/envelope.go index 0277be0..48d0430 100644 --- a/envelope.go +++ b/envelope.go @@ -181,7 +181,7 @@ func (e *Envelope) prepSignets(signets []*Signet, recipients bool, storage Trust if signet.Scheme == SignetSchemePassword { err := fillPassword(signet, !recipients, storage, e.suite.SecurityLevel) if err != nil { - return fmt.Errorf(`failed to get password for "%s": %s`, signet.ID, err) + return fmt.Errorf(`failed to get password for "%s": %w`, signet.ID, err) } continue } @@ -202,19 +202,19 @@ func (e *Envelope) prepSignets(signets []*Signet, recipients bool, storage Trust } // get signet from trust store - new, err := storage.GetSignet(signet.ID, recipients) + newSignet, err := storage.GetSignet(signet.ID, recipients) if err != nil { - return fmt.Errorf(`failed to get signet with ID "%s" from truststore: %s`, signet.ID, err) + return fmt.Errorf(`failed to get signet with ID "%s" from truststore: %w`, signet.ID, err) } // check for scheme mismatch - if signet.Scheme != "" && signet.Scheme != new.Scheme { - return fmt.Errorf(`failed to apply signet with ID "%s" from truststore: was expected to be of type %s, but is %s`, signet.ID, signet.Scheme, new.Scheme) + if signet.Scheme != "" && signet.Scheme != newSignet.Scheme { + return fmt.Errorf(`failed to apply signet with ID "%s" from truststore: was expected to be of type %s, but is %s`, signet.ID, signet.Scheme, newSignet.Scheme) } // apply signet back into envelope - signet = new - signets[i] = new + signet = newSignet + signets[i] = newSignet } // unwrap protection @@ -252,12 +252,12 @@ func fillPassword(signet *Signet, createPassword bool, storage TrustStore, minSe // check trust store for name if len(signet.ID) > 0 && storage != nil { // get signet from trust store - new, err := storage.GetSignet(signet.ID, false) - if err == nil && new.Info != nil { + newSignet, err := storage.GetSignet(signet.ID, false) + if err == nil && newSignet.Info != nil { if signet.Info == nil { - signet.Info = new.Info + signet.Info = newSignet.Info } else { - signet.Info.Name = new.Info.Name + signet.Info.Name = newSignet.Info.Name } } } diff --git a/hashtools/blake2.go b/hashtools/blake2.go index c44738c..ad4b876 100644 --- a/hashtools/blake2.go +++ b/hashtools/blake2.go @@ -3,7 +3,7 @@ package hashtools import ( "crypto" - // register BLAKE2 in Go's internal registry + // Register BLAKE2 in Go's internal registry. _ "golang.org/x/crypto/blake2b" _ "golang.org/x/crypto/blake2s" ) diff --git a/hashtools/sha.go b/hashtools/sha.go index 48e7e8b..eb1e947 100644 --- a/hashtools/sha.go +++ b/hashtools/sha.go @@ -3,11 +3,11 @@ package hashtools import ( "crypto" - // register SHA2 in Go's internal registry + // Register SHA2 in Go's internal registry. _ "crypto/sha256" _ "crypto/sha512" - // register SHA3 in Go's internal registry + // Register SHA3 in Go's internal registry. _ "golang.org/x/crypto/sha3" ) diff --git a/hashtools/tools_test.go b/hashtools/tools_test.go index a4086b5..4884104 100644 --- a/hashtools/tools_test.go +++ b/hashtools/tools_test.go @@ -3,6 +3,8 @@ package hashtools import "testing" func TestAll(t *testing.T) { + t.Parallel() + testData := []byte("The quick brown fox jumps over the lazy dog. ") all := AsList() diff --git a/letter-file.go b/letter-file.go index a2078eb..ec5f773 100644 --- a/letter-file.go +++ b/letter-file.go @@ -3,9 +3,8 @@ package jess import ( "errors" - "github.com/safing/portbase/formats/dsd" - "github.com/safing/portbase/container" + "github.com/safing/portbase/formats/dsd" ) /* diff --git a/letter.go b/letter.go index 2c43374..edadd7b 100644 --- a/letter.go +++ b/letter.go @@ -11,7 +11,6 @@ import ( "fmt" "github.com/safing/portbase/container" - "github.com/safing/portbase/formats/dsd" ) @@ -186,7 +185,7 @@ func LetterFromDSD(data []byte) (*Letter, error) { const ( // Field IDs for signing - // These IDs MUST NOT CHANGE + // These IDs MUST NOT CHANGE. fieldIDLetterVersion uint64 = 1 // signed, MAC'd (may not exist when wired) fieldIDLetterSuiteID uint64 = 2 // signed, MAC'd (may not exist when wired) diff --git a/letter_test.go b/letter_test.go index 1887489..4ad49c2 100644 --- a/letter_test.go +++ b/letter_test.go @@ -9,6 +9,8 @@ import ( ) func TestSerialization(t *testing.T) { + t.Parallel() + subject := &Letter{ Version: 1, SuiteID: SuiteComplete, @@ -36,6 +38,8 @@ func TestSerialization(t *testing.T) { } func testSerialize(t *testing.T, letter *Letter, wireFormat bool) { //nolint:unparam + t.Helper() + // File Format fileData, err := letter.ToFileFormat() @@ -85,10 +89,9 @@ func (letter *Letter) CheckEqual(other *Letter) error { letterValue := reflect.ValueOf(*letter) otherValue := reflect.ValueOf(*other) + var ok bool numElements := letterValue.NumField() for i := 0; i < numElements; i++ { - ok := false - name := letterValue.Type().Field(i).Name switch name { case "Data": // TODO: this required special handling in the past, leave it here for now. diff --git a/lhash/algs.go b/lhash/algs.go index e10e552..948d7fe 100644 --- a/lhash/algs.go +++ b/lhash/algs.go @@ -1,17 +1,20 @@ +// Package lhash provides integrated labeled hashes. +// +//nolint:gci package lhash import ( "crypto" "hash" - // register SHA2 in Go's internal registry + // Register SHA2 in Go's internal registry. _ "crypto/sha256" _ "crypto/sha512" - // register SHA3 in Go's internal registry + // Register SHA3 in Go's internal registry. _ "golang.org/x/crypto/sha3" - // register BLAKE2 in Go's internal registry + // Register BLAKE2 in Go's internal registry. _ "golang.org/x/crypto/blake2b" _ "golang.org/x/crypto/blake2s" ) diff --git a/lhash/labeledhash.go b/lhash/labeledhash.go index 7c04ca7..55c42a6 100644 --- a/lhash/labeledhash.go +++ b/lhash/labeledhash.go @@ -36,12 +36,12 @@ func Load(labeledHash []byte) (*LabeledHash, error) { algID, err := c.GetNextN64() if err != nil { - return nil, fmt.Errorf("failed to parse algorithm ID: %s", err) + return nil, fmt.Errorf("failed to parse algorithm ID: %w", err) } digest, err := c.GetNextBlock() if err != nil { - return nil, fmt.Errorf("failed to parse digest: %s", err) + return nil, fmt.Errorf("failed to parse digest: %w", err) } if c.Length() > 0 { @@ -67,7 +67,7 @@ func Load(labeledHash []byte) (*LabeledHash, error) { func FromHex(hexEncoded string) (*LabeledHash, error) { raw, err := hex.DecodeString(hexEncoded) if err != nil { - return nil, fmt.Errorf("failed to decode hex: %s", err) + return nil, fmt.Errorf("failed to decode hex: %w", err) } return Load(raw) @@ -78,7 +78,7 @@ func FromHex(hexEncoded string) (*LabeledHash, error) { func FromBase64(base64Encoded string) (*LabeledHash, error) { raw, err := base64.RawURLEncoding.DecodeString(base64Encoded) if err != nil { - return nil, fmt.Errorf("failed to decode base64: %s", err) + return nil, fmt.Errorf("failed to decode base64: %w", err) } return Load(raw) @@ -89,7 +89,7 @@ func FromBase64(base64Encoded string) (*LabeledHash, error) { func FromBase58(base58Encoded string) (*LabeledHash, error) { raw, err := base58.Decode(base58Encoded) if err != nil { - return nil, fmt.Errorf("failed to decode base58: %s", err) + return nil, fmt.Errorf("failed to decode base58: %w", err) } return Load(raw) diff --git a/lhash/labeledhash_test.go b/lhash/labeledhash_test.go index fc52606..8ed91f1 100644 --- a/lhash/labeledhash_test.go +++ b/lhash/labeledhash_test.go @@ -15,6 +15,8 @@ var ( ) func testAlgorithm(t *testing.T, alg Algorithm, emptyHex, foxHex string) { + t.Helper() + // setup emptyBytes, err := hex.DecodeString(emptyHex) if err != nil { @@ -84,6 +86,8 @@ func testAlgorithm(t *testing.T, alg Algorithm, emptyHex, foxHex string) { } func testFormat(t *testing.T, alg Algorithm, lhs, loaded *LabeledHash) { + t.Helper() + noMatchLH := Digest(alg, noMatchData) // Test equality. @@ -110,6 +114,8 @@ func testFormat(t *testing.T, alg Algorithm, lhs, loaded *LabeledHash) { } func TestHash(t *testing.T) { + t.Parallel() + testAlgorithm(t, SHA2_256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c", diff --git a/password.go b/password.go index 7f06587..8004178 100644 --- a/password.go +++ b/password.go @@ -6,7 +6,7 @@ import ( ) var ( - // ASCII printable characters (character codes 32-127) + // ASCII printable characters (character codes 32-127). passwordCharSets = []string{ "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", @@ -16,7 +16,7 @@ var ( } // extended ASCII codes (character code 128-255) - // assume pool size of 32 (a quarter), as not all of them are common / easily accessible on every keyboard + // assume pool size of 32 (a quarter), as not all of them are common / easily accessible on every keyboard. passwordExtraPoolSize = 32 createPasswordCallback func(signet *Signet, minSecurityLevel int) error diff --git a/password_test.go b/password_test.go index 526ad81..d2c6fdc 100644 --- a/password_test.go +++ b/password_test.go @@ -21,6 +21,8 @@ func getTestPassword(signet *Signet) error { } func TestCalculatePasswordSecurityLevel(t *testing.T) { + t.Parallel() + // basic weak testPWSL(t, "asdf", -1) testPWSL(t, "asdfasdf", -1) @@ -82,6 +84,8 @@ func TestCalculatePasswordSecurityLevel(t *testing.T) { } func testPWSL(t *testing.T, password string, expectedSecurityLevel int) { + t.Helper() + securityLevel := CalculatePasswordSecurityLevel(password, 1<<20) if securityLevel < expectedSecurityLevel { diff --git a/requirements_test.go b/requirements_test.go index ad70bae..8cc1573 100644 --- a/requirements_test.go +++ b/requirements_test.go @@ -3,6 +3,8 @@ package jess import "testing" func checkNoSpec(t *testing.T, a *Requirements, expectedNoSpec string) { + t.Helper() + noSpec := a.SerializeToNoSpec() if noSpec != expectedNoSpec { t.Errorf(`unexpected no spec "%s", expected "%s"`, noSpec, expectedNoSpec) @@ -10,6 +12,8 @@ func checkNoSpec(t *testing.T, a *Requirements, expectedNoSpec string) { } func TestRequirements(t *testing.T) { + t.Parallel() + a := NewRequirements() checkNoSpec(t, a, "") diff --git a/session.go b/session.go index 932cb11..ad9c177 100644 --- a/session.go +++ b/session.go @@ -86,18 +86,18 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo // prepare variables var ( - keySourceAvailable bool = false + keySourceAvailable bool totalSignetsSeen int - requireSecurityLevel bool = false - requireDefaultKeySize bool = false + requireSecurityLevel bool + requireDefaultKeySize bool ) // tool init loop: start for i, toolID := range s.envelope.suite.Tools { - /////////////////////////////////////// + // ==================================== // tool init loop: check for duplicates - /////////////////////////////////////// + // ==================================== for j, dupeToolID := range s.envelope.suite.Tools { if i != j && toolID == dupeToolID { @@ -105,9 +105,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo } } - ////////////////////////////////////// + // =================================== // tool init loop: parse, prep and get - ////////////////////////////////////// + // =================================== var ( hashTool *hashtools.HashTool @@ -135,9 +135,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo s.toolsWithState = append(s.toolsWithState, logic) } - //////////////////////////////////////////////////////////// + // =========================================================== // tool init loop: assign tools to queues and add requirements - //////////////////////////////////////////////////////////// + // =========================================================== switch tool.Info.Purpose { case tools.PurposeKeyDerivation: @@ -180,9 +180,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo s.toolRequirements.Add(Integrity) } - /////////////////////////////////////////////// + // ============================================ // tool init loop: process options, get hashers - /////////////////////////////////////////////// + // ============================================ for _, option := range tool.Info.Options { switch option { @@ -242,9 +242,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo } } - ////////////////////////////////// + // =============================== // tool init loop: initialize tool - ////////////////////////////////// + // =============================== // init tool logic.Init( @@ -257,18 +257,18 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo hashSumFn, ) - ///////////////////////////////////////////////// + // ============================================== // tool init loop: calc and check security levels - ///////////////////////////////////////////////// + // ============================================== err = s.calcAndCheckSecurityLevel(logic, nil) if err != nil { return nil, err } - ///////////////////////////////////////////// + // ========================================== // tool init loop: calculate default key size - ///////////////////////////////////////////// + // ========================================== // find biggest key size for default if tool.Info.KeySize > s.DefaultSymmetricKeySize { @@ -277,9 +277,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo } // tool init loop: end - ////////////////////////////////////////////////////////// + // ======================================================= // calc and check signet security levels, default key size - ////////////////////////////////////////////////////////// + // ======================================================= for _, tool := range s.all { @@ -342,9 +342,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo return nil, err } - ///////////////////////////////////////////////////////// + // ====================================================== // check security level and default key size requirements - ///////////////////////////////////////////////////////// + // ====================================================== // apply manual security level if minimumSecurityLevel > 0 && minimumSecurityLevel > s.SecurityLevel { @@ -364,9 +364,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo return nil, fmt.Errorf("this toolset requires the default key size to be set manually") } - /////////////// + // ============ // final checks - /////////////// + // ============ // check requirements requirements if s.toolRequirements.Empty() { diff --git a/signet.go b/signet.go index 7946316..4913f19 100644 --- a/signet.go +++ b/signet.go @@ -7,9 +7,9 @@ import ( "io" "time" - "github.com/safing/jess/tools" - uuid "github.com/satori/go.uuid" + + "github.com/safing/jess/tools" ) // Special signet types. diff --git a/suites.go b/suites.go index 75b04d9..ce01b38 100644 --- a/suites.go +++ b/suites.go @@ -1,11 +1,11 @@ package jess var ( - // lists + // Suite Lists. suitesMap = make(map[string]*Suite) suitesList []*Suite - // suite definitions + // Suite Definitions. // SuiteKeyV1 is a cipher suite for encryption with a key. SuiteKeyV1 = registerSuite(&Suite{ @@ -56,7 +56,7 @@ var ( Status: SuiteStatusRecommended, }) - // currently recommended suites + // Currently Recommended Suites. // SuiteKey is a a cipher suite for encryption with a key. SuiteKey = SuiteKeyV1 diff --git a/suites_test.go b/suites_test.go index 18373dc..2b003a6 100644 --- a/suites_test.go +++ b/suites_test.go @@ -11,6 +11,8 @@ import ( ) func getSuite(t *testing.T, suiteID string) (suite *Suite) { + t.Helper() + suite, ok := GetSuite(suiteID) if !ok { t.Fatalf("suite %s does not exist", suiteID) @@ -20,6 +22,8 @@ func getSuite(t *testing.T, suiteID string) (suite *Suite) { } func TestSuites(t *testing.T) { + t.Parallel() + for _, suite := range Suites() { err := suiteBullshitCheck(suite) @@ -120,9 +124,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo // tool check loop: start for i, toolID := range suite.Tools { - //////////////////////////////////////// + // ===================================== // tool check loop: check for duplicates - //////////////////////////////////////// + // ===================================== for j, dupeToolID := range suite.Tools { if i != j && toolID == dupeToolID { @@ -130,9 +134,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo } } - /////////////////////////////////////// + // ==================================== // tool check loop: parse, prep and get - /////////////////////////////////////// + // ==================================== var ( hashTool *hashtools.HashTool @@ -160,9 +164,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo s.toolsWithState = append(s.toolsWithState, logic) } - /////////////////////////////////////////////////////////////// + // ============================================================ // tool check loop: assign tools to queues and add requirements - /////////////////////////////////////////////////////////////// + // ============================================================ switch tool.Info.Purpose { case tools.PurposeKeyDerivation: @@ -205,9 +209,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo s.toolRequirements.Add(Integrity) } - //////////////////////////////////////////////// + // ============================================= // tool check loop: process options, get hashers - //////////////////////////////////////////////// + // ============================================= for _, option := range tool.Info.Options { switch option { @@ -259,9 +263,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo } } - /////////////////////////////////// + // ================================ // tool check loop: initialize tool - /////////////////////////////////// + // ================================ // init tool logic.Init( @@ -274,9 +278,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo hashSumFn, ) - ////////////////////////////////////////////////// + // =============================================== // tool check loop: calc and check security levels - ////////////////////////////////////////////////// + // =============================================== err = s.calcAndCheckSecurityLevel(logic, nil) if err != nil { @@ -285,9 +289,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo } // tool check loop: end - /////////////// + // ============ // final checks - /////////////// + // ============ // check requirements requirements if s.toolRequirements.Empty() { @@ -319,9 +323,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo return errors.New("key derivation tool specified, but not needed") } - ///////////////////////////////////////// + // ====================================== // check if values match suite definition - ///////////////////////////////////////// + // ====================================== // check if security level matches if s.SecurityLevel != suite.SecurityLevel { @@ -337,9 +341,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo ) } - /////////////////////////////////////////////////////////// + // ======================================================== // check if computeSuiteAttributes returns the same results - /////////////////////////////////////////////////////////// + // ======================================================== computedSuite := computeSuiteAttributes(suite.Tools, assumeKey) if computedSuite == nil { @@ -360,23 +364,23 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo } func computeSuiteAttributes(toolIDs []string, assumeKey bool) *Suite { - new := &Suite{ + newSuite := &Suite{ Provides: newEmptyRequirements(), SecurityLevel: 0, } // if we have a key if assumeKey { - new.Provides.Add(SenderAuthentication) - new.Provides.Add(RecipientAuthentication) + newSuite.Provides.Add(SenderAuthentication) + newSuite.Provides.Add(RecipientAuthentication) } // check all security levels and collect attributes for _, toolID := range toolIDs { - /////////////////////////////////////// + // ==================================== // tool check loop: parse, prep and get - /////////////////////////////////////// + // ==================================== var hashTool *hashtools.HashTool @@ -397,38 +401,38 @@ func computeSuiteAttributes(toolIDs []string, assumeKey bool) *Suite { // create logic instance and add to logic and state lists logic := tool.Factory() - ////////////////////////////////////// + // =================================== // tool check loop: collect attributes - ////////////////////////////////////// + // =================================== switch tool.Info.Purpose { case tools.PurposePassDerivation: - new.Provides.Add(SenderAuthentication) - new.Provides.Add(RecipientAuthentication) + newSuite.Provides.Add(SenderAuthentication) + newSuite.Provides.Add(RecipientAuthentication) case tools.PurposeKeyExchange: - new.Provides.Add(RecipientAuthentication) + newSuite.Provides.Add(RecipientAuthentication) case tools.PurposeKeyEncapsulation: - new.Provides.Add(RecipientAuthentication) + newSuite.Provides.Add(RecipientAuthentication) case tools.PurposeSigning: - new.Provides.Add(SenderAuthentication) + newSuite.Provides.Add(SenderAuthentication) case tools.PurposeIntegratedCipher: - new.Provides.Add(Confidentiality) - new.Provides.Add(Integrity) + newSuite.Provides.Add(Confidentiality) + newSuite.Provides.Add(Integrity) case tools.PurposeCipher: - new.Provides.Add(Confidentiality) + newSuite.Provides.Add(Confidentiality) case tools.PurposeMAC: - new.Provides.Add(Integrity) + newSuite.Provides.Add(Integrity) } - //////////////////////////////////////////////// + // ============================================= // tool check loop: process options, get hashers - //////////////////////////////////////////////// + // ============================================= for _, option := range tool.Info.Options { switch option { @@ -441,9 +445,9 @@ func computeSuiteAttributes(toolIDs []string, assumeKey bool) *Suite { } } - /////////////////////////////////// + // ================================ // tool check loop: initialize tool - /////////////////////////////////// + // ================================ // init tool logic.Init( @@ -455,19 +459,19 @@ func computeSuiteAttributes(toolIDs []string, assumeKey bool) *Suite { nil, ) - ////////////////////////////////////////// + // ======================================= // tool check loop: compute security level - ////////////////////////////////////////// + // ======================================= toolSecurityLevel, err := logic.SecurityLevel(nil) if err != nil { return nil } - if new.SecurityLevel == 0 || toolSecurityLevel < new.SecurityLevel { - new.SecurityLevel = toolSecurityLevel + if newSuite.SecurityLevel == 0 || toolSecurityLevel < newSuite.SecurityLevel { + newSuite.SecurityLevel = toolSecurityLevel } } - return new + return newSuite } diff --git a/supply/supply.go b/supply/supply.go index 225c9ce..9ba1e1a 100644 --- a/supply/supply.go +++ b/supply/supply.go @@ -5,7 +5,6 @@ import ( "sync" "github.com/safing/jess" - "github.com/safing/jess/tools" ) diff --git a/supply/supply_test.go b/supply/supply_test.go index 57407fa..b3a1915 100644 --- a/supply/supply_test.go +++ b/supply/supply_test.go @@ -7,6 +7,8 @@ import ( ) func TestSupply(t *testing.T) { + t.Parallel() + total := 10 supply := NewSignetSupply(total) scheme := "ECDH-X25519" diff --git a/tools.go b/tools.go index 2951659..605e0bb 100644 --- a/tools.go +++ b/tools.go @@ -3,7 +3,7 @@ package jess import ( "github.com/safing/jess/tools" - // import all tools + // Import all tools. _ "github.com/safing/jess/tools/all" ) diff --git a/tools/all/all.go b/tools/all/all.go index df18e08..8d59fb8 100644 --- a/tools/all/all.go +++ b/tools/all/all.go @@ -1,7 +1,10 @@ +// Package all imports all tool subpackages +// +//nolint:gci package all import ( - // Import all tool subpackages + // Import all tool subpackages. _ "github.com/safing/jess/tools/ecdh" _ "github.com/safing/jess/tools/gostdlib" ) diff --git a/tools/ecdh/nist.go b/tools/ecdh/nist.go index 937dc55..371feeb 100644 --- a/tools/ecdh/nist.go +++ b/tools/ecdh/nist.go @@ -3,12 +3,13 @@ package ecdh import ( "crypto" "crypto/elliptic" + "fmt" "math/big" + "github.com/aead/ecdh" + "github.com/safing/jess/tools" "github.com/safing/portbase/container" - - "github.com/aead/ecdh" ) var nistCurveInfo = &tools.ToolInfo{ @@ -115,7 +116,10 @@ func (ec *NistCurve) StoreKey(signet tools.SignetInt) error { c.AppendNumber(1) // store public key - curvePoint := pubKey.(ecdh.Point) + curvePoint, ok := pubKey.(ecdh.Point) + if !ok { + return fmt.Errorf("public key of invalid type %T", pubKey) + } c.AppendAsBlock(curvePoint.X.Bytes()) c.AppendAsBlock(curvePoint.Y.Bytes()) diff --git a/tools/ecdh/x25519.go b/tools/ecdh/x25519.go index e4090cc..da6ce41 100644 --- a/tools/ecdh/x25519.go +++ b/tools/ecdh/x25519.go @@ -2,11 +2,12 @@ package ecdh import ( "crypto" + "fmt" + + "github.com/aead/ecdh" "github.com/safing/jess/tools" "github.com/safing/portbase/container" - - "github.com/aead/ecdh" ) func init() { @@ -87,10 +88,16 @@ func (ec *X25519Curve) StoreKey(signet tools.SignetInt) error { c.AppendNumber(1) // store keys - pubKeyData := pubKey.([32]byte) + pubKeyData, ok := pubKey.([32]byte) + if !ok { + return fmt.Errorf("public key of invalid type %T", pubKey) + } c.Append(pubKeyData[:]) if !public { - privKeyData := privKey.([32]byte) + privKeyData, ok := privKey.([32]byte) + if !ok { + return fmt.Errorf("private key of invalid type %T", privKey) + } c.Append(privKeyData[:]) } diff --git a/tools/gostdlib/chacha20-poly1305.go b/tools/gostdlib/chacha20-poly1305.go index e61ae8f..f659aa1 100644 --- a/tools/gostdlib/chacha20-poly1305.go +++ b/tools/gostdlib/chacha20-poly1305.go @@ -3,9 +3,9 @@ package gostdlib import ( "crypto/cipher" - "github.com/safing/jess/tools" - "golang.org/x/crypto/chacha20poly1305" + + "github.com/safing/jess/tools" ) func init() { diff --git a/tools/gostdlib/hkdf.go b/tools/gostdlib/hkdf.go index 7fe6bbf..45d4bb5 100644 --- a/tools/gostdlib/hkdf.go +++ b/tools/gostdlib/hkdf.go @@ -5,10 +5,10 @@ import ( "fmt" "io" + "golang.org/x/crypto/hkdf" + "github.com/safing/jess/tools" "github.com/safing/portbase/container" - - "golang.org/x/crypto/hkdf" ) func init() { @@ -56,12 +56,12 @@ func (keyder *HKDF) DeriveKey(size int) ([]byte, error) { } // DeriveKeyWriteTo implements the ToolLogic interface. -func (keyder *HKDF) DeriveKeyWriteTo(new []byte) error { - n, err := io.ReadFull(keyder.reader, new) +func (keyder *HKDF) DeriveKeyWriteTo(newKey []byte) error { + n, err := io.ReadFull(keyder.reader, newKey) if err != nil { - return fmt.Errorf("failed to generate key: %s", err) + return fmt.Errorf("failed to generate key: %w", err) } - if n != len(new) { + if n != len(newKey) { return errors.New("failed to generate key: EOF") } return nil diff --git a/tools/gostdlib/pbkdf2.go b/tools/gostdlib/pbkdf2.go index d363e55..601433a 100644 --- a/tools/gostdlib/pbkdf2.go +++ b/tools/gostdlib/pbkdf2.go @@ -4,9 +4,9 @@ import ( "crypto/sha256" "hash" - "github.com/safing/jess/tools" - "golang.org/x/crypto/pbkdf2" + + "github.com/safing/jess/tools" ) func init() { diff --git a/tools/gostdlib/poly1305.go b/tools/gostdlib/poly1305.go index 9ada378..e1640f3 100644 --- a/tools/gostdlib/poly1305.go +++ b/tools/gostdlib/poly1305.go @@ -3,8 +3,9 @@ package gostdlib import ( "errors" + "golang.org/x/crypto/poly1305" //nolint:staticcheck,gci + "github.com/safing/jess/tools" - "golang.org/x/crypto/poly1305" ) func init() { diff --git a/tools/gostdlib/rsa-keys.go b/tools/gostdlib/rsa-keys.go index 03fc981..8b5b0a4 100644 --- a/tools/gostdlib/rsa-keys.go +++ b/tools/gostdlib/rsa-keys.go @@ -8,7 +8,6 @@ import ( "math/big" "github.com/safing/jess/tools" - "github.com/safing/portbase/container" ) @@ -163,7 +162,7 @@ func (base *rsaBase) SecurityLevel(signet tools.SignetInt) (int, error) { if pubkey == nil { err := signet.LoadKey() if err != nil { - return 0, fmt.Errorf("failed to load key to calculate security level: %s", err) + return 0, fmt.Errorf("failed to load key to calculate security level: %w", err) } pubkey = signet.PublicKey() } diff --git a/tools/gostdlib/salsa20.go b/tools/gostdlib/salsa20.go index 01979e9..0bbf5bd 100644 --- a/tools/gostdlib/salsa20.go +++ b/tools/gostdlib/salsa20.go @@ -1,9 +1,9 @@ package gostdlib import ( - "github.com/safing/jess/tools" - "golang.org/x/crypto/salsa20" + + "github.com/safing/jess/tools" ) func init() { diff --git a/tools/interfaces.go b/tools/interfaces.go index 8b7b5e8..4e59925 100644 --- a/tools/interfaces.go +++ b/tools/interfaces.go @@ -41,7 +41,7 @@ type SignetInt interface { GetStoredKey() (key []byte, public bool) // SetStoredKey sets a new stored key and whether it is public. - SetStoredKey(new []byte, public bool) + SetStoredKey(newKey []byte, public bool) // PublicKey returns the public key. PublicKey() crypto.PublicKey diff --git a/tools/tool.go b/tools/tool.go index 9abdb24..845cba7 100644 --- a/tools/tool.go +++ b/tools/tool.go @@ -32,7 +32,7 @@ type ToolInfo struct { // Tool Purposes. const ( - // Key Management and Creation, as well as Authenticity + // Key Management and Creation, as well as Authenticity. // PurposeKeyDerivation declares key derivation capabilities. PurposeKeyDerivation uint8 = iota + 1 @@ -56,7 +56,7 @@ const ( // Provides SenderAuthentication attribute. Theoretically also provides integrity, but as signing is done after everything else, it will not be able to detect a wrong key during decryption. PurposeSigning - // Confidentiality and Integrity + // Confidentiality and Integrity. // PurposeIntegratedCipher declares that the tool provides both encryption and integrity verification capabilities. // Provies Confidentiality and Integrity requirements. @@ -73,13 +73,13 @@ const ( // Tool Options. const ( - // Operation + // Operation Types. // OptionStreaming declares that the tool can work with streaming data and might be given a io.Reader and io.Writer instead of just a []byte slice. // TODO: Implementation pending. OptionStreaming uint8 = iota + 1 - // Needs + // Needs. // OptionNeedsManagedHasher declares that the tool requires a hashing algorithm to work. It will automatically hash everything that needs to be authenticated and may be shared with other algorithms. OptionNeedsManagedHasher diff --git a/tools/toollogic.go b/tools/toollogic.go index b93a564..0461d38 100644 --- a/tools/toollogic.go +++ b/tools/toollogic.go @@ -51,7 +51,7 @@ type ToolLogic interface { // DeriveKeyWriteTo derives a new key and writes it into the given slice. // Must be overridden by tools that declare FeatureKeyDerivation. - DeriveKeyWriteTo(new []byte) error + DeriveKeyWriteTo(newKey []byte) error // Key Exchanging @@ -221,7 +221,7 @@ func (tlb *ToolLogicBase) DeriveKey(size int) ([]byte, error) { } // DeriveKeyWriteTo implements the ToolLogic interface. -func (tlb *ToolLogicBase) DeriveKeyWriteTo(new []byte) error { +func (tlb *ToolLogicBase) DeriveKeyWriteTo(newKey []byte) error { return ErrNotImplemented } diff --git a/tools_test.go b/tools_test.go index 3390885..34cbfae 100644 --- a/tools_test.go +++ b/tools_test.go @@ -7,14 +7,13 @@ import ( "time" "github.com/safing/jess/hashtools" - "github.com/safing/jess/tools" - - // import all tools for testing _ "github.com/safing/jess/tools/all" ) func TestConformity(t *testing.T) { + t.Parallel() + // Test that every tool only provides one primary feature, as this enables to automatically assign a distinct role to every tool. for _, tool := range tools.AsList() { @@ -35,7 +34,7 @@ func TestConformity(t *testing.T) { } } -func TestPasswordHashingSpeed(t *testing.T) { +func TestPasswordHashingSpeed(t *testing.T) { //nolint:paralleltest // skip in short tests and when not running comprehensive if testing.Short() || !runComprehensiveTestsActive { return @@ -63,6 +62,8 @@ func TestPasswordHashingSpeed(t *testing.T) { //nolint:gocognit,gocyclo func TestSignetHandling(t *testing.T) { + t.Parallel() + hashTool, err := hashtools.Get("SHA2-256") if err != nil { t.Fatal(err) diff --git a/truststores/dir.go b/truststores/dir.go index 25ab646..25484f0 100644 --- a/truststores/dir.go +++ b/truststores/dir.go @@ -115,7 +115,7 @@ func (dts *DirTrustStore) SelectSignets(filter uint8, schemes ...string) ([]*jes ID: strings.Split(filepath.Base(path), ".")[0], Public: strings.HasSuffix(path, recipientSuffix), }) - return nil + return err } // check signet scheme @@ -139,7 +139,7 @@ func (dts *DirTrustStore) SelectSignets(filter uint8, schemes ...string) ([]*jes return nil }) if err != nil { - return nil, fmt.Errorf("failed to access trust store entry: %s", err) + return nil, fmt.Errorf("failed to access trust store entry: %w", err) } return selection, nil @@ -226,14 +226,14 @@ func (dts *DirTrustStore) AllEnvelopes() ([]*jess.Envelope, error) { Name: fmt.Sprintf("%s [failed to load]", strings.TrimSuffix(filepath.Base(path), envelopeSuffix)), }) - return nil + return err } all = append(all, envelope) return nil }) if err != nil { - return nil, fmt.Errorf("failed to access trust store entry: %s", err) + return nil, fmt.Errorf("failed to access trust store entry: %w", err) } return all, nil @@ -247,9 +247,9 @@ func NewDirTrustStore(storageDir string) (*DirTrustStore, error) { info, err := os.Stat(cleanedPath) if err != nil { if os.IsNotExist(err) { - return nil, fmt.Errorf("trust store does not exist: %s", err) + return nil, fmt.Errorf("trust store does not exist: %w", err) } - return nil, fmt.Errorf("failed to access trust store: %s", err) + return nil, fmt.Errorf("failed to access trust store: %w", err) } if !info.IsDir() { return nil, errors.New("truststore storage dir is a file, not a directory") diff --git a/truststores/io.go b/truststores/io.go index ff420c3..33446b5 100644 --- a/truststores/io.go +++ b/truststores/io.go @@ -27,7 +27,7 @@ func WriteSignetToFile(signet *jess.Signet, filename string) error { } // write - err = ioutil.WriteFile(filename, data, 0600) + err = ioutil.WriteFile(filename, data, 0600) //nolint:gofumpt // gofumpt is ignorant of octal numbers. if err != nil { return err } @@ -72,7 +72,7 @@ func WriteEnvelopeToFile(envelope *jess.Envelope, filename string) error { } // write to storage - err = ioutil.WriteFile(filename, data, 0600) + err = ioutil.WriteFile(filename, data, 0600) //nolint:gofumpt // gofumpt is ignorant of octal numbers. if err != nil { return err }