Skip to content

Commit

Permalink
remove logger from client
Browse files Browse the repository at this point in the history
Signed-off-by: Asra Ali <[email protected]>
  • Loading branch information
asraa committed Sep 19, 2022
1 parent 89b085e commit 4780a8c
Show file tree
Hide file tree
Showing 14 changed files with 62 additions and 128 deletions.
27 changes: 4 additions & 23 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"encoding/hex"
"encoding/json"
"io"
"log"

"github.com/theupdateframework/go-tuf/data"
"github.com/theupdateframework/go-tuf/util"
Expand Down Expand Up @@ -89,10 +88,6 @@ type Client struct {
// consistent snapshots (as specified in root.json)
consistentSnapshot bool

// this is an optional log writer.
// if nil, uses io.Discard
logger *log.Logger

// MaxDelegations limits by default the number of delegations visited for any
// target
MaxDelegations int
Expand All @@ -101,26 +96,13 @@ type Client struct {
MaxRootRotations int
}

type ClientOpts func(c *Client)

func WithLogger(logger *log.Logger) ClientOpts {
return func(c *Client) {
c.logger = logger
}
}

func NewClient(local LocalStore, remote RemoteStore, opts ...ClientOpts) *Client {
client := &Client{
func NewClient(local LocalStore, remote RemoteStore) *Client {
return &Client{
local: local,
remote: remote,
MaxDelegations: defaultMaxDelegations,
MaxRootRotations: defaultMaxRootRotations,
logger: log.New(io.Discard, "", 0),
}
for _, opt := range opts {
opt(client)
}
return client
}

// Init initializes a local repository from root metadata.
Expand Down Expand Up @@ -470,8 +452,7 @@ func (c *Client) loadAndVerifyRootMeta(rootJSON []byte, ignoreExpiredCheck bool)
if err := json.Unmarshal(s.Signed, root); err != nil {
return err
}

ndb := verify.NewDB(verify.WithLogger(c.logger))
ndb := verify.NewDB()
for id, k := range root.Keys {
if err := ndb.AddKey(id, k); err != nil {
return err
Expand Down Expand Up @@ -519,7 +500,7 @@ func (c *Client) verifyRoot(aJSON []byte, bJSON []byte) (*data.Root, error) {
return nil, err
}

ndb := verify.NewDB(verify.WithLogger(c.logger))
ndb := verify.NewDB()
for id, k := range aRoot.Keys {
if err := ndb.AddKey(id, k); err != nil {
return nil, err
Expand Down
3 changes: 1 addition & 2 deletions client/delegations.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ func (c *Client) getTargetFileMeta(target string) (data.TargetFileMeta, error) {
}

if targets.Delegations != nil {
delegationsDB, err := verify.NewDBFromDelegations(targets.Delegations,
verify.WithLogger(c.logger))
delegationsDB, err := verify.NewDBFromDelegations(targets.Delegations)
if err != nil {
return data.TargetFileMeta{}, err
}
Expand Down
2 changes: 0 additions & 2 deletions internal/fsutil/perm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
package fsutil

import (
"fmt"
"os"
"path/filepath"
"testing"
Expand Down Expand Up @@ -59,7 +58,6 @@ func TestEnsureMaxPermissions(t *testing.T) {
assert.NoError(t, err)
err = EnsureMaxPermissions(fi, os.FileMode(0222))
assert.Error(t, err)
fmt.Println(err)

// Check matching due to more restrictive perms on file
err = os.Chmod(p, 0444)
Expand Down
31 changes: 29 additions & 2 deletions local_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -197,18 +198,44 @@ type persistedKeys struct {
Data json.RawMessage `json:"data"`
}

type StoreOpts struct {
Logger *log.Logger
PassFunc util.PassphraseFunc
}

func FileSystemStore(dir string, p util.PassphraseFunc) LocalStore {
return &fileSystemStore{
dir: dir,
passphraseFunc: p,
logger: log.New(io.Discard, "", 0),
signerForKeyID: make(map[string]keys.Signer),
keyIDsForRole: make(map[string][]string),
}
}

func FileSystemStoreWithOpts(dir string, opts ...StoreOpts) LocalStore {
store := &fileSystemStore{
dir: dir,
passphraseFunc: nil,
logger: log.New(io.Discard, "", 0),
signerForKeyID: make(map[string]keys.Signer),
keyIDsForRole: make(map[string][]string),
}
for _, opt := range opts {
if opt.Logger != nil {
store.logger = opt.Logger
}
if opt.PassFunc != nil {
store.passphraseFunc = opt.PassFunc
}
}
return store
}

type fileSystemStore struct {
dir string
passphraseFunc util.PassphraseFunc
logger *log.Logger

signerForKeyID map[string]keys.Signer
keyIDsForRole map[string][]string
Expand Down Expand Up @@ -526,7 +553,7 @@ func (f *fileSystemStore) ChangePassphrase(role string) error {
keys, _, err := f.loadPrivateKeys(role)
if err != nil {
if os.IsNotExist(err) {
fmt.Printf("Failed to change passphrase. Missing keys file for %s role. \n", role)
f.logger.Printf("Failed to change passphrase. Missing keys file for %s role. \n", role)
}
return err
}
Expand All @@ -548,7 +575,7 @@ func (f *fileSystemStore) ChangePassphrase(role string) error {
if err := util.AtomicallyWriteFile(f.keysPath(role), append(data, '\n'), 0600); err != nil {
return err
}
fmt.Printf("Successfully changed passphrase for %s keys file\n", role)
f.logger.Printf("Successfully changed passphrase for %s keys file\n", role)
return nil
}

Expand Down
11 changes: 1 addition & 10 deletions pkg/deprecated/deprecated_repo_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
package deprecated

import (
"bytes"
"crypto"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"encoding/json"
"log"
"strings"
"testing"

"github.com/secure-systems-lab/go-securesystemslib/cjson"
Expand Down Expand Up @@ -37,10 +34,7 @@ func genKey(c *C, r *repo.Repo, role string) []string {
func (rs *RepoSuite) TestDeprecatedHexEncodedKeysSucceed(c *C) {
files := map[string][]byte{"foo.txt": []byte("foo")}
local := repo.MemoryStore(make(map[string]json.RawMessage), files)
var logBytes bytes.Buffer
opts := repo.WithLogger(log.New(&logBytes, "", 0))

r, err := repo.NewRepoWithOpts(local, opts)
r, err := repo.NewRepo(local)
c.Assert(err, IsNil)

r.Init(false)
Expand Down Expand Up @@ -85,7 +79,4 @@ func (rs *RepoSuite) TestDeprecatedHexEncodedKeysSucceed(c *C) {
c.Assert(r.Snapshot(), IsNil)
c.Assert(r.Timestamp(), IsNil)
c.Assert(r.Commit(), IsNil)

// Check logs.
c.Assert(strings.Contains(logBytes.String(), keys.WarnDeprecatedEcdsaKey), Equals, true)
}
26 changes: 3 additions & 23 deletions pkg/keys/deprecated_ecdsa.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,44 +9,27 @@ import (
"errors"
"fmt"
"io"
"log"

"github.com/theupdateframework/go-tuf/data"
)

var (
WarnDeprecatedEcdsaKey = "tuf: warning using deprecated ecdsa hex-encoded keys"
)

func NewDeprecatedEcdsaVerifier(opts ...VerifierOpts) Verifier {
verifier := &ecdsaVerifierWithDeprecatedSupport{
logger: log.New(io.Discard, "", log.LstdFlags),
}
for _, opt := range opts {
if opt.Logger != nil {
verifier.logger = opt.Logger
}
}
return verifier
func NewDeprecatedEcdsaVerifier() Verifier {
return &ecdsaVerifierWithDeprecatedSupport{}
}

type ecdsaVerifierWithDeprecatedSupport struct {
key *data.PublicKey
// This will switch based on whether this is a PEM-encoded key
// or a deprecated hex-encoded key.
Verifier
// This is used to write the deprecated warning to.
logger *log.Logger
}

func (p *ecdsaVerifierWithDeprecatedSupport) UnmarshalPublicKey(key *data.PublicKey) error {
p.key = key
pemVerifier := &EcdsaVerifier{}
if err := pemVerifier.UnmarshalPublicKey(key); err != nil {
// Try the deprecated hex-encoded verifier
hexVerifier := &deprecatedP256Verifier{
logger: p.logger,
}
hexVerifier := &deprecatedP256Verifier{}
if err := hexVerifier.UnmarshalPublicKey(key); err != nil {
return err
}
Expand All @@ -67,8 +50,6 @@ func (p *ecdsaVerifierWithDeprecatedSupport) UnmarshalPublicKey(key *data.Public
type deprecatedP256Verifier struct {
PublicKey data.HexBytes `json:"public"`
key *data.PublicKey
// This is used to write the deprecated warning to.
logger *log.Logger
}

func (p *deprecatedP256Verifier) Public() string {
Expand Down Expand Up @@ -116,6 +97,5 @@ func (p *deprecatedP256Verifier) UnmarshalPublicKey(key *data.PublicKey) error {
}

p.key = key
p.logger.Print(WarnDeprecatedEcdsaKey)
return nil
}
21 changes: 0 additions & 21 deletions pkg/keys/deprecated_ecdsa_test.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
package keys

import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"encoding/json"
"errors"
"log"
"strings"

"github.com/theupdateframework/go-tuf/data"
. "gopkg.in/check.v1"
Expand Down Expand Up @@ -130,21 +127,3 @@ func (DeprecatedECDSASuite) TestMarshalUnmarshalPublicKey(c *C) {

c.Assert(deprecatedEcdsa.MarshalPublicKey(), DeepEquals, pub)
}

func (DeprecatedECDSASuite) TestLogMessageWriter(c *C) {
signer, err := generatedDeprecatedSigner()
c.Assert(err, IsNil)

pub := signer.PublicData()

var logBytes bytes.Buffer
opts := WithLogger(log.New(&logBytes, "", 0))

deprecatedEcdsa := NewDeprecatedEcdsaVerifier(opts)
err = deprecatedEcdsa.UnmarshalPublicKey(pub)
c.Assert(err, IsNil)
c.Assert(strings.TrimSuffix(logBytes.String(), "\n"), Equals,
WarnDeprecatedEcdsaKey)

c.Assert(deprecatedEcdsa.MarshalPublicKey(), DeepEquals, pub)
}
2 changes: 1 addition & 1 deletion pkg/keys/ecdsa.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func init() {
SignerMap.Store(data.KeyTypeECDSA_SHA2_P256, newEcdsaSigner)
}

func NewEcdsaVerifier(_ ...VerifierOpts) Verifier {
func NewEcdsaVerifier() Verifier {
return &EcdsaVerifier{}
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/keys/ed25519.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func NewEd25519Signer() Signer {
return &ed25519Signer{}
}

func NewEd25519Verifier(_ ...VerifierOpts) Verifier {
func NewEd25519Verifier() Verifier {
return &ed25519Verifier{}
}

Expand Down
13 changes: 2 additions & 11 deletions pkg/keys/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package keys
import (
"errors"
"fmt"
"log"
"sync"

"github.com/theupdateframework/go-tuf/data"
Expand Down Expand Up @@ -58,20 +57,12 @@ type Signer interface {
SignMessage(message []byte) ([]byte, error)
}

type VerifierOpts struct {
Logger *log.Logger
}

func WithLogger(logger *log.Logger) VerifierOpts {
return VerifierOpts{logger}
}

func GetVerifier(key *data.PublicKey, opts ...VerifierOpts) (Verifier, error) {
func GetVerifier(key *data.PublicKey) (Verifier, error) {
st, ok := VerifierMap.Load(key.Type)
if !ok {
return nil, ErrInvalidKey
}
s := st.(func(opts ...VerifierOpts) Verifier)(opts...)
s := st.(func() Verifier)()
if err := s.UnmarshalPublicKey(key); err != nil {
return nil, fmt.Errorf("tuf: error unmarshalling key: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/keys/rsa.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func init() {
SignerMap.Store(data.KeyTypeRSASSA_PSS_SHA256, newRsaSigner)
}

func newRsaVerifier(_ ...VerifierOpts) Verifier {
func newRsaVerifier() Verifier {
return &rsaVerifier{}
}

Expand Down
7 changes: 3 additions & 4 deletions repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func (r *Repo) Init(consistentSnapshot bool) error {
}

func (r *Repo) topLevelKeysDB() (*verify.DB, error) {
db := verify.NewDB(verify.WithLogger(r.logger))
db := verify.NewDB()
root, err := r.root()
if err != nil {
return nil, err
Expand Down Expand Up @@ -975,7 +975,7 @@ func (r *Repo) delegatorDBs(delegateeRole string) ([]*verify.DB, error) {
continue
}

db, err := verify.NewDBFromDelegations(t.Delegations, verify.WithLogger(r.logger))
db, err := verify.NewDBFromDelegations(t.Delegations)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -1024,8 +1024,7 @@ func (r *Repo) targetDelegationForPath(path string, preferredRole string) (*data
}

if targetsMeta.Delegations != nil && len(targetsMeta.Delegations.Roles) > 0 {
db, err := verify.NewDBFromDelegations(targetsMeta.Delegations,
verify.WithLogger(r.logger))
db, err := verify.NewDBFromDelegations(targetsMeta.Delegations)
if err != nil {
return nil, nil, err
}
Expand Down
Loading

0 comments on commit 4780a8c

Please sign in to comment.