From 00799c2b09d4103b604aaaabe7202c3233f2cff8 Mon Sep 17 00:00:00 2001 From: Tibor Vass Date: Thu, 7 Sep 2017 14:49:52 -0700 Subject: [PATCH] Remove `Notary` from Repository constructor functions Also fixes a small bug with SetLegacyVersions. Signed-off-by: Tibor Vass --- client/backwards_compatibility_test.go | 18 ++++-- client/changelist/file_changelist.go | 2 +- client/client.go | 87 ++++++++++++------------- client/client_test.go | 90 ++++++++++++++------------ client/client_update_test.go | 15 +++-- client/delegations.go | 18 +++--- client/errors.go | 1 + client/witness.go | 2 +- cmd/notary/delegations.go | 8 +-- cmd/notary/keys.go | 4 +- cmd/notary/keys_test.go | 8 +-- cmd/notary/repo_factory.go | 2 +- cmd/notary/tuf.go | 2 +- trustmanager/remoteks/client_test.go | 7 +- trustmanager/remoteks/server_test.go | 4 +- trustmanager/yubikey/import.go | 1 + trustpinning/trustpin_test.go | 3 +- tuf/data/roles_test.go | 2 +- 18 files changed, 145 insertions(+), 129 deletions(-) diff --git a/client/backwards_compatibility_test.go b/client/backwards_compatibility_test.go index 3098bda0e1..568641bf12 100644 --- a/client/backwards_compatibility_test.go +++ b/client/backwards_compatibility_test.go @@ -22,7 +22,7 @@ import ( // Once a fixture is read in, ensure that it's valid by making sure the expiry // times of all the metadata and certificates is > 10 years ahead -func requireValidFixture(t *testing.T, notaryRepo *NotaryRepository) { +func requireValidFixture(t *testing.T, notaryRepo *repository) { tenYearsInFuture := time.Now().AddDate(10, 0, 0) require.True(t, notaryRepo.tufRepo.Root.Signed.Expires.After(tenYearsInFuture)) require.True(t, notaryRepo.tufRepo.Snapshot.Signed.Expires.After(tenYearsInFuture)) @@ -90,7 +90,7 @@ func Test0Dot1Migration(t *testing.T) { ts := fullTestServer(t) defer ts.Close() - _, err = NewFileCachedNotaryRepository(tmpDir, gun, ts.URL, http.DefaultTransport, + _, err = NewFileCachedRepository(tmpDir, gun, ts.URL, http.DefaultTransport, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) @@ -138,7 +138,7 @@ func Test0Dot3Migration(t *testing.T) { ts := fullTestServer(t) defer ts.Close() - _, err = NewFileCachedNotaryRepository(tmpDir, gun, ts.URL, http.DefaultTransport, + _, err = NewFileCachedRepository(tmpDir, gun, ts.URL, http.DefaultTransport, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) @@ -197,9 +197,10 @@ func Test0Dot1RepoFormat(t *testing.T) { ts := fullTestServer(t) defer ts.Close() - repo, err := NewFileCachedNotaryRepository(tmpDir, gun, ts.URL, http.DefaultTransport, + r, err := NewFileCachedRepository(tmpDir, gun, ts.URL, http.DefaultTransport, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) + repo := r.(*repository) // targets should have 1 target, and it should be readable offline targets, err := repo.ListTargets() @@ -260,9 +261,10 @@ func Test0Dot3RepoFormat(t *testing.T) { ts := fullTestServer(t) defer ts.Close() - repo, err := NewFileCachedNotaryRepository(tmpDir, gun, ts.URL, http.DefaultTransport, + r, err := NewFileCachedRepository(tmpDir, gun, ts.URL, http.DefaultTransport, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) + repo := r.(*repository) // targets should have 1 target, and it should be readable offline targets, err := repo.ListTargets() @@ -326,9 +328,10 @@ func TestDownloading0Dot1RepoFormat(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(repoDir) - repo, err := NewFileCachedNotaryRepository(repoDir, gun, ts.URL, http.DefaultTransport, + r, err := NewFileCachedRepository(repoDir, gun, ts.URL, http.DefaultTransport, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) + repo := r.(*repository) err = repo.Update(true) require.NoError(t, err, "error updating repo: %s", err) @@ -351,9 +354,10 @@ func TestDownloading0Dot3RepoFormat(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(repoDir) - repo, err := NewFileCachedNotaryRepository(repoDir, gun, ts.URL, http.DefaultTransport, + r, err := NewFileCachedRepository(repoDir, gun, ts.URL, http.DefaultTransport, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) + repo := r.(*repository) err = repo.Update(true) require.NoError(t, err, "error updating repo: %s", err) diff --git a/client/changelist/file_changelist.go b/client/changelist/file_changelist.go index 7e128a194c..343760bb97 100644 --- a/client/changelist/file_changelist.go +++ b/client/changelist/file_changelist.go @@ -5,12 +5,12 @@ import ( "fmt" "io/ioutil" "os" + "path/filepath" "sort" "time" "github.com/Sirupsen/logrus" "github.com/docker/distribution/uuid" - "path/filepath" ) // FileChangelist stores all the changes as files diff --git a/client/client.go b/client/client.go index ca193364a2..63650526ab 100644 --- a/client/client.go +++ b/client/client.go @@ -36,9 +36,8 @@ func init() { data.SetDefaultExpiryTimes(data.NotaryDefaultExpiries) } -// NotaryRepository stores all the information needed to operate on a notary -// repository. -type NotaryRepository struct { +// repository stores all the information needed to operate on a notary repository. +type repository struct { baseDir string gun data.GUN baseURL string @@ -53,15 +52,14 @@ type NotaryRepository struct { LegacyVersions int // number of versions back to fetch roots to sign with } -// NewFileCachedNotaryRepository is a wrapper for NewNotaryRepository that initializes +// NewFileCachedRepository is a wrapper for NewRepository that initializes // a file cache from the provided repository, local config information and a crypto service. // It also retrieves the remote store associated to the base directory under where all the // trust files will be stored and the specified GUN. // // In case of a nil RoundTripper, a default offline store is used instead. -func NewFileCachedNotaryRepository(baseDir string, gun data.GUN, baseURL string, rt http.RoundTripper, - retriever notary.PassRetriever, trustPinning trustpinning.TrustPinConfig) ( - *NotaryRepository, error) { +func NewFileCachedRepository(baseDir string, gun data.GUN, baseURL string, rt http.RoundTripper, + retriever notary.PassRetriever, trustPinning trustpinning.TrustPinConfig) (Repository, error) { cache, err := store.NewFileStore( filepath.Join(baseDir, tufDir, filepath.FromSlash(gun.String()), "metadata"), @@ -91,18 +89,17 @@ func NewFileCachedNotaryRepository(baseDir string, gun data.GUN, baseURL string, return nil, err } - return NewNotaryRepository(baseDir, gun, baseURL, remoteStore, cache, trustPinning, cryptoService, cl) + return NewRepository(baseDir, gun, baseURL, remoteStore, cache, trustPinning, cryptoService, cl) } -// NewNotaryRepository is the base method that returns a new notary repository. +// NewRepository is the base method that returns a new notary repository. // It takes the base directory under where all the trust files will be stored // (This is normally defaults to "~/.notary" or "~/.docker/trust" when enabling // docker content trust). // It expects an initialized cache. In case of a nil remote store, a default // offline store is used. -func NewNotaryRepository(baseDir string, gun data.GUN, baseURL string, remoteStore store.RemoteStore, cache store.MetadataStore, - trustPinning trustpinning.TrustPinConfig, cryptoService signed.CryptoService, cl changelist.Changelist) ( - *NotaryRepository, error) { +func NewRepository(baseDir string, gun data.GUN, baseURL string, remoteStore store.RemoteStore, cache store.MetadataStore, + trustPinning trustpinning.TrustPinConfig, cryptoService signed.CryptoService, cl changelist.Changelist) (Repository, error) { // Repo's remote store is either a valid remote store or an OfflineStore if remoteStore == nil { @@ -113,7 +110,7 @@ func NewNotaryRepository(baseDir string, gun data.GUN, baseURL string, remoteSto return nil, fmt.Errorf("got an invalid cache (nil metadata store)") } - nRepo := &NotaryRepository{ + nRepo := &repository{ gun: gun, baseURL: baseURL, baseDir: baseDir, @@ -128,8 +125,8 @@ func NewNotaryRepository(baseDir string, gun data.GUN, baseURL string, remoteSto return nRepo, nil } -// GetGUN is a getter for the GUN object from a NotaryRepository -func (r *NotaryRepository) GetGUN() data.GUN { +// GetGUN is a getter for the GUN object from a Repository +func (r *repository) GetGUN() data.GUN { return r.gun } @@ -183,12 +180,12 @@ func rootCertKey(gun data.GUN, privKey data.PrivateKey) (data.PublicKey, error) } // GetCryptoService is the getter for the repository's CryptoService -func (r *NotaryRepository) GetCryptoService() signed.CryptoService { +func (r *repository) GetCryptoService() signed.CryptoService { return r.cryptoService } // initialize initializes the notary repository with a set of rootkeys, root certificates and roles. -func (r *NotaryRepository) initialize(rootKeyIDs []string, rootCerts []data.PublicKey, serverManagedRoles ...data.RoleName) error { +func (r *repository) initialize(rootKeyIDs []string, rootCerts []data.PublicKey, serverManagedRoles ...data.RoleName) error { // currently we only support server managing timestamps and snapshots, and // nothing else - timestamps are always managed by the server, and implicit @@ -266,7 +263,7 @@ func (r *NotaryRepository) initialize(rootKeyIDs []string, rootCerts []data.Publ // createNewPublicKeyFromKeyIDs generates a set of public keys corresponding to the given list of // key IDs existing in the repository's CryptoService. // the public keys returned are ordered to correspond to the keyIDs -func (r *NotaryRepository) createNewPublicKeyFromKeyIDs(keyIDs []string) ([]data.PublicKey, error) { +func (r *repository) createNewPublicKeyFromKeyIDs(keyIDs []string) ([]data.PublicKey, error) { publicKeys := []data.PublicKey{} privKeys, err := getAllPrivKeys(keyIDs, r.GetCryptoService()) @@ -287,7 +284,7 @@ func (r *NotaryRepository) createNewPublicKeyFromKeyIDs(keyIDs []string) ([]data // publicKeysOfKeyIDs confirms that the public key and private keys (by Key IDs) forms valid, strictly ordered key pairs // (eg. keyIDs[0] must match pubKeys[0] and keyIDs[1] must match certs[1] and so on). // Or throw error when they mismatch. -func (r *NotaryRepository) publicKeysOfKeyIDs(keyIDs []string, pubKeys []data.PublicKey) ([]data.PublicKey, error) { +func (r *repository) publicKeysOfKeyIDs(keyIDs []string, pubKeys []data.PublicKey) ([]data.PublicKey, error) { if len(keyIDs) != len(pubKeys) { err := fmt.Errorf("require matching number of keyIDs and public keys but got %d IDs and %d public keys", len(keyIDs), len(pubKeys)) return nil, err @@ -301,7 +298,7 @@ func (r *NotaryRepository) publicKeysOfKeyIDs(keyIDs []string, pubKeys []data.Pu // matchKeyIdsWithPubKeys validates that the private keys (represented by their IDs) and the public keys // forms matching key pairs -func matchKeyIdsWithPubKeys(r *NotaryRepository, ids []string, pubKeys []data.PublicKey) error { +func matchKeyIdsWithPubKeys(r *repository, ids []string, pubKeys []data.PublicKey) error { for i := 0; i < len(ids); i++ { privKey, _, err := r.GetCryptoService().GetPrivateKey(ids[i]) if err != nil { @@ -322,7 +319,7 @@ func matchKeyIdsWithPubKeys(r *NotaryRepository, ids []string, pubKeys []data.Pu // timestamp key and possibly other serverManagedRoles), but the created repository // result is only stored on local disk, not published to the server. To do that, // use r.Publish() eventually. -func (r *NotaryRepository) Initialize(rootKeyIDs []string, serverManagedRoles ...data.RoleName) error { +func (r *repository) Initialize(rootKeyIDs []string, serverManagedRoles ...data.RoleName) error { return r.initialize(rootKeyIDs, nil, serverManagedRoles...) } @@ -346,7 +343,7 @@ func keyExistsInList(cert data.PublicKey, ids map[string]bool) error { } // InitializeWithCertificate initializes the repository with root keys and their corresponding certificates -func (r *NotaryRepository) InitializeWithCertificate(rootKeyIDs []string, rootCerts []data.PublicKey, +func (r *repository) InitializeWithCertificate(rootKeyIDs []string, rootCerts []data.PublicKey, serverManagedRoles ...data.RoleName) error { // If we explicitly pass in certificate(s) but not key, then look keys up using certificate @@ -368,7 +365,7 @@ func (r *NotaryRepository) InitializeWithCertificate(rootKeyIDs []string, rootCe return r.initialize(rootKeyIDs, rootCerts, serverManagedRoles...) } -func (r *NotaryRepository) initializeRoles(rootKeys []data.PublicKey, localRoles, remoteRoles []data.RoleName) ( +func (r *repository) initializeRoles(rootKeys []data.PublicKey, localRoles, remoteRoles []data.RoleName) ( root, targets, snapshot, timestamp data.BaseRole, err error) { root = data.NewBaseRole( data.CanonicalRootRole, @@ -467,7 +464,7 @@ func addChange(cl changelist.Changelist, c changelist.Change, roles ...data.Role // AddTarget creates new changelist entries to add a target to the given roles // in the repository when the changelist gets applied at publish time. // If roles are unspecified, the default role is "targets" -func (r *NotaryRepository) AddTarget(target *Target, roles ...data.RoleName) error { +func (r *repository) AddTarget(target *Target, roles ...data.RoleName) error { if len(target.Hashes) == 0 { return fmt.Errorf("no hashes specified for target \"%s\"", target.Name) } @@ -488,7 +485,7 @@ func (r *NotaryRepository) AddTarget(target *Target, roles ...data.RoleName) err // RemoveTarget creates new changelist entries to remove a target from the given // roles in the repository when the changelist gets applied at publish time. // If roles are unspecified, the default role is "target". -func (r *NotaryRepository) RemoveTarget(targetName string, roles ...data.RoleName) error { +func (r *repository) RemoveTarget(targetName string, roles ...data.RoleName) error { logrus.Debugf("Removing target \"%s\"", targetName) template := changelist.NewTUFChange(changelist.ActionDelete, "", changelist.TypeTargetsTarget, targetName, nil) @@ -503,7 +500,7 @@ func (r *NotaryRepository) RemoveTarget(targetName string, roles ...data.RoleNam // its entries will be strictly shadowed by those in other parts of the "targets/a" // subtree and also the "targets/x" subtree, as we will defer parsing it until // we explicitly reach it in our iteration of the provided list of roles. -func (r *NotaryRepository) ListTargets(roles ...data.RoleName) ([]*TargetWithRole, error) { +func (r *repository) ListTargets(roles ...data.RoleName) ([]*TargetWithRole, error) { if err := r.Update(false); err != nil { return nil, err } @@ -556,7 +553,7 @@ func (r *NotaryRepository) ListTargets(roles ...data.RoleName) ([]*TargetWithRol // the target entry found in the subtree of the highest priority role // will be returned. // See the IMPORTANT section on ListTargets above. Those roles also apply here. -func (r *NotaryRepository) GetTargetByName(name string, roles ...data.RoleName) (*TargetWithRole, error) { +func (r *repository) GetTargetByName(name string, roles ...data.RoleName) (*TargetWithRole, error) { if err := r.Update(false); err != nil { return nil, err } @@ -610,7 +607,7 @@ func (f ErrNoSuchTarget) Error() string { // GetAllTargetMetadataByName searches the entire delegation role tree to find the specified target by name for all // roles, and returns a list of TargetSignedStructs for each time it finds the specified target. // If given an empty string for a target name, it will return back all targets signed into the repository in every role -func (r *NotaryRepository) GetAllTargetMetadataByName(name string) ([]TargetSignedStruct, error) { +func (r *repository) GetAllTargetMetadataByName(name string) ([]TargetSignedStruct, error) { if err := r.Update(false); err != nil { return nil, err } @@ -657,13 +654,13 @@ func (r *NotaryRepository) GetAllTargetMetadataByName(name string) ([]TargetSign } // GetChangelist returns the list of the repository's unpublished changes -func (r *NotaryRepository) GetChangelist() (changelist.Changelist, error) { +func (r *repository) GetChangelist() (changelist.Changelist, error) { return r.changelist, nil } // getRemoteStore returns the remoteStore of a repository if valid or // or an OfflineStore otherwise -func (r *NotaryRepository) getRemoteStore() store.RemoteStore { +func (r *repository) getRemoteStore() store.RemoteStore { if r.remoteStore != nil { return r.remoteStore } @@ -681,7 +678,7 @@ type RoleWithSignatures struct { // ListRoles returns a list of RoleWithSignatures objects for this repo // This represents the latest metadata for each role in this repo -func (r *NotaryRepository) ListRoles() ([]RoleWithSignatures, error) { +func (r *repository) ListRoles() ([]RoleWithSignatures, error) { // Update to latest repo state if err := r.Update(false); err != nil { return nil, err @@ -720,7 +717,7 @@ func (r *NotaryRepository) ListRoles() ([]RoleWithSignatures, error) { // Publish pushes the local changes in signed material to the remote notary-server // Conceptually it performs an operation similar to a `git rebase` -func (r *NotaryRepository) Publish() error { +func (r *repository) Publish() error { if err := r.publish(r.changelist); err != nil { return err } @@ -735,7 +732,7 @@ func (r *NotaryRepository) Publish() error { // publish pushes the changes in the given changelist to the remote notary-server // Conceptually it performs an operation similar to a `git rebase` -func (r *NotaryRepository) publish(cl changelist.Changelist) error { +func (r *repository) publish(cl changelist.Changelist) error { var initialPublish bool // update first before publishing if err := r.Update(true); err != nil { @@ -842,7 +839,7 @@ func signRootIfNecessary(updates map[data.RoleName][]byte, repo *tuf.Repo, extra // Fetch back a `legacyVersions` number of roots files, collect the root public keys // This includes old `root` roles as well as legacy versioned root roles, e.g. `1.root` -func (r *NotaryRepository) oldKeysForLegacyClientSupport(legacyVersions int, initialPublish bool) (data.KeyList, error) { +func (r *repository) oldKeysForLegacyClientSupport(legacyVersions int, initialPublish bool) (data.KeyList, error) { if initialPublish { return nil, nil } @@ -932,7 +929,7 @@ func signTargets(updates map[data.RoleName][]byte, repo *tuf.Repo, initialPublis // r.tufRepo. This attempts to load metadata for all roles. Since server // snapshots are supported, if the snapshot metadata fails to load, that's ok. // This assumes that bootstrapRepo is only used by Publish() or RotateKey() -func (r *NotaryRepository) bootstrapRepo() error { +func (r *repository) bootstrapRepo() error { b := tuf.NewRepoBuilder(r.gun, r.GetCryptoService(), r.trustPinning) logrus.Debugf("Loading trusted collection.") @@ -963,7 +960,7 @@ func (r *NotaryRepository) bootstrapRepo() error { // saveMetadata saves contents of r.tufRepo onto the local disk, creating // signatures as necessary, possibly prompting for passphrases. -func (r *NotaryRepository) saveMetadata(ignoreSnapshot bool) error { +func (r *repository) saveMetadata(ignoreSnapshot bool) error { logrus.Debugf("Saving changes to Trusted Collection.") rootJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalRootRole, nil) @@ -1007,7 +1004,7 @@ func (r *NotaryRepository) saveMetadata(ignoreSnapshot bool) error { // returns a properly constructed ErrRepositoryNotExist error based on this // repo's information -func (r *NotaryRepository) errRepositoryNotExist() error { +func (r *repository) errRepositoryNotExist() error { host := r.baseURL parsed, err := url.Parse(r.baseURL) if err == nil { @@ -1018,7 +1015,7 @@ func (r *NotaryRepository) errRepositoryNotExist() error { // Update bootstraps a trust anchor (root.json) before updating all the // metadata from the repo. -func (r *NotaryRepository) Update(forWrite bool) error { +func (r *repository) Update(forWrite bool) error { c, err := r.bootstrapClient(forWrite) if err != nil { if _, ok := err.(store.ErrMetaNotFound); ok { @@ -1064,7 +1061,7 @@ func (r *NotaryRepository) Update(forWrite bool) error { // // Returns a TUFClient for the remote server, which may not be actually // operational (if the URL is invalid but a root.json is cached). -func (r *NotaryRepository) bootstrapClient(checkInitialized bool) (*tufClient, error) { +func (r *repository) bootstrapClient(checkInitialized bool) (*tufClient, error) { minVersion := 1 // the old root on disk should not be validated against any trust pinning configuration // because if we have an old root, it itself is the thing that pins trust @@ -1139,7 +1136,7 @@ func (r *NotaryRepository) bootstrapClient(checkInitialized bool) (*tufClient, e // managing the key to the server. If key(s) are specified by keyList, then they are // used for signing the role. // These changes are staged in a changelist until publish is called. -func (r *NotaryRepository) RotateKey(role data.RoleName, serverManagesKey bool, keyList []string) error { +func (r *repository) RotateKey(role data.RoleName, serverManagesKey bool, keyList []string) error { if err := checkRotationInput(role, serverManagesKey); err != nil { return err } @@ -1157,7 +1154,7 @@ func (r *NotaryRepository) RotateKey(role data.RoleName, serverManagesKey bool, } // Given a set of new keys to rotate to and a set of keys to drop, returns the list of current keys to use -func (r *NotaryRepository) pubKeyListForRotation(role data.RoleName, serverManaged bool, newKeys []string) (pubKeyList data.KeyList, err error) { +func (r *repository) pubKeyListForRotation(role data.RoleName, serverManaged bool, newKeys []string) (pubKeyList data.KeyList, err error) { var pubKey data.PublicKey // If server manages the key being rotated, request a rotation and return the new key @@ -1202,7 +1199,7 @@ func (r *NotaryRepository) pubKeyListForRotation(role data.RoleName, serverManag return pubKeyList, nil } -func (r *NotaryRepository) pubKeysToCerts(role data.RoleName, pubKeyList data.KeyList) (data.KeyList, error) { +func (r *repository) pubKeysToCerts(role data.RoleName, pubKeyList data.KeyList) (data.KeyList, error) { // only generate certs for root keys if role != data.CanonicalRootRole { return pubKeyList, nil @@ -1243,7 +1240,7 @@ func checkRotationInput(role data.RoleName, serverManaged bool) error { return nil } -func (r *NotaryRepository) rootFileKeyChange(cl changelist.Changelist, role data.RoleName, action string, keyList []data.PublicKey) error { +func (r *repository) rootFileKeyChange(cl changelist.Changelist, role data.RoleName, action string, keyList []data.PublicKey) error { meta := changelist.TUFRootData{ RoleName: role, Keys: keyList, @@ -1271,7 +1268,7 @@ func DeleteTrustData(baseDir string, gun data.GUN, URL string, rt http.RoundTrip if err := os.RemoveAll(localRepo); err != nil { return fmt.Errorf("error clearing TUF repo data: %v", err) } - // Note that this will require admin permission in this NotaryRepository's roundtripper + // Note that this will require admin permission for the gun in the roundtripper if deleteRemote { remote, err := getRemoteStore(URL, gun, rt) if err != nil { @@ -1287,6 +1284,6 @@ func DeleteTrustData(baseDir string, gun data.GUN, URL string, rt http.RoundTrip // SetLegacyVersions allows the number of legacy versions of the root // to be inspected for old signing keys to be configured. -func (r NotaryRepository) SetLegacyVersions(n int) { +func (r *repository) SetLegacyVersions(n int) { r.LegacyVersions = n } diff --git a/client/client_test.go b/client/client_test.go index e18c7daf6c..65fe4a830d 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -156,7 +156,7 @@ func errorTestServer(t *testing.T, errorCode int) *httptest.Server { // initializes a repository in a temporary directory func initializeRepo(t *testing.T, rootType, gun, url string, - serverManagesSnapshot bool) (*NotaryRepository, string) { + serverManagesSnapshot bool) (*repository, string) { // Temporary directory where test files will be created tempBaseDir, err := ioutil.TempDir("", "notary-test-") @@ -188,12 +188,13 @@ func initializeRepo(t *testing.T, rootType, gun, url string, } // Creates a new repository and adds a root key. Returns the repo and key ID. -func createRepoAndKey(t *testing.T, rootType, tempBaseDir, gun, url string) (*NotaryRepository, *passRoleRecorder, string) { +func createRepoAndKey(t *testing.T, rootType, tempBaseDir, gun, url string) (*repository, *passRoleRecorder, string) { rec := newRoleRecorder() - repo, err := NewFileCachedNotaryRepository( + r, err := NewFileCachedRepository( tempBaseDir, data.GUN(gun), url, http.DefaultTransport, rec.retriever, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) + repo := r.(*repository) rootPubKey, err := testutils.CreateOrAddKey(repo.GetCryptoService(), data.CanonicalRootRole, repo.gun, rootType) require.NoError(t, err, "error generating root key: %s", err) @@ -210,8 +211,8 @@ func createRepoAndKey(t *testing.T, rootType, tempBaseDir, gun, url string) (*No // repo, in order to eliminate caches (for instance, cryptoservice cache) // if a new directory is to be created, it also eliminates the TUF metadata // cache -func newRepoToTestRepo(t *testing.T, existingRepo *NotaryRepository, newDir bool) ( - *NotaryRepository, *passRoleRecorder) { +func newRepoToTestRepo(t *testing.T, existingRepo *repository, newDir bool) ( + *repository, *passRoleRecorder) { repoDir := existingRepo.baseDir if newDir { @@ -221,10 +222,11 @@ func newRepoToTestRepo(t *testing.T, existingRepo *NotaryRepository, newDir bool } rec := newRoleRecorder() - repo, err := NewFileCachedNotaryRepository( + r, err := NewFileCachedRepository( repoDir, existingRepo.gun, existingRepo.baseURL, http.DefaultTransport, rec.retriever, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repository: %s", err) + repo := r.(*repository) if err != nil && newDir { defer os.RemoveAll(repoDir) } @@ -525,7 +527,7 @@ func TestInitRepoServerManagesTimestampAndSnapshotKeys(t *testing.T) { // This creates a new KeyFileStore in the repo's base directory and makes sure // the repo has the right number of keys -func requireRepoHasExpectedKeys(t *testing.T, repo *NotaryRepository, +func requireRepoHasExpectedKeys(t *testing.T, repo *repository, rootKeyID string, expectedSnapshotKey bool) { // The repo should have a keyFileStore and have created keys using it, @@ -573,7 +575,7 @@ func requireRepoHasExpectedKeys(t *testing.T, repo *NotaryRepository, // role, the JSON is well-formed, and the signatures exist. // For the root.json file, also check that the root, snapshot, and // targets key IDs are present. -func requireRepoHasExpectedMetadata(t *testing.T, repo *NotaryRepository, +func requireRepoHasExpectedMetadata(t *testing.T, repo *repository, role data.RoleName, expected bool) { filename := filepath.Join(tufDir, filepath.FromSlash(repo.gun.String()), @@ -698,8 +700,9 @@ func testInitRepoAttemptsExceeded(t *testing.T, rootType string) { defer ts.Close() retriever := passphrase.ConstantRetriever("password") - repo, err := NewFileCachedNotaryRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, retriever, trustpinning.TrustPinConfig{}) + r, err := NewFileCachedRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, retriever, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) + repo := r.(*repository) rootPubKey, err := testutils.CreateOrAddKey(repo.GetCryptoService(), data.CanonicalRootRole, repo.gun, rootType) require.NoError(t, err, "error generating root key: %s", err) @@ -707,8 +710,9 @@ func testInitRepoAttemptsExceeded(t *testing.T, rootType string) { retriever = passphrase.ConstantRetriever("incorrect password") // repo.GetCryptoService’s FileKeyStore caches the unlocked private key, so to test // private key unlocking we need a new repo instance. - repo, err = NewFileCachedNotaryRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, retriever, trustpinning.TrustPinConfig{}) + r, err = NewFileCachedRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, retriever, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) + repo = r.(*repository) err = repo.Initialize([]string{rootPubKey.ID()}) require.EqualError(t, err, trustmanager.ErrAttemptsExceeded{}.Error()) } @@ -737,27 +741,29 @@ func testInitRepoPasswordInvalid(t *testing.T, rootType string) { defer ts.Close() retriever := passphrase.ConstantRetriever("password") - repo, err := NewFileCachedNotaryRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, retriever, trustpinning.TrustPinConfig{}) + r, err := NewFileCachedRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, retriever, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) + repo := r.(*repository) rootPubKey, err := testutils.CreateOrAddKey(repo.GetCryptoService(), data.CanonicalRootRole, repo.gun, rootType) require.NoError(t, err, "error generating root key: %s", err) // repo.GetCryptoService’s FileKeyStore caches the unlocked private key, so to test // private key unlocking we need a new repo instance. - repo, err = NewFileCachedNotaryRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, giveUpPassphraseRetriever, trustpinning.TrustPinConfig{}) + r, err = NewFileCachedRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, giveUpPassphraseRetriever, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) + repo = r.(*repository) err = repo.Initialize([]string{rootPubKey.ID()}) require.EqualError(t, err, trustmanager.ErrPasswordInvalid{}.Error()) } -func addTarget(t *testing.T, repo *NotaryRepository, targetName, targetFile string, +func addTarget(t *testing.T, repo *repository, targetName, targetFile string, roles ...data.RoleName) *Target { var targetCustom *json.RawMessage return addTargetWithCustom(t, repo, targetName, targetFile, targetCustom, roles...) } -func addTargetWithCustom(t *testing.T, repo *NotaryRepository, targetName, +func addTargetWithCustom(t *testing.T, repo *repository, targetName, targetFile string, targetCustom *json.RawMessage, roles ...data.RoleName) *Target { target, err := NewTarget(targetName, targetFile, targetCustom) require.NoError(t, err, "error creating target") @@ -767,7 +773,7 @@ func addTargetWithCustom(t *testing.T, repo *NotaryRepository, targetName, } // calls GetChangelist and gets the actual changes out -func getChanges(t *testing.T, repo *NotaryRepository) []changelist.Change { +func getChanges(t *testing.T, repo *repository) []changelist.Change { changeList, err := repo.GetChangelist() require.NoError(t, err) return changeList.List() @@ -805,7 +811,7 @@ func testAddTargetToTargetRoleByDefault(t *testing.T, clearCache bool) { // Tests that adding a target to a repo or deleting a target from a repo, // with the given roles, makes a change to the expected scopes -func testAddOrDeleteTarget(t *testing.T, repo *NotaryRepository, action string, +func testAddOrDeleteTarget(t *testing.T, repo *repository, action string, rolesToChange []data.RoleName, expectedScopes []string) { require.Len(t, getChanges(t, repo), 0, "should start with zero changes") @@ -963,7 +969,7 @@ func testAddTargetToSpecifiedInvalidRoles(t *testing.T, clearCache bool) { } // General way to require that errors writing a changefile are propagated up -func testErrorWritingChangefiles(t *testing.T, writeChangeFile func(*NotaryRepository) error) { +func testErrorWritingChangefiles(t *testing.T, writeChangeFile func(*repository) error) { ts, _, _ := simpleTestServer(t) defer ts.Close() gun := "docker.com/notary" @@ -1018,7 +1024,7 @@ func TestAddTargetWithInvalidTarget(t *testing.T) { // TestAddTargetErrorWritingChanges expects errors writing a change to file // to be propagated. func TestAddTargetErrorWritingChanges(t *testing.T) { - testErrorWritingChangefiles(t, func(repo *NotaryRepository) error { + testErrorWritingChangefiles(t, func(repo *repository) error { var targetCustom *json.RawMessage target, err := NewTarget("latest", "../fixtures/intermediate-ca.crt", targetCustom) require.NoError(t, err, "error creating target") @@ -1138,7 +1144,7 @@ func testRemoveTargetToSpecifiedInvalidRoles(t *testing.T, clearCache bool) { // TestRemoveTargetErrorWritingChanges expects errors writing a change to file // to be propagated. func TestRemoveTargetErrorWritingChanges(t *testing.T) { - testErrorWritingChangefiles(t, func(repo *NotaryRepository) error { + testErrorWritingChangefiles(t, func(repo *repository) error { return repo.RemoveTarget("latest", data.CanonicalTargetsRole) }) } @@ -1171,7 +1177,7 @@ func testListEmptyTargets(t *testing.T, rootType string) { // reads data from the repository in order to fake data being served via // the ServeMux. -func fakeServerData(t *testing.T, repo *NotaryRepository, mux *http.ServeMux, +func fakeServerData(t *testing.T, repo *repository, mux *http.ServeMux, keys map[string]data.PrivateKey) { timestampKey, ok := keys[data.CanonicalTimestampRole.String()] @@ -1798,9 +1804,10 @@ func TestPublishUninitializedRepo(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempBaseDir) - repo, err := NewFileCachedNotaryRepository(tempBaseDir, gun, ts.URL, + r, err := NewFileCachedRepository(tempBaseDir, gun, ts.URL, http.DefaultTransport, passphraseRetriever, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repository: %s", err) + repo := r.(*repository) err = repo.Publish() require.NoError(t, err) @@ -1864,7 +1871,7 @@ func testPublishWithData(t *testing.T, rootType string, clearCache, serverManage // requires that adding to the given roles results in the targets actually being // added only to the expected roles and no others -func requirePublishToRolesSucceeds(t *testing.T, repo1 *NotaryRepository, +func requirePublishToRolesSucceeds(t *testing.T, repo1 *repository, publishToRoles []data.RoleName, expectedPublishedRoles []data.RoleName) { // were there unpublished changes before? @@ -1894,7 +1901,7 @@ func requirePublishToRolesSucceeds(t *testing.T, repo1 *NotaryRepository, // Should be two targets per role for _, role := range expectedPublishedRoles { - for _, repo := range []*NotaryRepository{repo1, repo2} { + for _, repo := range []*repository{repo1, repo2} { targets, err := repo.ListTargets(role) require.NoError(t, err) @@ -2072,7 +2079,7 @@ func TestPublishRootCorrupt(t *testing.T) { // When publishing snapshot, root, or target, if the repo hasn't been published // before, if the metadata is corrupt, it can't be published. -func testPublishBadMetadata(t *testing.T, roleName string, repo *NotaryRepository, +func testPublishBadMetadata(t *testing.T, roleName string, repo *repository, publishFirst, succeeds bool) { if publishFirst { @@ -2130,9 +2137,10 @@ func TestPublishSnapshotLocalKeysCreatedFirst(t *testing.T) { func(http.ResponseWriter, *http.Request) { requestMade = true })) defer ts.Close() - repo, err := NewFileCachedNotaryRepository( + r, err := NewFileCachedRepository( tempBaseDir, gun, ts.URL, http.DefaultTransport, passphraseRetriever, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) + repo := r.(*repository) cs := cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever)) @@ -2147,7 +2155,7 @@ func TestPublishSnapshotLocalKeysCreatedFirst(t *testing.T) { require.False(t, requestMade) } -func createKey(t *testing.T, repo *NotaryRepository, role data.RoleName, x509 bool) data.PublicKey { +func createKey(t *testing.T, repo *repository, role data.RoleName, x509 bool) data.PublicKey { key, err := repo.GetCryptoService().Create(role, repo.gun, data.ECDSAKey) require.NoError(t, err, "error creating key") @@ -2231,7 +2239,7 @@ func testPublishDelegations(t *testing.T, clearCache, x509Keys bool) { _, err := repo2.ListTargets() require.NoError(t, err, "unable to pull repo") - for _, repo := range []*NotaryRepository{repo1, repo2} { + for _, repo := range []*repository{repo1, repo2} { // targets should have delegations targets/a and targets/c targets := repo.tufRepo.Targets[data.CanonicalTargetsRole] require.Len(t, targets.Signed.Delegations.Roles, 2) @@ -2508,7 +2516,7 @@ func TestPublishTargetsDelegationFromTwoRepos(t *testing.T) { rec1.clear() // both repos should be able to see all targets - for _, repo := range []*NotaryRepository{repo1, repo2} { + for _, repo := range []*repository{repo1, repo2} { targets, err := repo.ListTargets() require.NoError(t, err) require.Len(t, targets, 3) @@ -2768,12 +2776,12 @@ func TestRemoteRotationNoInit(t *testing.T) { // Rotates the keys. After the rotation, downloading the latest metadata // and require that the keys have changed -func requireRotationSuccessful(t *testing.T, repo1 *NotaryRepository, keysToRotate map[data.RoleName]bool) { +func requireRotationSuccessful(t *testing.T, repo1 *repository, keysToRotate map[data.RoleName]bool) { // Create a new repo that is used to download the data after the rotation repo2, _ := newRepoToTestRepo(t, repo1, true) defer os.RemoveAll(repo2.baseDir) - repos := []*NotaryRepository{repo1, repo2} + repos := []*repository{repo1, repo2} oldRoles := make(map[string]data.BaseRole) for roleName := range keysToRotate { @@ -2937,7 +2945,7 @@ func testRotateKeySuccess(t *testing.T, serverManagesSnapshotInit bool, require.NoError(t, err) } -func logRepoTrustRoot(t *testing.T, prefix string, repo *NotaryRepository) { +func logRepoTrustRoot(t *testing.T, prefix string, repo *repository) { logrus.Debugf("==== %s", prefix) root := repo.tufRepo.Root logrus.Debugf("Root signatures:") @@ -2951,7 +2959,7 @@ func logRepoTrustRoot(t *testing.T, prefix string, repo *NotaryRepository) { } // ID of the (only) certificate trusted by the root role metadata -func rootRoleCertID(t *testing.T, repo *NotaryRepository) string { +func rootRoleCertID(t *testing.T, repo *repository) string { rootKeys := repo.tufRepo.Root.Signed.Roles[data.CanonicalRootRole].KeyIDs require.Len(t, rootKeys, 1) return rootKeys[0] @@ -3284,9 +3292,10 @@ func TestRemoteServerUnavailableNoLocalCache(t *testing.T) { ts := errorTestServer(t, 500) defer ts.Close() - repo, err := NewFileCachedNotaryRepository(tempBaseDir, "docker.com/notary", + r, err := NewFileCachedRepository(tempBaseDir, "docker.com/notary", ts.URL, http.DefaultTransport, passphraseRetriever, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) + repo := r.(*repository) _, err = repo.ListTargets(data.CanonicalTargetsRole) require.Error(t, err) @@ -3381,7 +3390,7 @@ func TestAddDelegationChangefileApplicable(t *testing.T) { // TestAddDelegationErrorWritingChanges expects errors writing a change to file // to be propagated. func TestAddDelegationErrorWritingChanges(t *testing.T) { - testErrorWritingChangefiles(t, func(repo *NotaryRepository) error { + testErrorWritingChangefiles(t, func(repo *repository) error { targetKeyIds := repo.GetCryptoService().ListKeys(data.CanonicalTargetsRole) require.NotEmpty(t, targetKeyIds) targetPubKey := repo.GetCryptoService().GetKey(targetKeyIds[0]) @@ -3586,7 +3595,7 @@ func TestFullRemoveDelegationChangefileApplicable(t *testing.T) { // TestRemoveDelegationErrorWritingChanges expects errors writing a change to // file to be propagated. func TestRemoveDelegationErrorWritingChanges(t *testing.T) { - testErrorWritingChangefiles(t, func(repo *NotaryRepository) error { + testErrorWritingChangefiles(t, func(repo *repository) error { return repo.RemoveDelegationKeysAndPaths("targets/a", []string{""}, []string{}) }) } @@ -3597,7 +3606,7 @@ func TestRemoveDelegationErrorWritingChanges(t *testing.T) { func TestBootstrapClientBadURL(t *testing.T) { tempBaseDir, err := ioutil.TempDir("", "notary-test-") require.NoError(t, err, "failed to create a temporary directory: %s", err) - repo, err := NewFileCachedNotaryRepository( + r, err := NewFileCachedRepository( tempBaseDir, "testGun", "http://localhost:9998", @@ -3606,6 +3615,7 @@ func TestBootstrapClientBadURL(t *testing.T) { trustpinning.TrustPinConfig{}, ) require.NoError(t, err, "error creating repo: %s", err) + repo := r.(*repository) c, err := repo.bootstrapClient(false) require.Nil(t, c) @@ -3621,13 +3631,13 @@ func TestBootstrapClientBadURL(t *testing.T) { require.EqualError(t, err, err2.Error()) } -// TestClientInvalidURL checks that instantiating a new NotaryRepository +// TestClientInvalidURL checks that instantiating a new repository // correctly returns an error when the URL is valid but does not point to // a TUF server func TestClientInvalidURL(t *testing.T) { tempBaseDir, err := ioutil.TempDir("", "notary-test-") require.NoError(t, err, "failed to create a temporary directory: %s", err) - repo, err := NewFileCachedNotaryRepository( + r, err := NewFileCachedRepository( tempBaseDir, "testGun", "#!*)&!)#*^%!#)%^!#", @@ -3635,10 +3645,10 @@ func TestClientInvalidURL(t *testing.T) { passphraseRetriever, trustpinning.TrustPinConfig{}, ) - // NewFileCachedNotaryRepository should fail and return an error + // NewFileCachedRepository should fail and return an error // since it initializes the cache but also the remote repository // from the baseURL and the GUN - require.Nil(t, repo) + require.Nil(t, r) require.Error(t, err) } diff --git a/client/client_update_test.go b/client/client_update_test.go index 87673388e0..0728594b06 100644 --- a/client/client_update_test.go +++ b/client/client_update_test.go @@ -26,15 +26,15 @@ import ( "github.com/stretchr/testify/require" ) -func newBlankRepo(t *testing.T, url string) *NotaryRepository { +func newBlankRepo(t *testing.T, url string) *repository { // Temporary directory where test files will be created tempBaseDir, err := ioutil.TempDir("", "notary-test-") require.NoError(t, err, "failed to create a temporary directory: %s", err) - repo, err := NewFileCachedNotaryRepository(tempBaseDir, "docker.com/notary", url, + r, err := NewFileCachedRepository(tempBaseDir, "docker.com/notary", url, http.DefaultTransport, passphrase.ConstantRetriever("pass"), trustpinning.TrustPinConfig{}) require.NoError(t, err) - return repo + return r.(*repository) } var metadataDelegations = []data.RoleName{"targets/a", "targets/a/b", "targets/b", "targets/a/b/c", "targets/b/c"} @@ -207,9 +207,10 @@ func TestUpdateInOfflineMode(t *testing.T) { require.NoError(t, err, "failed to create a temporary directory: %s", err) defer os.RemoveAll(tempBaseDir) - offlineRepo, err := NewFileCachedNotaryRepository(tempBaseDir, "docker.com/notary", "https://nope", + or, err := NewFileCachedRepository(tempBaseDir, "docker.com/notary", "https://nope", nil, passphrase.ConstantRetriever("pass"), trustpinning.TrustPinConfig{}) require.NoError(t, err) + offlineRepo := or.(*repository) err = offlineRepo.Update(false) require.Error(t, err) require.IsType(t, store.ErrOffline{}, err) @@ -403,7 +404,7 @@ type updateOpts struct { forWrite bool // whether the update is for writing or not (force check remote root.json) role data.RoleName // the role to mess up on the server - checkRepo func(*NotaryRepository, *testutils.MetadataSwizzler) // a callback that can examine the repo at the end + checkRepo func(*repository, *testutils.MetadataSwizzler) // a callback that can examine the repo at the end } // If there's no local cache, we go immediately to check the remote server for @@ -1171,8 +1172,8 @@ func TestUpdateNonRootRemoteCorruptedCanUseLocalCache(t *testing.T) { // requires that a delegation role and its descendants were not accepted as a valid part of the // TUF repo, but everything else was -func checkBadDelegationRoleSkipped(t *testing.T, delgRoleName string) func(*NotaryRepository, *testutils.MetadataSwizzler) { - return func(repo *NotaryRepository, s *testutils.MetadataSwizzler) { +func checkBadDelegationRoleSkipped(t *testing.T, delgRoleName string) func(*repository, *testutils.MetadataSwizzler) { + return func(repo *repository, s *testutils.MetadataSwizzler) { for _, roleName := range s.Roles { if roleName != data.CanonicalTargetsRole && !data.IsDelegation(roleName) { continue diff --git a/client/delegations.go b/client/delegations.go index d32c558fcf..e0861819f5 100644 --- a/client/delegations.go +++ b/client/delegations.go @@ -14,7 +14,7 @@ import ( // AddDelegation creates changelist entries to add provided delegation public keys and paths. // This method composes AddDelegationRoleAndKeys and AddDelegationPaths (each creates one changelist if called). -func (r *NotaryRepository) AddDelegation(name data.RoleName, delegationKeys []data.PublicKey, paths []string) error { +func (r *repository) AddDelegation(name data.RoleName, delegationKeys []data.PublicKey, paths []string) error { if len(delegationKeys) > 0 { err := r.AddDelegationRoleAndKeys(name, delegationKeys) if err != nil { @@ -33,7 +33,7 @@ func (r *NotaryRepository) AddDelegation(name data.RoleName, delegationKeys []da // AddDelegationRoleAndKeys creates a changelist entry to add provided delegation public keys. // This method is the simplest way to create a new delegation, because the delegation must have at least // one key upon creation to be valid since we will reject the changelist while validating the threshold. -func (r *NotaryRepository) AddDelegationRoleAndKeys(name data.RoleName, delegationKeys []data.PublicKey) error { +func (r *repository) AddDelegationRoleAndKeys(name data.RoleName, delegationKeys []data.PublicKey) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} @@ -57,7 +57,7 @@ func (r *NotaryRepository) AddDelegationRoleAndKeys(name data.RoleName, delegati // AddDelegationPaths creates a changelist entry to add provided paths to an existing delegation. // This method cannot create a new delegation itself because the role must meet the key threshold upon creation. -func (r *NotaryRepository) AddDelegationPaths(name data.RoleName, paths []string) error { +func (r *repository) AddDelegationPaths(name data.RoleName, paths []string) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} @@ -78,7 +78,7 @@ func (r *NotaryRepository) AddDelegationPaths(name data.RoleName, paths []string // RemoveDelegationKeysAndPaths creates changelist entries to remove provided delegation key IDs and paths. // This method composes RemoveDelegationPaths and RemoveDelegationKeys (each creates one changelist if called). -func (r *NotaryRepository) RemoveDelegationKeysAndPaths(name data.RoleName, keyIDs, paths []string) error { +func (r *repository) RemoveDelegationKeysAndPaths(name data.RoleName, keyIDs, paths []string) error { if len(paths) > 0 { err := r.RemoveDelegationPaths(name, paths) if err != nil { @@ -95,7 +95,7 @@ func (r *NotaryRepository) RemoveDelegationKeysAndPaths(name data.RoleName, keyI } // RemoveDelegationRole creates a changelist to remove all paths and keys from a role, and delete the role in its entirety. -func (r *NotaryRepository) RemoveDelegationRole(name data.RoleName) error { +func (r *repository) RemoveDelegationRole(name data.RoleName) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} @@ -108,7 +108,7 @@ func (r *NotaryRepository) RemoveDelegationRole(name data.RoleName) error { } // RemoveDelegationPaths creates a changelist entry to remove provided paths from an existing delegation. -func (r *NotaryRepository) RemoveDelegationPaths(name data.RoleName, paths []string) error { +func (r *repository) RemoveDelegationPaths(name data.RoleName, paths []string) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} @@ -132,7 +132,7 @@ func (r *NotaryRepository) RemoveDelegationPaths(name data.RoleName, paths []str // the role itself will be deleted in its entirety. // It can also delete a key from all delegations under a parent using a name // with a wildcard at the end. -func (r *NotaryRepository) RemoveDelegationKeys(name data.RoleName, keyIDs []string) error { +func (r *repository) RemoveDelegationKeys(name data.RoleName, keyIDs []string) error { if !data.IsDelegation(name) && !data.IsWildDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} @@ -152,7 +152,7 @@ func (r *NotaryRepository) RemoveDelegationKeys(name data.RoleName, keyIDs []str } // ClearDelegationPaths creates a changelist entry to remove all paths from an existing delegation. -func (r *NotaryRepository) ClearDelegationPaths(name data.RoleName) error { +func (r *repository) ClearDelegationPaths(name data.RoleName) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} @@ -203,7 +203,7 @@ func newDeleteDelegationChange(name data.RoleName, content []byte) *changelist.T // GetDelegationRoles returns the keys and roles of the repository's delegations // Also converts key IDs to canonical key IDs to keep consistent with signing prompts -func (r *NotaryRepository) GetDelegationRoles() ([]data.Role, error) { +func (r *repository) GetDelegationRoles() ([]data.Role, error) { // Update state of the repo to latest if err := r.Update(false); err != nil { return nil, err diff --git a/client/errors.go b/client/errors.go index 4c765dace0..ba7759c4f7 100644 --- a/client/errors.go +++ b/client/errors.go @@ -2,6 +2,7 @@ package client import ( "fmt" + "github.com/docker/notary/tuf/data" ) diff --git a/client/witness.go b/client/witness.go index 72aed031c9..b52239baae 100644 --- a/client/witness.go +++ b/client/witness.go @@ -8,7 +8,7 @@ import ( // Witness creates change objects to witness (i.e. re-sign) the given // roles on the next publish. One change is created per role -func (r *NotaryRepository) Witness(roles ...data.RoleName) ([]data.RoleName, error) { +func (r *repository) Witness(roles ...data.RoleName) ([]data.RoleName, error) { var err error successful := make([]data.RoleName, 0, len(roles)) for _, role := range roles { diff --git a/cmd/notary/delegations.go b/cmd/notary/delegations.go index 6b96304be2..fa8c30db30 100644 --- a/cmd/notary/delegations.go +++ b/cmd/notary/delegations.go @@ -103,7 +103,7 @@ func (d *delegationCommander) delegationPurgeKeys(cmd *cobra.Command, args []str return err } - nRepo, err := notaryclient.NewFileCachedNotaryRepository( + nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), @@ -153,7 +153,7 @@ func (d *delegationCommander) delegationsList(cmd *cobra.Command, args []string) } // initialize repo with transport to get latest state of the world before listing delegations - nRepo, err := notaryclient.NewFileCachedNotaryRepository( + nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), rt, d.retriever, trustPin) if err != nil { return err @@ -184,7 +184,7 @@ func (d *delegationCommander) delegationRemove(cmd *cobra.Command, args []string // no online operations are performed by add so the transport argument // should be nil - nRepo, err := notaryclient.NewFileCachedNotaryRepository( + nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, d.retriever, trustPin) if err != nil { return err @@ -314,7 +314,7 @@ func (d *delegationCommander) delegationAdd(cmd *cobra.Command, args []string) e // no online operations are performed by add so the transport argument // should be nil - nRepo, err := notaryclient.NewFileCachedNotaryRepository( + nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, d.retriever, trustPin) if err != nil { return err diff --git a/cmd/notary/keys.go b/cmd/notary/keys.go index bf61b29cc5..e78d1a9927 100644 --- a/cmd/notary/keys.go +++ b/cmd/notary/keys.go @@ -310,7 +310,7 @@ func (k *keyCommander) keysRotate(cmd *cobra.Command, args []string) error { return err } - nRepo, err := notaryclient.NewFileCachedNotaryRepository( + nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), rt, k.getRetriever(), trustPin) if err != nil { @@ -341,7 +341,7 @@ func (k *keyCommander) keysRotate(cmd *cobra.Command, args []string) error { return nil } } - nRepo.LegacyVersions = k.legacyVersions + nRepo.SetLegacyVersions(k.legacyVersions) if err := nRepo.RotateKey(rotateKeyRole, k.rotateKeyServerManaged, keyList); err != nil { return err } diff --git a/cmd/notary/keys_test.go b/cmd/notary/keys_test.go index 5d85aa7a00..244a954e05 100644 --- a/cmd/notary/keys_test.go +++ b/cmd/notary/keys_test.go @@ -333,7 +333,7 @@ func setUpRepo(t *testing.T, tempBaseDir string, gun data.GUN, ret notary.PassRe cryptoService := cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(ret)) ts := httptest.NewServer(server.RootHandler(ctx, nil, cryptoService, nil, nil, nil)) - repo, err := client.NewFileCachedNotaryRepository( + repo, err := client.NewFileCachedRepository( tempBaseDir, gun, ts.URL, http.DefaultTransport, ret, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) @@ -376,7 +376,7 @@ func TestRotateKeyRemoteServerManagesKey(t *testing.T) { } require.NoError(t, k.keysRotate(&cobra.Command{}, []string{gun.String(), role, "-r"})) - repo, err := client.NewFileCachedNotaryRepository(tempBaseDir, data.GUN(gun), ts.URL, http.DefaultTransport, ret, trustpinning.TrustPinConfig{}) + repo, err := client.NewFileCachedRepository(tempBaseDir, data.GUN(gun), ts.URL, http.DefaultTransport, ret, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) cl, err := repo.GetChangelist() @@ -430,7 +430,7 @@ func TestRotateKeyBothKeys(t *testing.T) { require.NoError(t, k.keysRotate(&cobra.Command{}, []string{gun.String(), data.CanonicalTargetsRole.String()})) require.NoError(t, k.keysRotate(&cobra.Command{}, []string{gun.String(), data.CanonicalSnapshotRole.String()})) - repo, err := client.NewFileCachedNotaryRepository(tempBaseDir, data.GUN(gun), ts.URL, nil, ret, trustpinning.TrustPinConfig{}) + repo, err := client.NewFileCachedRepository(tempBaseDir, data.GUN(gun), ts.URL, nil, ret, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) cl, err := repo.GetChangelist() @@ -495,7 +495,7 @@ func TestRotateKeyRootIsInteractive(t *testing.T) { require.Contains(t, out.String(), "Aborting action") - repo, err := client.NewFileCachedNotaryRepository(tempBaseDir, gun, ts.URL, nil, ret, trustpinning.TrustPinConfig{}) + repo, err := client.NewFileCachedRepository(tempBaseDir, gun, ts.URL, nil, ret, trustpinning.TrustPinConfig{}) require.NoError(t, err, "error creating repo: %s", err) // There should still just be one root key (and one targets and one snapshot) diff --git a/cmd/notary/repo_factory.go b/cmd/notary/repo_factory.go index 6547b06af6..62dc95fce0 100644 --- a/cmd/notary/repo_factory.go +++ b/cmd/notary/repo_factory.go @@ -31,7 +31,7 @@ func ConfigureRepo(v *viper.Viper, retriever notary.PassRetriever, onlineOperati return nil, err } } - return client.NewFileCachedNotaryRepository( + return client.NewFileCachedRepository( v.GetString("trust_dir"), gun, getRemoteTrustServer(v), diff --git a/cmd/notary/tuf.go b/cmd/notary/tuf.go index fbb8b707b4..42f419cf07 100644 --- a/cmd/notary/tuf.go +++ b/cmd/notary/tuf.go @@ -1034,7 +1034,7 @@ func maybeAutoPublish(cmd *cobra.Command, doPublish bool, gun data.GUN, config * return err } - nRepo, err := notaryclient.NewFileCachedNotaryRepository( + nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), rt, passRetriever, trustPin) if err != nil { return err diff --git a/trustmanager/remoteks/client_test.go b/trustmanager/remoteks/client_test.go index fef9b1fdb7..4b25cbe417 100644 --- a/trustmanager/remoteks/client_test.go +++ b/trustmanager/remoteks/client_test.go @@ -9,12 +9,13 @@ import ( "crypto/tls" "crypto/x509" - "github.com/docker/notary/storage" - "github.com/docker/notary/trustmanager" - "google.golang.org/grpc/credentials" "io/ioutil" "path/filepath" "runtime" + + "github.com/docker/notary/storage" + "github.com/docker/notary/trustmanager" + "google.golang.org/grpc/credentials" ) type TestError struct{} diff --git a/trustmanager/remoteks/server_test.go b/trustmanager/remoteks/server_test.go index 807ba55f87..70465bfd2c 100644 --- a/trustmanager/remoteks/server_test.go +++ b/trustmanager/remoteks/server_test.go @@ -1,11 +1,11 @@ package remoteks import ( - "github.com/stretchr/testify/require" - "golang.org/x/net/context" "testing" "github.com/docker/notary/storage" + "github.com/stretchr/testify/require" + "golang.org/x/net/context" ) func TestNewGRPCStorage(t *testing.T) { diff --git a/trustmanager/yubikey/import.go b/trustmanager/yubikey/import.go index c8eddf6dc1..a51af88bdf 100644 --- a/trustmanager/yubikey/import.go +++ b/trustmanager/yubikey/import.go @@ -5,6 +5,7 @@ package yubikey import ( "encoding/pem" "errors" + "github.com/docker/notary" "github.com/docker/notary/trustmanager" "github.com/docker/notary/tuf/data" diff --git a/trustpinning/trustpin_test.go b/trustpinning/trustpin_test.go index aa35fa6637..d8ba99c3e3 100644 --- a/trustpinning/trustpin_test.go +++ b/trustpinning/trustpin_test.go @@ -1,8 +1,9 @@ package trustpinning import ( - "github.com/stretchr/testify/require" "testing" + + "github.com/stretchr/testify/require" ) func TestWildcardMatch(t *testing.T) { diff --git a/tuf/data/roles_test.go b/tuf/data/roles_test.go index 72b277ad41..79d659548b 100644 --- a/tuf/data/roles_test.go +++ b/tuf/data/roles_test.go @@ -1,11 +1,11 @@ package data import ( + "fmt" "path" "strings" "testing" - "fmt" "github.com/stretchr/testify/require" )