Fix linter errors

This commit is contained in:
Daniel 2021-10-02 23:00:01 +02:00
parent 70f411c597
commit 5059051610
52 changed files with 305 additions and 241 deletions

View file

@ -6,6 +6,7 @@ import (
"strings" "strings"
"github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2"
"github.com/safing/jess" "github.com/safing/jess"
) )

View file

@ -6,6 +6,7 @@ import (
"time" "time"
"github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2"
"github.com/safing/jess" "github.com/safing/jess"
"github.com/safing/jess/tools" "github.com/safing/jess/tools"
) )

View file

@ -4,11 +4,10 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/safing/jess/hashtools"
"github.com/safing/jess/tools"
"github.com/AlecAivazis/survey/v2" "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 func pickTools(toolNames []string, promptMsg string) ([]string, error) { //nolint:unused,deadcode // TODO

View file

@ -82,7 +82,7 @@ var (
return nil return nil
} }
} else if !os.IsNotExist(err) { } 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 == "-" { if outputFilename == "-" {
file = os.Stdout file = os.Stdout
} else { } 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 { if err != nil {
return err return err
} }

View file

@ -3,11 +3,10 @@ package main
import ( import (
"errors" "errors"
"github.com/safing/jess/truststores" "github.com/spf13/cobra"
"github.com/safing/jess" "github.com/safing/jess"
"github.com/safing/jess/truststores"
"github.com/spf13/cobra"
) )
func init() { func init() {
@ -34,7 +33,7 @@ var configureCmd = &cobra.Command{
// get envelope from trust store // get envelope from trust store
envelope, err := trustStore.GetEnvelope(envelopeName) envelope, err := trustStore.GetEnvelope(envelopeName)
if err != nil && err != jess.ErrEnvelopeNotFound { if err != nil && !errors.Is(err, jess.ErrEnvelopeNotFound) {
return err return err
} }

View file

@ -6,8 +6,9 @@ import (
"strings" "strings"
"github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2"
"github.com/safing/jess"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/safing/jess"
) )
const ( const (
@ -94,7 +95,7 @@ func manageSignets() error {
case "Delete": case "Delete":
err = trustStore.DeleteSignet(selectedSignet.ID, selectedSignet.Public) err = trustStore.DeleteSignet(selectedSignet.ID, selectedSignet.Public)
if err != nil { if err != nil {
return nil return err
} }
case "Back to list": case "Back to list":
continue continue

View file

@ -8,11 +8,10 @@ import (
"os" "os"
"strings" "strings"
"github.com/safing/portbase/container" "github.com/spf13/cobra"
"github.com/safing/jess" "github.com/safing/jess"
"github.com/safing/portbase/container"
"github.com/spf13/cobra"
) )
func init() { func init() {
@ -73,7 +72,7 @@ var (
return nil return nil
} }
} else if !os.IsNotExist(err) { } 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 == "-" { if outputFilename == "-" {
file = os.Stdout file = os.Stdout
} else { } 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 { if err != nil {
return err return err
} }

View file

@ -6,11 +6,10 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"github.com/safing/portbase/container" "github.com/spf13/cobra"
"github.com/safing/jess" "github.com/safing/jess"
"github.com/safing/portbase/container"
"github.com/spf13/cobra"
) )
func init() { func init() {

View file

@ -3,6 +3,7 @@ package main
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"errors"
"fmt" "fmt"
"strings" "strings"
"text/tabwriter" "text/tabwriter"
@ -111,7 +112,7 @@ func formatSignetSecurityLevel(signet *jess.Signet) string {
securityLevel, err := tool.StaticLogic.SecurityLevel(signet) securityLevel, err := tool.StaticLogic.SecurityLevel(signet)
if err != nil { if err != nil {
if err == tools.ErrProtected { if errors.Is(err, tools.ErrProtected) {
return "[protected]" return "[protected]"
} }
return failPlaceholder return failPlaceholder

View file

@ -5,15 +5,12 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/safing/jess/truststores"
"github.com/safing/jess"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/safing/portbase/info" "github.com/safing/jess"
// import all tools
_ "github.com/safing/jess/tools/all" _ "github.com/safing/jess/tools/all"
"github.com/safing/jess/truststores"
"github.com/safing/portbase/info"
) )
const ( const (

View file

@ -2,7 +2,7 @@ package main
import ( import (
"bufio" "bufio"
"crypto/sha1" //nolint:gosec // required for HIBP API "crypto/sha1"
"encoding/hex" "encoding/hex"
"errors" "errors"
"fmt" "fmt"
@ -10,9 +10,9 @@ import (
"net/http" "net/http"
"strings" "strings"
"github.com/safing/jess"
"github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2"
"github.com/safing/jess"
) )
func registerPasswordCallbacks() { func registerPasswordCallbacks() {
@ -115,7 +115,7 @@ func checkForWeakPassword(pw string) error {
// request hash list // request hash list
resp, err := http.Get(fmt.Sprintf("https://api.pwnedpasswords.com/range/%s", prefix)) resp, err := http.Get(fmt.Sprintf("https://api.pwnedpasswords.com/range/%s", prefix))
if err != nil { 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() defer resp.Body.Close()
@ -139,7 +139,7 @@ func checkForWeakPassword(pw string) error {
} }
// fmt.Printf("checked %d leaked passwords\n", cnt) // fmt.Printf("checked %d leaked passwords\n", cnt)
if err := scanner.Err(); err != nil { 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 return nil

View file

@ -6,6 +6,8 @@ import (
//nolint:unused,deadcode // tested manually //nolint:unused,deadcode // tested manually
func testCfWP(t *testing.T, password string, expectedError string) { func testCfWP(t *testing.T, password string, expectedError string) {
t.Helper()
var errMsg string var errMsg string
err := checkForWeakPassword(password) err := checkForWeakPassword(password)
if err != nil { if err != nil {
@ -17,7 +19,9 @@ func testCfWP(t *testing.T, password string, expectedError string) {
} }
func TestCheckForWeakPassword(t *testing.T) { 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, "asdfasdfasdf", "")
// testCfWP(t, "mfJLiQH9O9V9zXYrkNeYvGLvE14HcPyW7/sWWGfBX2nBU7c", "") // testCfWP(t, "mfJLiQH9O9V9zXYrkNeYvGLvE14HcPyW7/sWWGfBX2nBU7c", "")
} }

View file

@ -26,7 +26,7 @@ func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error {
case wireStateInit: // client case wireStateInit: // client
keyMaterial, err = w.session.setupClosingKeyMaterial(letter) keyMaterial, err = w.session.setupClosingKeyMaterial(letter)
if err != nil { 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 fallthrough
@ -34,12 +34,12 @@ func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error {
if w.msgNo == 0 || (!w.server && w.reKeyNeeded()) { if w.msgNo == 0 || (!w.server && w.reKeyNeeded()) {
err = w.generateLocalKeyExchangeSignets(letter) err = w.generateLocalKeyExchangeSignets(letter)
if err != nil { 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) err = w.generateLocalKeyEncapsulationSignets(letter)
if err != nil { 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 w.handshakeState = wireStateAwaitKey
@ -49,7 +49,7 @@ func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error {
err = w.generateLocalKeyExchangeSignets(letter) err = w.generateLocalKeyExchangeSignets(letter)
if err != nil { 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: // debugging:
@ -67,17 +67,17 @@ func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error {
keyMaterial, err = w.makeSharedKeys(keyMaterial) keyMaterial, err = w.makeSharedKeys(keyMaterial)
if err != nil { 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) err = w.generateLocalKeyEncapsulationSignets(letter)
if err != nil { 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) keyMaterial, err = w.makeAndEncapsulateNewKeys(letter, keyMaterial)
if err != nil { 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) w.newKeyMaterial = copyKeyMaterial(keyMaterial)
@ -102,13 +102,13 @@ func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error {
// init KDF // init KDF
err = w.session.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...) err = w.session.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...)
if err != nil { 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 // derive new carryover key
err = w.session.kdf.DeriveKeyWriteTo(w.sendKeyCarryover) err = w.session.kdf.DeriveKeyWriteTo(w.sendKeyCarryover)
if err != nil { 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 { if w.msgNo == 0 {
// copy initial sendkey to recvkey // copy initial sendkey to recvkey
@ -137,7 +137,7 @@ func (w *WireSession) recvHandshakeAndInitKDF(letter *Letter) error {
case wireStateInit: // server case wireStateInit: // server
keyMaterial, err = w.session.setupOpeningKeyMaterial(letter) keyMaterial, err = w.session.setupOpeningKeyMaterial(letter)
if err != nil { 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 fallthrough
@ -246,13 +246,13 @@ func (w *WireSession) recvHandshakeAndInitKDF(letter *Letter) error {
// init KDF // init KDF
err = w.session.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...) err = w.session.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...)
if err != nil { 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 // derive new carryover key
err = w.session.kdf.DeriveKeyWriteTo(w.recvKeyCarryover) err = w.session.kdf.DeriveKeyWriteTo(w.recvKeyCarryover)
if err != nil { 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 { if w.msgNo == 0 {
// copy initial recvkey to sendkey // copy initial recvkey to sendkey
@ -456,11 +456,11 @@ func (w *WireSession) burnEphemeralKeys() error {
} }
func copyKeyMaterial(keyMaterial [][]byte) [][]byte { func copyKeyMaterial(keyMaterial [][]byte) [][]byte {
new := make([][]byte, len(keyMaterial)) copied := make([][]byte, len(keyMaterial))
for index, part := range keyMaterial { for index, part := range keyMaterial {
newPart := make([]byte, len(part)) copiedPart := make([]byte, len(part))
copy(newPart, part) copy(copiedPart, part)
new[index] = newPart copied[index] = copiedPart
} }
return new return copied
} }

View file

@ -9,6 +9,8 @@ import (
) )
func TestWire(t *testing.T) { func TestWire(t *testing.T) {
t.Parallel()
wireReKeyAfterMsgs = 100 wireReKeyAfterMsgs = 100
// current suites recommendation // current suites recommendation
@ -21,6 +23,8 @@ func TestWire(t *testing.T) {
} }
func testWireCorrespondence(t *testing.T, suite *Suite, testData string) { func testWireCorrespondence(t *testing.T, suite *Suite, testData string) {
t.Helper()
wtr := &wireTestRange{t: t} wtr := &wireTestRange{t: t}
wtr.init(suite, testData) wtr.init(suite, testData)
fmt.Printf("\n\nsimulating %v\n", suite.ID) fmt.Printf("\n\nsimulating %v\n", suite.ID)

72
core.go
View file

@ -28,14 +28,14 @@ func (s *Session) Close(data []byte) (*Letter, error) { //nolint:gocognit
data = copiedData data = copiedData
} }
///////////////// // ==============
// key management // key management
///////////////// // ==============
// create nonce // create nonce
nonce, err := RandomBytes(s.NonceSize()) nonce, err := RandomBytes(s.NonceSize())
if err != nil { 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 letter.Nonce = nonce
@ -57,13 +57,13 @@ func (s *Session) Close(data []byte) (*Letter, error) { //nolint:gocognit
// init KDF // init KDF
err = s.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...) err = s.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...)
if err != nil { 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 // encryption
///////////// // ==========
// setup tools // setup tools
err = s.setup() err = s.setup()
@ -76,7 +76,7 @@ func (s *Session) Close(data []byte) (*Letter, error) { //nolint:gocognit
for _, tool := range s.ciphers { for _, tool := range s.ciphers {
data, err = tool.Encrypt(data) data, err = tool.Encrypt(data)
if err != nil { 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 { for _, tool := range s.integratedCiphers {
data, err = tool.AuthenticatedEncrypt(data, associatedData) data, err = tool.AuthenticatedEncrypt(data, associatedData)
if err != nil { 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 { for _, tool := range s.macs {
mac, err := tool.MAC(data, associatedData) mac, err := tool.MAC(data, associatedData)
if err != nil { 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) 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 { err = s.envelope.LoopSenders(tool.Info().Name, func(signet *Signet) error {
sig, err := tool.Sign(data, associatedSigningData, signet) sig, err := tool.Sign(data, associatedSigningData, signet)
if err != nil { 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{ 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) return nil, fmt.Errorf("unsupported letter version: %d", letter.Version)
} }
///////// // ======
// verify // 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. // 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 = s.envelope.LoopSenders(tool.Info().Name, func(signet *Signet) error {
err := tool.Verify(data, associatedSigningData, letter.Signatures[sigIndex].Value, signet) err := tool.Verify(data, associatedSigningData, letter.Signatures[sigIndex].Value, signet)
if err != nil { 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++ sigIndex++
@ -240,9 +240,9 @@ func (s *Session) Open(letter *Letter) ([]byte, error) { //nolint:gocognit,gocyc
return data, nil return data, nil
} }
///////////////// // ==============
// key management // key management
///////////////// // ==============
// key establishment // key establishment
if s.wire != nil { if s.wire != nil {
@ -259,13 +259,13 @@ func (s *Session) Open(letter *Letter) ([]byte, error) { //nolint:gocognit,gocyc
// init KDF // init KDF
err = s.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...) err = s.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...)
if err != nil { 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 // decryption
///////////// // ==========
// setup tools // setup tools
err = s.setup() err = s.setup()
@ -291,7 +291,7 @@ func (s *Session) Open(letter *Letter) ([]byte, error) { //nolint:gocognit,gocyc
for _, tool := range s.macs { for _, tool := range s.macs {
mac, err := tool.MAC(data, associatedData) mac, err := tool.MAC(data, associatedData)
if err != nil { 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) allMacs.Append(mac)
} }
@ -334,9 +334,9 @@ func (s *Session) Verify(letter *Letter) error {
return fmt.Errorf("unsupported letter version: %d", letter.Version) return fmt.Errorf("unsupported letter version: %d", letter.Version)
} }
///////// // ======
// verify // 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. // 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 = s.envelope.LoopSenders(tool.Info().Name, func(signet *Signet) error {
err := tool.Verify(data, associatedSigningData, letter.Signatures[sigIndex].Value, signet) err := tool.Verify(data, associatedSigningData, letter.Signatures[sigIndex].Value, signet)
if err != nil { 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++ sigIndex++
@ -413,7 +413,7 @@ func (s *Session) setupClosingKeyMaterial(letter *Letter) ([][]byte, error) {
} }
pwKey, err := s.passDerivator.DeriveKeyFromPassword(signet.Key, letter.Nonce) pwKey, err := s.passDerivator.DeriveKeyFromPassword(signet.Key, letter.Nonce)
if err != nil { 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{ letter.Keys = append(letter.Keys, &Seal{
Scheme: SignetSchemePassword, Scheme: SignetSchemePassword,
@ -436,23 +436,23 @@ func (s *Session) setupClosingKeyMaterial(letter *Letter) ([][]byte, error) {
senderSignet := NewSignetBase(tool.Definition()) senderSignet := NewSignetBase(tool.Definition())
err := senderSignet.GenerateKey() err := senderSignet.GenerateKey()
if err != nil { 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 // create exchange and add to letter
exchKey, err := tool.MakeSharedKey(senderSignet, recipient) exchKey, err := tool.MakeSharedKey(senderSignet, recipient)
if err != nil { 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 // add to letter
senderRcpt, err := senderSignet.AsRecipient() // convert to public signet senderRcpt, err := senderSignet.AsRecipient() // convert to public signet
if err != nil { 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() err = senderRcpt.StoreKey()
if err != nil { 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{ letter.Keys = append(letter.Keys, &Seal{
ID: recipient.ID, ID: recipient.ID,
@ -492,13 +492,13 @@ func (s *Session) setupClosingKeyMaterial(letter *Letter) ([][]byte, error) {
// generate new key // generate new key
newKey, err := RandomBytes(tool.Helper().DefaultSymmetricKeySize()) newKey, err := RandomBytes(tool.Helper().DefaultSymmetricKeySize())
if err != nil { 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 // encapsulate key
wrappedKey, err := tool.EncapsulateKey(newKey, recipient) wrappedKey, err := tool.EncapsulateKey(newKey, recipient)
if err != nil { 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 // add to letter
@ -553,7 +553,7 @@ func (s *Session) setupOpeningKeyMaterial(letter *Letter) ([][]byte, error) {
} }
pwKey, err := s.passDerivator.DeriveKeyFromPassword(signet.Key, letter.Nonce) pwKey, err := s.passDerivator.DeriveKeyFromPassword(signet.Key, letter.Nonce)
if err != nil { 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) keyMaterial = append(keyMaterial, pwKey)
@ -579,7 +579,7 @@ func (s *Session) setupOpeningKeyMaterial(letter *Letter) ([][]byte, error) {
// load key // load key
err := peerSignet.LoadKey() err := peerSignet.LoadKey()
if err != nil { 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 // save to state
if s.wire != nil { if s.wire != nil {
@ -592,7 +592,7 @@ func (s *Session) setupOpeningKeyMaterial(letter *Letter) ([][]byte, error) {
// make shared key // make shared key
exchKey, err := tool.MakeSharedKey(signet, peerSignet) exchKey, err := tool.MakeSharedKey(signet, peerSignet)
if err != nil { 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 // add key
@ -638,7 +638,7 @@ func (s *Session) setup() error {
for _, tool := range s.toolsWithState { for _, tool := range s.toolsWithState {
err := tool.Setup() err := tool.Setup()
if err != nil { 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 { for _, tool := range s.toolsWithState {
err := tool.Reset() err := tool.Reset()
if err != nil { 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 { for _, mngdHasher := range managedHashers {
n, err := mngdHasher.hash.Write(data) n, err := mngdHasher.hash.Write(data)
if err != nil { 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) { if n != len(data) {
return fmt.Errorf("failed to fully write data to managed hasher %s", mngdHasher.tool.Name) 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) n, err = mngdHasher.hash.Write(associatedData)
if err != nil { 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) { if n != len(associatedData) {
return fmt.Errorf("failed to fully write associated data to managed hasher %s", mngdHasher.tool.Name) return fmt.Errorf("failed to fully write associated data to managed hasher %s", mngdHasher.tool.Name)

View file

@ -46,6 +46,8 @@ var (
) )
func tErrorf(t *testing.T, msg string, args ...interface{}) { func tErrorf(t *testing.T, msg string, args ...interface{}) {
t.Helper()
t.Errorf(msg, args...) t.Errorf(msg, args...)
if runTestsInDebugStyleActive { if runTestsInDebugStyleActive {
debugStyleErrorCnt++ debugStyleErrorCnt++
@ -120,14 +122,17 @@ func init() {
} }
func TestCoreBasic(t *testing.T) { func TestCoreBasic(t *testing.T) {
t.Parallel()
for _, suite := range Suites() { for _, suite := range Suites() {
testStorage(t, suite) 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) { 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 // skip in short tests and when not running comprehensive
if testing.Short() || !runComprehensiveTestsActive { if testing.Short() || !runComprehensiveTestsActive {
@ -221,6 +226,8 @@ func TestCoreAllCombinations(t *testing.T) {
} }
func testStorage(t *testing.T, suite *Suite) (detectedInvalid bool) { func testStorage(t *testing.T, suite *Suite) (detectedInvalid bool) {
t.Helper()
// t.Logf("testing storage with %s", suite.ID) // t.Logf("testing storage with %s", suite.ID)
e, err := setupEnvelopeAndTrustStore(t, suite) e, err := setupEnvelopeAndTrustStore(t, suite)
@ -291,6 +298,8 @@ func testStorage(t *testing.T, suite *Suite) (detectedInvalid bool) {
//nolint:gocognit,gocyclo //nolint:gocognit,gocyclo
func setupEnvelopeAndTrustStore(t *testing.T, suite *Suite) (*Envelope, error) { func setupEnvelopeAndTrustStore(t *testing.T, suite *Suite) (*Envelope, error) {
t.Helper()
// check if suite is registered // check if suite is registered
if suite.ID == "" { if suite.ID == "" {
// register as test suite // 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) { func getOrMakeSignet(t *testing.T, tool tools.ToolLogic, recipient bool, signetID string) (*Signet, error) {
t.Helper()
// check if signet already exists // check if signet already exists
signet, err := testTrustStore.GetSignet(signetID, recipient) signet, err := testTrustStore.GetSignet(signetID, recipient)
if err == nil { if err == nil {
@ -468,24 +479,24 @@ func getOrMakeSignet(t *testing.T, tool tools.ToolLogic, recipient bool, signetI
} }
// create new signet // create new signet
new := NewSignetBase(tool.Definition()) newSignet := NewSignetBase(tool.Definition())
new.ID = signetID newSignet.ID = signetID
// generate signet and log time taken // generate signet and log time taken
start := time.Now() start := time.Now()
err = tool.GenerateKey(new) err = tool.GenerateKey(newSignet)
if err != nil { if err != nil {
return nil, err 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 // store signet
err = testTrustStore.StoreSignet(new) err = testTrustStore.StoreSignet(newSignet)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// store recipient // store recipient
newRcpt, err := new.AsRecipient() newRcpt, err := newSignet.AsRecipient()
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -498,7 +509,7 @@ func getOrMakeSignet(t *testing.T, tool tools.ToolLogic, recipient bool, signetI
if recipient { if recipient {
return newRcpt, nil return newRcpt, nil
} }
return new, nil return newSignet, nil
} }
// generateCombinations returns all possible combinations of the given []string slice. // generateCombinations returns all possible combinations of the given []string slice.

View file

@ -1,7 +1,7 @@
package jess package jess
var ( 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 defaultSecurityLevel = 128
minimumSecurityLevel = 0 minimumSecurityLevel = 0

View file

@ -181,7 +181,7 @@ func (e *Envelope) prepSignets(signets []*Signet, recipients bool, storage Trust
if signet.Scheme == SignetSchemePassword { if signet.Scheme == SignetSchemePassword {
err := fillPassword(signet, !recipients, storage, e.suite.SecurityLevel) err := fillPassword(signet, !recipients, storage, e.suite.SecurityLevel)
if err != nil { 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 continue
} }
@ -202,19 +202,19 @@ func (e *Envelope) prepSignets(signets []*Signet, recipients bool, storage Trust
} }
// get signet from trust store // get signet from trust store
new, err := storage.GetSignet(signet.ID, recipients) newSignet, err := storage.GetSignet(signet.ID, recipients)
if err != nil { 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 // check for scheme mismatch
if signet.Scheme != "" && 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, 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, newSignet.Scheme)
} }
// apply signet back into envelope // apply signet back into envelope
signet = new signet = newSignet
signets[i] = new signets[i] = newSignet
} }
// unwrap protection // unwrap protection
@ -252,12 +252,12 @@ func fillPassword(signet *Signet, createPassword bool, storage TrustStore, minSe
// check trust store for name // check trust store for name
if len(signet.ID) > 0 && storage != nil { if len(signet.ID) > 0 && storage != nil {
// get signet from trust store // get signet from trust store
new, err := storage.GetSignet(signet.ID, false) newSignet, err := storage.GetSignet(signet.ID, false)
if err == nil && new.Info != nil { if err == nil && newSignet.Info != nil {
if signet.Info == nil { if signet.Info == nil {
signet.Info = new.Info signet.Info = newSignet.Info
} else { } else {
signet.Info.Name = new.Info.Name signet.Info.Name = newSignet.Info.Name
} }
} }
} }

View file

@ -3,7 +3,7 @@ package hashtools
import ( import (
"crypto" "crypto"
// register BLAKE2 in Go's internal registry // Register BLAKE2 in Go's internal registry.
_ "golang.org/x/crypto/blake2b" _ "golang.org/x/crypto/blake2b"
_ "golang.org/x/crypto/blake2s" _ "golang.org/x/crypto/blake2s"
) )

View file

@ -3,11 +3,11 @@ package hashtools
import ( import (
"crypto" "crypto"
// register SHA2 in Go's internal registry // Register SHA2 in Go's internal registry.
_ "crypto/sha256" _ "crypto/sha256"
_ "crypto/sha512" _ "crypto/sha512"
// register SHA3 in Go's internal registry // Register SHA3 in Go's internal registry.
_ "golang.org/x/crypto/sha3" _ "golang.org/x/crypto/sha3"
) )

View file

@ -3,6 +3,8 @@ package hashtools
import "testing" import "testing"
func TestAll(t *testing.T) { func TestAll(t *testing.T) {
t.Parallel()
testData := []byte("The quick brown fox jumps over the lazy dog. ") testData := []byte("The quick brown fox jumps over the lazy dog. ")
all := AsList() all := AsList()

View file

@ -3,9 +3,8 @@ package jess
import ( import (
"errors" "errors"
"github.com/safing/portbase/formats/dsd"
"github.com/safing/portbase/container" "github.com/safing/portbase/container"
"github.com/safing/portbase/formats/dsd"
) )
/* /*

View file

@ -11,7 +11,6 @@ import (
"fmt" "fmt"
"github.com/safing/portbase/container" "github.com/safing/portbase/container"
"github.com/safing/portbase/formats/dsd" "github.com/safing/portbase/formats/dsd"
) )
@ -186,7 +185,7 @@ func LetterFromDSD(data []byte) (*Letter, error) {
const ( const (
// Field IDs for signing // 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) fieldIDLetterVersion uint64 = 1 // signed, MAC'd (may not exist when wired)
fieldIDLetterSuiteID uint64 = 2 // signed, MAC'd (may not exist when wired) fieldIDLetterSuiteID uint64 = 2 // signed, MAC'd (may not exist when wired)

View file

@ -9,6 +9,8 @@ import (
) )
func TestSerialization(t *testing.T) { func TestSerialization(t *testing.T) {
t.Parallel()
subject := &Letter{ subject := &Letter{
Version: 1, Version: 1,
SuiteID: SuiteComplete, SuiteID: SuiteComplete,
@ -36,6 +38,8 @@ func TestSerialization(t *testing.T) {
} }
func testSerialize(t *testing.T, letter *Letter, wireFormat bool) { //nolint:unparam func testSerialize(t *testing.T, letter *Letter, wireFormat bool) { //nolint:unparam
t.Helper()
// File Format // File Format
fileData, err := letter.ToFileFormat() fileData, err := letter.ToFileFormat()
@ -85,10 +89,9 @@ func (letter *Letter) CheckEqual(other *Letter) error {
letterValue := reflect.ValueOf(*letter) letterValue := reflect.ValueOf(*letter)
otherValue := reflect.ValueOf(*other) otherValue := reflect.ValueOf(*other)
var ok bool
numElements := letterValue.NumField() numElements := letterValue.NumField()
for i := 0; i < numElements; i++ { for i := 0; i < numElements; i++ {
ok := false
name := letterValue.Type().Field(i).Name name := letterValue.Type().Field(i).Name
switch name { switch name {
case "Data": // TODO: this required special handling in the past, leave it here for now. case "Data": // TODO: this required special handling in the past, leave it here for now.

View file

@ -1,17 +1,20 @@
// Package lhash provides integrated labeled hashes.
//
//nolint:gci
package lhash package lhash
import ( import (
"crypto" "crypto"
"hash" "hash"
// register SHA2 in Go's internal registry // Register SHA2 in Go's internal registry.
_ "crypto/sha256" _ "crypto/sha256"
_ "crypto/sha512" _ "crypto/sha512"
// register SHA3 in Go's internal registry // Register SHA3 in Go's internal registry.
_ "golang.org/x/crypto/sha3" _ "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/blake2b"
_ "golang.org/x/crypto/blake2s" _ "golang.org/x/crypto/blake2s"
) )

View file

@ -36,12 +36,12 @@ func Load(labeledHash []byte) (*LabeledHash, error) {
algID, err := c.GetNextN64() algID, err := c.GetNextN64()
if err != nil { 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() digest, err := c.GetNextBlock()
if err != nil { 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 { if c.Length() > 0 {
@ -67,7 +67,7 @@ func Load(labeledHash []byte) (*LabeledHash, error) {
func FromHex(hexEncoded string) (*LabeledHash, error) { func FromHex(hexEncoded string) (*LabeledHash, error) {
raw, err := hex.DecodeString(hexEncoded) raw, err := hex.DecodeString(hexEncoded)
if err != nil { 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) return Load(raw)
@ -78,7 +78,7 @@ func FromHex(hexEncoded string) (*LabeledHash, error) {
func FromBase64(base64Encoded string) (*LabeledHash, error) { func FromBase64(base64Encoded string) (*LabeledHash, error) {
raw, err := base64.RawURLEncoding.DecodeString(base64Encoded) raw, err := base64.RawURLEncoding.DecodeString(base64Encoded)
if err != nil { 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) return Load(raw)
@ -89,7 +89,7 @@ func FromBase64(base64Encoded string) (*LabeledHash, error) {
func FromBase58(base58Encoded string) (*LabeledHash, error) { func FromBase58(base58Encoded string) (*LabeledHash, error) {
raw, err := base58.Decode(base58Encoded) raw, err := base58.Decode(base58Encoded)
if err != nil { 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) return Load(raw)

View file

@ -15,6 +15,8 @@ var (
) )
func testAlgorithm(t *testing.T, alg Algorithm, emptyHex, foxHex string) { func testAlgorithm(t *testing.T, alg Algorithm, emptyHex, foxHex string) {
t.Helper()
// setup // setup
emptyBytes, err := hex.DecodeString(emptyHex) emptyBytes, err := hex.DecodeString(emptyHex)
if err != nil { 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) { func testFormat(t *testing.T, alg Algorithm, lhs, loaded *LabeledHash) {
t.Helper()
noMatchLH := Digest(alg, noMatchData) noMatchLH := Digest(alg, noMatchData)
// Test equality. // Test equality.
@ -110,6 +114,8 @@ func testFormat(t *testing.T, alg Algorithm, lhs, loaded *LabeledHash) {
} }
func TestHash(t *testing.T) { func TestHash(t *testing.T) {
t.Parallel()
testAlgorithm(t, SHA2_256, testAlgorithm(t, SHA2_256,
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c", "ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c",

View file

@ -6,7 +6,7 @@ import (
) )
var ( var (
// ASCII printable characters (character codes 32-127) // ASCII printable characters (character codes 32-127).
passwordCharSets = []string{ passwordCharSets = []string{
"abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
@ -16,7 +16,7 @@ var (
} }
// extended ASCII codes (character code 128-255) // 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 passwordExtraPoolSize = 32
createPasswordCallback func(signet *Signet, minSecurityLevel int) error createPasswordCallback func(signet *Signet, minSecurityLevel int) error

View file

@ -21,6 +21,8 @@ func getTestPassword(signet *Signet) error {
} }
func TestCalculatePasswordSecurityLevel(t *testing.T) { func TestCalculatePasswordSecurityLevel(t *testing.T) {
t.Parallel()
// basic weak // basic weak
testPWSL(t, "asdf", -1) testPWSL(t, "asdf", -1)
testPWSL(t, "asdfasdf", -1) testPWSL(t, "asdfasdf", -1)
@ -82,6 +84,8 @@ func TestCalculatePasswordSecurityLevel(t *testing.T) {
} }
func testPWSL(t *testing.T, password string, expectedSecurityLevel int) { func testPWSL(t *testing.T, password string, expectedSecurityLevel int) {
t.Helper()
securityLevel := CalculatePasswordSecurityLevel(password, 1<<20) securityLevel := CalculatePasswordSecurityLevel(password, 1<<20)
if securityLevel < expectedSecurityLevel { if securityLevel < expectedSecurityLevel {

View file

@ -3,6 +3,8 @@ package jess
import "testing" import "testing"
func checkNoSpec(t *testing.T, a *Requirements, expectedNoSpec string) { func checkNoSpec(t *testing.T, a *Requirements, expectedNoSpec string) {
t.Helper()
noSpec := a.SerializeToNoSpec() noSpec := a.SerializeToNoSpec()
if noSpec != expectedNoSpec { if noSpec != expectedNoSpec {
t.Errorf(`unexpected no spec "%s", expected "%s"`, 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) { func TestRequirements(t *testing.T) {
t.Parallel()
a := NewRequirements() a := NewRequirements()
checkNoSpec(t, a, "") checkNoSpec(t, a, "")

View file

@ -86,18 +86,18 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo
// prepare variables // prepare variables
var ( var (
keySourceAvailable bool = false keySourceAvailable bool
totalSignetsSeen int totalSignetsSeen int
requireSecurityLevel bool = false requireSecurityLevel bool
requireDefaultKeySize bool = false requireDefaultKeySize bool
) )
// tool init loop: start // tool init loop: start
for i, toolID := range s.envelope.suite.Tools { for i, toolID := range s.envelope.suite.Tools {
/////////////////////////////////////// // ====================================
// tool init loop: check for duplicates // tool init loop: check for duplicates
/////////////////////////////////////// // ====================================
for j, dupeToolID := range s.envelope.suite.Tools { for j, dupeToolID := range s.envelope.suite.Tools {
if i != j && toolID == dupeToolID { 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 // tool init loop: parse, prep and get
////////////////////////////////////// // ===================================
var ( var (
hashTool *hashtools.HashTool hashTool *hashtools.HashTool
@ -135,9 +135,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo
s.toolsWithState = append(s.toolsWithState, logic) s.toolsWithState = append(s.toolsWithState, logic)
} }
//////////////////////////////////////////////////////////// // ===========================================================
// tool init loop: assign tools to queues and add requirements // tool init loop: assign tools to queues and add requirements
//////////////////////////////////////////////////////////// // ===========================================================
switch tool.Info.Purpose { switch tool.Info.Purpose {
case tools.PurposeKeyDerivation: case tools.PurposeKeyDerivation:
@ -180,9 +180,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo
s.toolRequirements.Add(Integrity) s.toolRequirements.Add(Integrity)
} }
/////////////////////////////////////////////// // ============================================
// tool init loop: process options, get hashers // tool init loop: process options, get hashers
/////////////////////////////////////////////// // ============================================
for _, option := range tool.Info.Options { for _, option := range tool.Info.Options {
switch option { switch option {
@ -242,9 +242,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo
} }
} }
////////////////////////////////// // ===============================
// tool init loop: initialize tool // tool init loop: initialize tool
////////////////////////////////// // ===============================
// init tool // init tool
logic.Init( logic.Init(
@ -257,18 +257,18 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo
hashSumFn, hashSumFn,
) )
///////////////////////////////////////////////// // ==============================================
// tool init loop: calc and check security levels // tool init loop: calc and check security levels
///////////////////////////////////////////////// // ==============================================
err = s.calcAndCheckSecurityLevel(logic, nil) err = s.calcAndCheckSecurityLevel(logic, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
///////////////////////////////////////////// // ==========================================
// tool init loop: calculate default key size // tool init loop: calculate default key size
///////////////////////////////////////////// // ==========================================
// find biggest key size for default // find biggest key size for default
if tool.Info.KeySize > s.DefaultSymmetricKeySize { if tool.Info.KeySize > s.DefaultSymmetricKeySize {
@ -277,9 +277,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo
} // tool init loop: end } // tool init loop: end
////////////////////////////////////////////////////////// // =======================================================
// calc and check signet security levels, default key size // calc and check signet security levels, default key size
////////////////////////////////////////////////////////// // =======================================================
for _, tool := range s.all { for _, tool := range s.all {
@ -342,9 +342,9 @@ func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo
return nil, err return nil, err
} }
///////////////////////////////////////////////////////// // ======================================================
// check security level and default key size requirements // check security level and default key size requirements
///////////////////////////////////////////////////////// // ======================================================
// apply manual security level // apply manual security level
if minimumSecurityLevel > 0 && minimumSecurityLevel > s.SecurityLevel { 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") return nil, fmt.Errorf("this toolset requires the default key size to be set manually")
} }
/////////////// // ============
// final checks // final checks
/////////////// // ============
// check requirements requirements // check requirements requirements
if s.toolRequirements.Empty() { if s.toolRequirements.Empty() {

View file

@ -7,9 +7,9 @@ import (
"io" "io"
"time" "time"
"github.com/safing/jess/tools"
uuid "github.com/satori/go.uuid" uuid "github.com/satori/go.uuid"
"github.com/safing/jess/tools"
) )
// Special signet types. // Special signet types.

View file

@ -1,11 +1,11 @@
package jess package jess
var ( var (
// lists // Suite Lists.
suitesMap = make(map[string]*Suite) suitesMap = make(map[string]*Suite)
suitesList []*Suite suitesList []*Suite
// suite definitions // Suite Definitions.
// SuiteKeyV1 is a cipher suite for encryption with a key. // SuiteKeyV1 is a cipher suite for encryption with a key.
SuiteKeyV1 = registerSuite(&Suite{ SuiteKeyV1 = registerSuite(&Suite{
@ -56,7 +56,7 @@ var (
Status: SuiteStatusRecommended, Status: SuiteStatusRecommended,
}) })
// currently recommended suites // Currently Recommended Suites.
// SuiteKey is a a cipher suite for encryption with a key. // SuiteKey is a a cipher suite for encryption with a key.
SuiteKey = SuiteKeyV1 SuiteKey = SuiteKeyV1

View file

@ -11,6 +11,8 @@ import (
) )
func getSuite(t *testing.T, suiteID string) (suite *Suite) { func getSuite(t *testing.T, suiteID string) (suite *Suite) {
t.Helper()
suite, ok := GetSuite(suiteID) suite, ok := GetSuite(suiteID)
if !ok { if !ok {
t.Fatalf("suite %s does not exist", suiteID) 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) { func TestSuites(t *testing.T) {
t.Parallel()
for _, suite := range Suites() { for _, suite := range Suites() {
err := suiteBullshitCheck(suite) err := suiteBullshitCheck(suite)
@ -120,9 +124,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo
// tool check loop: start // tool check loop: start
for i, toolID := range suite.Tools { for i, toolID := range suite.Tools {
//////////////////////////////////////// // =====================================
// tool check loop: check for duplicates // tool check loop: check for duplicates
//////////////////////////////////////// // =====================================
for j, dupeToolID := range suite.Tools { for j, dupeToolID := range suite.Tools {
if i != j && toolID == dupeToolID { if i != j && toolID == dupeToolID {
@ -130,9 +134,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo
} }
} }
/////////////////////////////////////// // ====================================
// tool check loop: parse, prep and get // tool check loop: parse, prep and get
/////////////////////////////////////// // ====================================
var ( var (
hashTool *hashtools.HashTool hashTool *hashtools.HashTool
@ -160,9 +164,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo
s.toolsWithState = append(s.toolsWithState, logic) s.toolsWithState = append(s.toolsWithState, logic)
} }
/////////////////////////////////////////////////////////////// // ============================================================
// tool check loop: assign tools to queues and add requirements // tool check loop: assign tools to queues and add requirements
/////////////////////////////////////////////////////////////// // ============================================================
switch tool.Info.Purpose { switch tool.Info.Purpose {
case tools.PurposeKeyDerivation: case tools.PurposeKeyDerivation:
@ -205,9 +209,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo
s.toolRequirements.Add(Integrity) s.toolRequirements.Add(Integrity)
} }
//////////////////////////////////////////////// // =============================================
// tool check loop: process options, get hashers // tool check loop: process options, get hashers
//////////////////////////////////////////////// // =============================================
for _, option := range tool.Info.Options { for _, option := range tool.Info.Options {
switch option { switch option {
@ -259,9 +263,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo
} }
} }
/////////////////////////////////// // ================================
// tool check loop: initialize tool // tool check loop: initialize tool
/////////////////////////////////// // ================================
// init tool // init tool
logic.Init( logic.Init(
@ -274,9 +278,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo
hashSumFn, hashSumFn,
) )
////////////////////////////////////////////////// // ===============================================
// tool check loop: calc and check security levels // tool check loop: calc and check security levels
////////////////////////////////////////////////// // ===============================================
err = s.calcAndCheckSecurityLevel(logic, nil) err = s.calcAndCheckSecurityLevel(logic, nil)
if err != nil { if err != nil {
@ -285,9 +289,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo
} // tool check loop: end } // tool check loop: end
/////////////// // ============
// final checks // final checks
/////////////// // ============
// check requirements requirements // check requirements requirements
if s.toolRequirements.Empty() { 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") return errors.New("key derivation tool specified, but not needed")
} }
///////////////////////////////////////// // ======================================
// check if values match suite definition // check if values match suite definition
///////////////////////////////////////// // ======================================
// check if security level matches // check if security level matches
if s.SecurityLevel != suite.SecurityLevel { if s.SecurityLevel != suite.SecurityLevel {
@ -337,9 +341,9 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo
) )
} }
/////////////////////////////////////////////////////////// // ========================================================
// check if computeSuiteAttributes returns the same results // check if computeSuiteAttributes returns the same results
/////////////////////////////////////////////////////////// // ========================================================
computedSuite := computeSuiteAttributes(suite.Tools, assumeKey) computedSuite := computeSuiteAttributes(suite.Tools, assumeKey)
if computedSuite == nil { if computedSuite == nil {
@ -360,23 +364,23 @@ func suiteBullshitCheck(suite *Suite) error { //nolint:gocognit,gocyclo
} }
func computeSuiteAttributes(toolIDs []string, assumeKey bool) *Suite { func computeSuiteAttributes(toolIDs []string, assumeKey bool) *Suite {
new := &Suite{ newSuite := &Suite{
Provides: newEmptyRequirements(), Provides: newEmptyRequirements(),
SecurityLevel: 0, SecurityLevel: 0,
} }
// if we have a key // if we have a key
if assumeKey { if assumeKey {
new.Provides.Add(SenderAuthentication) newSuite.Provides.Add(SenderAuthentication)
new.Provides.Add(RecipientAuthentication) newSuite.Provides.Add(RecipientAuthentication)
} }
// check all security levels and collect attributes // check all security levels and collect attributes
for _, toolID := range toolIDs { for _, toolID := range toolIDs {
/////////////////////////////////////// // ====================================
// tool check loop: parse, prep and get // tool check loop: parse, prep and get
/////////////////////////////////////// // ====================================
var hashTool *hashtools.HashTool 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 // create logic instance and add to logic and state lists
logic := tool.Factory() logic := tool.Factory()
////////////////////////////////////// // ===================================
// tool check loop: collect attributes // tool check loop: collect attributes
////////////////////////////////////// // ===================================
switch tool.Info.Purpose { switch tool.Info.Purpose {
case tools.PurposePassDerivation: case tools.PurposePassDerivation:
new.Provides.Add(SenderAuthentication) newSuite.Provides.Add(SenderAuthentication)
new.Provides.Add(RecipientAuthentication) newSuite.Provides.Add(RecipientAuthentication)
case tools.PurposeKeyExchange: case tools.PurposeKeyExchange:
new.Provides.Add(RecipientAuthentication) newSuite.Provides.Add(RecipientAuthentication)
case tools.PurposeKeyEncapsulation: case tools.PurposeKeyEncapsulation:
new.Provides.Add(RecipientAuthentication) newSuite.Provides.Add(RecipientAuthentication)
case tools.PurposeSigning: case tools.PurposeSigning:
new.Provides.Add(SenderAuthentication) newSuite.Provides.Add(SenderAuthentication)
case tools.PurposeIntegratedCipher: case tools.PurposeIntegratedCipher:
new.Provides.Add(Confidentiality) newSuite.Provides.Add(Confidentiality)
new.Provides.Add(Integrity) newSuite.Provides.Add(Integrity)
case tools.PurposeCipher: case tools.PurposeCipher:
new.Provides.Add(Confidentiality) newSuite.Provides.Add(Confidentiality)
case tools.PurposeMAC: case tools.PurposeMAC:
new.Provides.Add(Integrity) newSuite.Provides.Add(Integrity)
} }
//////////////////////////////////////////////// // =============================================
// tool check loop: process options, get hashers // tool check loop: process options, get hashers
//////////////////////////////////////////////// // =============================================
for _, option := range tool.Info.Options { for _, option := range tool.Info.Options {
switch option { switch option {
@ -441,9 +445,9 @@ func computeSuiteAttributes(toolIDs []string, assumeKey bool) *Suite {
} }
} }
/////////////////////////////////// // ================================
// tool check loop: initialize tool // tool check loop: initialize tool
/////////////////////////////////// // ================================
// init tool // init tool
logic.Init( logic.Init(
@ -455,19 +459,19 @@ func computeSuiteAttributes(toolIDs []string, assumeKey bool) *Suite {
nil, nil,
) )
////////////////////////////////////////// // =======================================
// tool check loop: compute security level // tool check loop: compute security level
////////////////////////////////////////// // =======================================
toolSecurityLevel, err := logic.SecurityLevel(nil) toolSecurityLevel, err := logic.SecurityLevel(nil)
if err != nil { if err != nil {
return nil return nil
} }
if new.SecurityLevel == 0 || toolSecurityLevel < new.SecurityLevel { if newSuite.SecurityLevel == 0 || toolSecurityLevel < newSuite.SecurityLevel {
new.SecurityLevel = toolSecurityLevel newSuite.SecurityLevel = toolSecurityLevel
} }
} }
return new return newSuite
} }

View file

@ -5,7 +5,6 @@ import (
"sync" "sync"
"github.com/safing/jess" "github.com/safing/jess"
"github.com/safing/jess/tools" "github.com/safing/jess/tools"
) )

View file

@ -7,6 +7,8 @@ import (
) )
func TestSupply(t *testing.T) { func TestSupply(t *testing.T) {
t.Parallel()
total := 10 total := 10
supply := NewSignetSupply(total) supply := NewSignetSupply(total)
scheme := "ECDH-X25519" scheme := "ECDH-X25519"

View file

@ -3,7 +3,7 @@ package jess
import ( import (
"github.com/safing/jess/tools" "github.com/safing/jess/tools"
// import all tools // Import all tools.
_ "github.com/safing/jess/tools/all" _ "github.com/safing/jess/tools/all"
) )

View file

@ -1,7 +1,10 @@
// Package all imports all tool subpackages
//
//nolint:gci
package all package all
import ( import (
// Import all tool subpackages // Import all tool subpackages.
_ "github.com/safing/jess/tools/ecdh" _ "github.com/safing/jess/tools/ecdh"
_ "github.com/safing/jess/tools/gostdlib" _ "github.com/safing/jess/tools/gostdlib"
) )

View file

@ -3,12 +3,13 @@ package ecdh
import ( import (
"crypto" "crypto"
"crypto/elliptic" "crypto/elliptic"
"fmt"
"math/big" "math/big"
"github.com/aead/ecdh"
"github.com/safing/jess/tools" "github.com/safing/jess/tools"
"github.com/safing/portbase/container" "github.com/safing/portbase/container"
"github.com/aead/ecdh"
) )
var nistCurveInfo = &tools.ToolInfo{ var nistCurveInfo = &tools.ToolInfo{
@ -115,7 +116,10 @@ func (ec *NistCurve) StoreKey(signet tools.SignetInt) error {
c.AppendNumber(1) c.AppendNumber(1)
// store public key // 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.X.Bytes())
c.AppendAsBlock(curvePoint.Y.Bytes()) c.AppendAsBlock(curvePoint.Y.Bytes())

View file

@ -2,11 +2,12 @@ package ecdh
import ( import (
"crypto" "crypto"
"fmt"
"github.com/aead/ecdh"
"github.com/safing/jess/tools" "github.com/safing/jess/tools"
"github.com/safing/portbase/container" "github.com/safing/portbase/container"
"github.com/aead/ecdh"
) )
func init() { func init() {
@ -87,10 +88,16 @@ func (ec *X25519Curve) StoreKey(signet tools.SignetInt) error {
c.AppendNumber(1) c.AppendNumber(1)
// store keys // 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[:]) c.Append(pubKeyData[:])
if !public { 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[:]) c.Append(privKeyData[:])
} }

View file

@ -3,9 +3,9 @@ package gostdlib
import ( import (
"crypto/cipher" "crypto/cipher"
"github.com/safing/jess/tools"
"golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/chacha20poly1305"
"github.com/safing/jess/tools"
) )
func init() { func init() {

View file

@ -5,10 +5,10 @@ import (
"fmt" "fmt"
"io" "io"
"golang.org/x/crypto/hkdf"
"github.com/safing/jess/tools" "github.com/safing/jess/tools"
"github.com/safing/portbase/container" "github.com/safing/portbase/container"
"golang.org/x/crypto/hkdf"
) )
func init() { func init() {
@ -56,12 +56,12 @@ func (keyder *HKDF) DeriveKey(size int) ([]byte, error) {
} }
// DeriveKeyWriteTo implements the ToolLogic interface. // DeriveKeyWriteTo implements the ToolLogic interface.
func (keyder *HKDF) DeriveKeyWriteTo(new []byte) error { func (keyder *HKDF) DeriveKeyWriteTo(newKey []byte) error {
n, err := io.ReadFull(keyder.reader, new) n, err := io.ReadFull(keyder.reader, newKey)
if err != nil { 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 errors.New("failed to generate key: EOF")
} }
return nil return nil

View file

@ -4,9 +4,9 @@ import (
"crypto/sha256" "crypto/sha256"
"hash" "hash"
"github.com/safing/jess/tools"
"golang.org/x/crypto/pbkdf2" "golang.org/x/crypto/pbkdf2"
"github.com/safing/jess/tools"
) )
func init() { func init() {

View file

@ -3,8 +3,9 @@ package gostdlib
import ( import (
"errors" "errors"
"golang.org/x/crypto/poly1305" //nolint:staticcheck,gci
"github.com/safing/jess/tools" "github.com/safing/jess/tools"
"golang.org/x/crypto/poly1305"
) )
func init() { func init() {

View file

@ -8,7 +8,6 @@ import (
"math/big" "math/big"
"github.com/safing/jess/tools" "github.com/safing/jess/tools"
"github.com/safing/portbase/container" "github.com/safing/portbase/container"
) )
@ -163,7 +162,7 @@ func (base *rsaBase) SecurityLevel(signet tools.SignetInt) (int, error) {
if pubkey == nil { if pubkey == nil {
err := signet.LoadKey() err := signet.LoadKey()
if err != nil { 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() pubkey = signet.PublicKey()
} }

View file

@ -1,9 +1,9 @@
package gostdlib package gostdlib
import ( import (
"github.com/safing/jess/tools"
"golang.org/x/crypto/salsa20" "golang.org/x/crypto/salsa20"
"github.com/safing/jess/tools"
) )
func init() { func init() {

View file

@ -41,7 +41,7 @@ type SignetInt interface {
GetStoredKey() (key []byte, public bool) GetStoredKey() (key []byte, public bool)
// SetStoredKey sets a new stored key and whether it is public. // 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 returns the public key.
PublicKey() crypto.PublicKey PublicKey() crypto.PublicKey

View file

@ -32,7 +32,7 @@ type ToolInfo struct {
// Tool Purposes. // Tool Purposes.
const ( const (
// Key Management and Creation, as well as Authenticity // Key Management and Creation, as well as Authenticity.
// PurposeKeyDerivation declares key derivation capabilities. // PurposeKeyDerivation declares key derivation capabilities.
PurposeKeyDerivation uint8 = iota + 1 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. // 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 PurposeSigning
// Confidentiality and Integrity // Confidentiality and Integrity.
// PurposeIntegratedCipher declares that the tool provides both encryption and integrity verification capabilities. // PurposeIntegratedCipher declares that the tool provides both encryption and integrity verification capabilities.
// Provies Confidentiality and Integrity requirements. // Provies Confidentiality and Integrity requirements.
@ -73,13 +73,13 @@ const (
// Tool Options. // Tool Options.
const ( 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. // 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. // TODO: Implementation pending.
OptionStreaming uint8 = iota + 1 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 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 OptionNeedsManagedHasher

View file

@ -51,7 +51,7 @@ type ToolLogic interface {
// DeriveKeyWriteTo derives a new key and writes it into the given slice. // DeriveKeyWriteTo derives a new key and writes it into the given slice.
// Must be overridden by tools that declare FeatureKeyDerivation. // Must be overridden by tools that declare FeatureKeyDerivation.
DeriveKeyWriteTo(new []byte) error DeriveKeyWriteTo(newKey []byte) error
// Key Exchanging // Key Exchanging
@ -221,7 +221,7 @@ func (tlb *ToolLogicBase) DeriveKey(size int) ([]byte, error) {
} }
// DeriveKeyWriteTo implements the ToolLogic interface. // DeriveKeyWriteTo implements the ToolLogic interface.
func (tlb *ToolLogicBase) DeriveKeyWriteTo(new []byte) error { func (tlb *ToolLogicBase) DeriveKeyWriteTo(newKey []byte) error {
return ErrNotImplemented return ErrNotImplemented
} }

View file

@ -7,14 +7,13 @@ import (
"time" "time"
"github.com/safing/jess/hashtools" "github.com/safing/jess/hashtools"
"github.com/safing/jess/tools" "github.com/safing/jess/tools"
// import all tools for testing
_ "github.com/safing/jess/tools/all" _ "github.com/safing/jess/tools/all"
) )
func TestConformity(t *testing.T) { 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. // 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() { 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 // skip in short tests and when not running comprehensive
if testing.Short() || !runComprehensiveTestsActive { if testing.Short() || !runComprehensiveTestsActive {
return return
@ -63,6 +62,8 @@ func TestPasswordHashingSpeed(t *testing.T) {
//nolint:gocognit,gocyclo //nolint:gocognit,gocyclo
func TestSignetHandling(t *testing.T) { func TestSignetHandling(t *testing.T) {
t.Parallel()
hashTool, err := hashtools.Get("SHA2-256") hashTool, err := hashtools.Get("SHA2-256")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View file

@ -115,7 +115,7 @@ func (dts *DirTrustStore) SelectSignets(filter uint8, schemes ...string) ([]*jes
ID: strings.Split(filepath.Base(path), ".")[0], ID: strings.Split(filepath.Base(path), ".")[0],
Public: strings.HasSuffix(path, recipientSuffix), Public: strings.HasSuffix(path, recipientSuffix),
}) })
return nil return err
} }
// check signet scheme // check signet scheme
@ -139,7 +139,7 @@ func (dts *DirTrustStore) SelectSignets(filter uint8, schemes ...string) ([]*jes
return nil return nil
}) })
if err != 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 return selection, nil
@ -226,14 +226,14 @@ func (dts *DirTrustStore) AllEnvelopes() ([]*jess.Envelope, error) {
Name: fmt.Sprintf("%s [failed to load]", Name: fmt.Sprintf("%s [failed to load]",
strings.TrimSuffix(filepath.Base(path), envelopeSuffix)), strings.TrimSuffix(filepath.Base(path), envelopeSuffix)),
}) })
return nil return err
} }
all = append(all, envelope) all = append(all, envelope)
return nil return nil
}) })
if err != 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 return all, nil
@ -247,9 +247,9 @@ func NewDirTrustStore(storageDir string) (*DirTrustStore, error) {
info, err := os.Stat(cleanedPath) info, err := os.Stat(cleanedPath)
if err != nil { if err != nil {
if os.IsNotExist(err) { 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() { if !info.IsDir() {
return nil, errors.New("truststore storage dir is a file, not a directory") return nil, errors.New("truststore storage dir is a file, not a directory")

View file

@ -27,7 +27,7 @@ func WriteSignetToFile(signet *jess.Signet, filename string) error {
} }
// write // write
err = ioutil.WriteFile(filename, data, 0600) err = ioutil.WriteFile(filename, data, 0600) //nolint:gofumpt // gofumpt is ignorant of octal numbers.
if err != nil { if err != nil {
return err return err
} }
@ -72,7 +72,7 @@ func WriteEnvelopeToFile(envelope *jess.Envelope, filename string) error {
} }
// write to storage // 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 { if err != nil {
return err return err
} }