repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
theupdateframework/notary
client/client.go
InitializeWithCertificate
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 if len(rootKeyIDs) == 0 && len(rootCerts) != 0 { rootKeyIDs = []string{} availableRootKeyIDs := make(map[string]bool) for _, k := range r.GetCryptoService().ListKeys(data.CanonicalRootRole) { availableRootKeyIDs[k] = true } for _, cert := range rootCerts { if err := keyExistsInList(cert, availableRootKeyIDs); err != nil { return fmt.Errorf("error initializing repository with certificate: %v", err) } keyID, _ := utils.CanonicalKeyID(cert) rootKeyIDs = append(rootKeyIDs, keyID) } } return r.initialize(rootKeyIDs, rootCerts, serverManagedRoles...) }
go
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 if len(rootKeyIDs) == 0 && len(rootCerts) != 0 { rootKeyIDs = []string{} availableRootKeyIDs := make(map[string]bool) for _, k := range r.GetCryptoService().ListKeys(data.CanonicalRootRole) { availableRootKeyIDs[k] = true } for _, cert := range rootCerts { if err := keyExistsInList(cert, availableRootKeyIDs); err != nil { return fmt.Errorf("error initializing repository with certificate: %v", err) } keyID, _ := utils.CanonicalKeyID(cert) rootKeyIDs = append(rootKeyIDs, keyID) } } return r.initialize(rootKeyIDs, rootCerts, serverManagedRoles...) }
[ "func", "(", "r", "*", "repository", ")", "InitializeWithCertificate", "(", "rootKeyIDs", "[", "]", "string", ",", "rootCerts", "[", "]", "data", ".", "PublicKey", ",", "serverManagedRoles", "...", "data", ".", "RoleName", ")", "error", "{", "if", "len", "...
// InitializeWithCertificate initializes the repository with root keys and their corresponding certificates
[ "InitializeWithCertificate", "initializes", "the", "repository", "with", "root", "keys", "and", "their", "corresponding", "certificates" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L383-L403
train
theupdateframework/notary
client/client.go
addChange
func addChange(cl changelist.Changelist, c changelist.Change, roles ...data.RoleName) error { if len(roles) == 0 { roles = []data.RoleName{data.CanonicalTargetsRole} } var changes []changelist.Change for _, role := range roles { // Ensure we can only add targets to the CanonicalTargetsRole, // or a Delegation role (which is <CanonicalTargetsRole>/something else) if role != data.CanonicalTargetsRole && !data.IsDelegation(role) && !data.IsWildDelegation(role) { return data.ErrInvalidRole{ Role: role, Reason: "cannot add targets to this role", } } changes = append(changes, changelist.NewTUFChange( c.Action(), role, c.Type(), c.Path(), c.Content(), )) } for _, c := range changes { if err := cl.Add(c); err != nil { return err } } return nil }
go
func addChange(cl changelist.Changelist, c changelist.Change, roles ...data.RoleName) error { if len(roles) == 0 { roles = []data.RoleName{data.CanonicalTargetsRole} } var changes []changelist.Change for _, role := range roles { // Ensure we can only add targets to the CanonicalTargetsRole, // or a Delegation role (which is <CanonicalTargetsRole>/something else) if role != data.CanonicalTargetsRole && !data.IsDelegation(role) && !data.IsWildDelegation(role) { return data.ErrInvalidRole{ Role: role, Reason: "cannot add targets to this role", } } changes = append(changes, changelist.NewTUFChange( c.Action(), role, c.Type(), c.Path(), c.Content(), )) } for _, c := range changes { if err := cl.Add(c); err != nil { return err } } return nil }
[ "func", "addChange", "(", "cl", "changelist", ".", "Changelist", ",", "c", "changelist", ".", "Change", ",", "roles", "...", "data", ".", "RoleName", ")", "error", "{", "if", "len", "(", "roles", ")", "==", "0", "{", "roles", "=", "[", "]", "data", ...
// adds a TUF Change template to the given roles
[ "adds", "a", "TUF", "Change", "template", "to", "the", "given", "roles" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L468-L499
train
theupdateframework/notary
client/client.go
AddTarget
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) } logrus.Debugf("Adding target \"%s\" with sha256 \"%x\" and size %d bytes.\n", target.Name, target.Hashes["sha256"], target.Length) meta := data.FileMeta{Length: target.Length, Hashes: target.Hashes, Custom: target.Custom} metaJSON, err := json.Marshal(meta) if err != nil { return err } template := changelist.NewTUFChange( changelist.ActionCreate, "", changelist.TypeTargetsTarget, target.Name, metaJSON) return addChange(r.changelist, template, roles...) }
go
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) } logrus.Debugf("Adding target \"%s\" with sha256 \"%x\" and size %d bytes.\n", target.Name, target.Hashes["sha256"], target.Length) meta := data.FileMeta{Length: target.Length, Hashes: target.Hashes, Custom: target.Custom} metaJSON, err := json.Marshal(meta) if err != nil { return err } template := changelist.NewTUFChange( changelist.ActionCreate, "", changelist.TypeTargetsTarget, target.Name, metaJSON) return addChange(r.changelist, template, roles...) }
[ "func", "(", "r", "*", "repository", ")", "AddTarget", "(", "target", "*", "Target", ",", "roles", "...", "data", ".", "RoleName", ")", "error", "{", "if", "len", "(", "target", ".", "Hashes", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(...
// 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"
[ "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", "...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L504-L520
train
theupdateframework/notary
client/client.go
RemoveTarget
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) return addChange(r.changelist, template, roles...) }
go
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) return addChange(r.changelist, template, roles...) }
[ "func", "(", "r", "*", "repository", ")", "RemoveTarget", "(", "targetName", "string", ",", "roles", "...", "data", ".", "RoleName", ")", "error", "{", "logrus", ".", "Debugf", "(", "\"Removing target \\\"%s\\\"\"", ",", "\\\"", ")", "\n", "\\\"", "\n", "t...
// 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".
[ "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", "unspecifi...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L525-L530
train
theupdateframework/notary
client/client.go
getRemoteStore
func (r *repository) getRemoteStore() store.RemoteStore { if r.remoteStore != nil { return r.remoteStore } r.remoteStore = &store.OfflineStore{} return r.remoteStore }
go
func (r *repository) getRemoteStore() store.RemoteStore { if r.remoteStore != nil { return r.remoteStore } r.remoteStore = &store.OfflineStore{} return r.remoteStore }
[ "func", "(", "r", "*", "repository", ")", "getRemoteStore", "(", ")", "store", ".", "RemoteStore", "{", "if", "r", ".", "remoteStore", "!=", "nil", "{", "return", "r", ".", "remoteStore", "\n", "}", "\n", "r", ".", "remoteStore", "=", "&", "store", "...
// getRemoteStore returns the remoteStore of a repository if valid or // or an OfflineStore otherwise
[ "getRemoteStore", "returns", "the", "remoteStore", "of", "a", "repository", "if", "valid", "or", "or", "an", "OfflineStore", "otherwise" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L539-L547
train
theupdateframework/notary
client/client.go
Publish
func (r *repository) Publish() error { if err := r.publish(r.changelist); err != nil { return err } if err := r.changelist.Clear(""); err != nil { // This is not a critical problem when only a single host is pushing // but will cause weird behaviour if changelist cleanup is failing // and there are multiple hosts writing to the repo. logrus.Warn("Unable to clear changelist. You may want to manually delete the folder ", r.changelist.Location()) } return nil }
go
func (r *repository) Publish() error { if err := r.publish(r.changelist); err != nil { return err } if err := r.changelist.Clear(""); err != nil { // This is not a critical problem when only a single host is pushing // but will cause weird behaviour if changelist cleanup is failing // and there are multiple hosts writing to the repo. logrus.Warn("Unable to clear changelist. You may want to manually delete the folder ", r.changelist.Location()) } return nil }
[ "func", "(", "r", "*", "repository", ")", "Publish", "(", ")", "error", "{", "if", "err", ":=", "r", ".", "publish", "(", "r", ".", "changelist", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "r", ".", ...
// Publish pushes the local changes in signed material to the remote notary-server // Conceptually it performs an operation similar to a `git rebase`
[ "Publish", "pushes", "the", "local", "changes", "in", "signed", "material", "to", "the", "remote", "notary", "-", "server", "Conceptually", "it", "performs", "an", "operation", "similar", "to", "a", "git", "rebase" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L551-L562
train
theupdateframework/notary
client/client.go
publish
func (r *repository) publish(cl changelist.Changelist) error { var initialPublish bool // update first before publishing if err := r.updateTUF(true); err != nil { // If the remote is not aware of the repo, then this is being published // for the first time. Try to initialize the repository before publishing. if _, ok := err.(ErrRepositoryNotExist); ok { err := r.bootstrapRepo() if _, ok := err.(store.ErrMetaNotFound); ok { logrus.Infof("No TUF data found locally or remotely - initializing repository %s for the first time", r.gun.String()) err = r.Initialize(nil) } if err != nil { logrus.WithError(err).Debugf("Unable to load or initialize repository during first publish: %s", err.Error()) return err } // Ensure we will push the initial root and targets file. Either or // both of the root and targets may not be marked as Dirty, since // there may not be any changes that update them, so use a // different boolean. initialPublish = true } else { // We could not update, so we cannot publish. logrus.Error("Could not publish Repository since we could not update: ", err.Error()) return err } } // apply the changelist to the repo if err := applyChangelist(r.tufRepo, r.invalid, cl); err != nil { logrus.Debug("Error applying changelist") return err } // these are the TUF files we will need to update, serialized as JSON before // we send anything to remote updatedFiles := make(map[data.RoleName][]byte) // Fetch old keys to support old clients legacyKeys, err := r.oldKeysForLegacyClientSupport(r.LegacyVersions, initialPublish) if err != nil { return err } // check if our root file is nearing expiry or dirty. Resign if it is. If // root is not dirty but we are publishing for the first time, then just // publish the existing root we have. if err := signRootIfNecessary(updatedFiles, r.tufRepo, legacyKeys, initialPublish); err != nil { return err } if err := signTargets(updatedFiles, r.tufRepo, initialPublish); err != nil { return err } // if we initialized the repo while designating the server as the snapshot // signer, then there won't be a snapshots file. However, we might now // have a local key (if there was a rotation), so initialize one. if r.tufRepo.Snapshot == nil { if err := r.tufRepo.InitSnapshot(); err != nil { return err } } if snapshotJSON, err := serializeCanonicalRole( r.tufRepo, data.CanonicalSnapshotRole, nil); err == nil { // Only update the snapshot if we've successfully signed it. updatedFiles[data.CanonicalSnapshotRole] = snapshotJSON } else if signErr, ok := err.(signed.ErrInsufficientSignatures); ok && signErr.FoundKeys == 0 { // If signing fails due to us not having the snapshot key, then // assume the server is going to sign, and do not include any snapshot // data. logrus.Debugf("Client does not have the key to sign snapshot. " + "Assuming that server should sign the snapshot.") } else { logrus.Debugf("Client was unable to sign the snapshot: %s", err.Error()) return err } remote := r.getRemoteStore() return remote.SetMulti(data.MetadataRoleMapToStringMap(updatedFiles)) }
go
func (r *repository) publish(cl changelist.Changelist) error { var initialPublish bool // update first before publishing if err := r.updateTUF(true); err != nil { // If the remote is not aware of the repo, then this is being published // for the first time. Try to initialize the repository before publishing. if _, ok := err.(ErrRepositoryNotExist); ok { err := r.bootstrapRepo() if _, ok := err.(store.ErrMetaNotFound); ok { logrus.Infof("No TUF data found locally or remotely - initializing repository %s for the first time", r.gun.String()) err = r.Initialize(nil) } if err != nil { logrus.WithError(err).Debugf("Unable to load or initialize repository during first publish: %s", err.Error()) return err } // Ensure we will push the initial root and targets file. Either or // both of the root and targets may not be marked as Dirty, since // there may not be any changes that update them, so use a // different boolean. initialPublish = true } else { // We could not update, so we cannot publish. logrus.Error("Could not publish Repository since we could not update: ", err.Error()) return err } } // apply the changelist to the repo if err := applyChangelist(r.tufRepo, r.invalid, cl); err != nil { logrus.Debug("Error applying changelist") return err } // these are the TUF files we will need to update, serialized as JSON before // we send anything to remote updatedFiles := make(map[data.RoleName][]byte) // Fetch old keys to support old clients legacyKeys, err := r.oldKeysForLegacyClientSupport(r.LegacyVersions, initialPublish) if err != nil { return err } // check if our root file is nearing expiry or dirty. Resign if it is. If // root is not dirty but we are publishing for the first time, then just // publish the existing root we have. if err := signRootIfNecessary(updatedFiles, r.tufRepo, legacyKeys, initialPublish); err != nil { return err } if err := signTargets(updatedFiles, r.tufRepo, initialPublish); err != nil { return err } // if we initialized the repo while designating the server as the snapshot // signer, then there won't be a snapshots file. However, we might now // have a local key (if there was a rotation), so initialize one. if r.tufRepo.Snapshot == nil { if err := r.tufRepo.InitSnapshot(); err != nil { return err } } if snapshotJSON, err := serializeCanonicalRole( r.tufRepo, data.CanonicalSnapshotRole, nil); err == nil { // Only update the snapshot if we've successfully signed it. updatedFiles[data.CanonicalSnapshotRole] = snapshotJSON } else if signErr, ok := err.(signed.ErrInsufficientSignatures); ok && signErr.FoundKeys == 0 { // If signing fails due to us not having the snapshot key, then // assume the server is going to sign, and do not include any snapshot // data. logrus.Debugf("Client does not have the key to sign snapshot. " + "Assuming that server should sign the snapshot.") } else { logrus.Debugf("Client was unable to sign the snapshot: %s", err.Error()) return err } remote := r.getRemoteStore() return remote.SetMulti(data.MetadataRoleMapToStringMap(updatedFiles)) }
[ "func", "(", "r", "*", "repository", ")", "publish", "(", "cl", "changelist", ".", "Changelist", ")", "error", "{", "var", "initialPublish", "bool", "\n", "if", "err", ":=", "r", ".", "updateTUF", "(", "true", ")", ";", "err", "!=", "nil", "{", "if",...
// publish pushes the changes in the given changelist to the remote notary-server // Conceptually it performs an operation similar to a `git rebase`
[ "publish", "pushes", "the", "changes", "in", "the", "given", "changelist", "to", "the", "remote", "notary", "-", "server", "Conceptually", "it", "performs", "an", "operation", "similar", "to", "a", "git", "rebase" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L566-L649
train
theupdateframework/notary
client/client.go
getOldRootPublicKeys
func getOldRootPublicKeys(root *data.SignedRoot) data.KeyList { rootRole, err := root.BuildBaseRole(data.CanonicalRootRole) if err != nil { return nil } return rootRole.ListKeys() }
go
func getOldRootPublicKeys(root *data.SignedRoot) data.KeyList { rootRole, err := root.BuildBaseRole(data.CanonicalRootRole) if err != nil { return nil } return rootRole.ListKeys() }
[ "func", "getOldRootPublicKeys", "(", "root", "*", "data", ".", "SignedRoot", ")", "data", ".", "KeyList", "{", "rootRole", ",", "err", ":=", "root", ".", "BuildBaseRole", "(", "data", ".", "CanonicalRootRole", ")", "\n", "if", "err", "!=", "nil", "{", "r...
// get all the saved previous roles keys < the current root version
[ "get", "all", "the", "saved", "previous", "roles", "keys", "<", "the", "current", "root", "version" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L743-L749
train
theupdateframework/notary
client/client.go
saveMetadata
func (r *repository) saveMetadata(ignoreSnapshot bool) error { logrus.Debugf("Saving changes to Trusted Collection.") rootJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalRootRole, nil) if err != nil { return err } err = r.cache.Set(data.CanonicalRootRole.String(), rootJSON) if err != nil { return err } targetsToSave := make(map[data.RoleName][]byte) for t := range r.tufRepo.Targets { signedTargets, err := r.tufRepo.SignTargets(t, data.DefaultExpires(data.CanonicalTargetsRole)) if err != nil { return err } targetsJSON, err := json.Marshal(signedTargets) if err != nil { return err } targetsToSave[t] = targetsJSON } for role, blob := range targetsToSave { // If the parent directory does not exist, the cache.Set will create it r.cache.Set(role.String(), blob) } if ignoreSnapshot { return nil } snapshotJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalSnapshotRole, nil) if err != nil { return err } return r.cache.Set(data.CanonicalSnapshotRole.String(), snapshotJSON) }
go
func (r *repository) saveMetadata(ignoreSnapshot bool) error { logrus.Debugf("Saving changes to Trusted Collection.") rootJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalRootRole, nil) if err != nil { return err } err = r.cache.Set(data.CanonicalRootRole.String(), rootJSON) if err != nil { return err } targetsToSave := make(map[data.RoleName][]byte) for t := range r.tufRepo.Targets { signedTargets, err := r.tufRepo.SignTargets(t, data.DefaultExpires(data.CanonicalTargetsRole)) if err != nil { return err } targetsJSON, err := json.Marshal(signedTargets) if err != nil { return err } targetsToSave[t] = targetsJSON } for role, blob := range targetsToSave { // If the parent directory does not exist, the cache.Set will create it r.cache.Set(role.String(), blob) } if ignoreSnapshot { return nil } snapshotJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalSnapshotRole, nil) if err != nil { return err } return r.cache.Set(data.CanonicalSnapshotRole.String(), snapshotJSON) }
[ "func", "(", "r", "*", "repository", ")", "saveMetadata", "(", "ignoreSnapshot", "bool", ")", "error", "{", "logrus", ".", "Debugf", "(", "\"Saving changes to Trusted Collection.\"", ")", "\n", "rootJSON", ",", "err", ":=", "serializeCanonicalRole", "(", "r", "....
// saveMetadata saves contents of r.tufRepo onto the local disk, creating // signatures as necessary, possibly prompting for passphrases.
[ "saveMetadata", "saves", "contents", "of", "r", ".", "tufRepo", "onto", "the", "local", "disk", "creating", "signatures", "as", "necessary", "possibly", "prompting", "for", "passphrases", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L801-L841
train
theupdateframework/notary
client/client.go
pubKeyListForRotation
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 if serverManaged { remote := r.getRemoteStore() pubKey, err = rotateRemoteKey(role, remote) pubKeyList = make(data.KeyList, 0, 1) pubKeyList = append(pubKeyList, pubKey) if err != nil { return nil, fmt.Errorf("unable to rotate remote key: %s", err) } return pubKeyList, nil } // If no new keys are passed in, we generate one if len(newKeys) == 0 { pubKeyList = make(data.KeyList, 0, 1) pubKey, err = r.GetCryptoService().Create(role, r.gun, data.ECDSAKey) pubKeyList = append(pubKeyList, pubKey) } if err != nil { return nil, fmt.Errorf("unable to generate key: %s", err) } // If a list of keys to rotate to are provided, we add those if len(newKeys) > 0 { pubKeyList = make(data.KeyList, 0, len(newKeys)) for _, keyID := range newKeys { pubKey = r.GetCryptoService().GetKey(keyID) if pubKey == nil { return nil, fmt.Errorf("unable to find key: %s", keyID) } pubKeyList = append(pubKeyList, pubKey) } } // Convert to certs (for root keys) if pubKeyList, err = r.pubKeysToCerts(role, pubKeyList); err != nil { return nil, err } return pubKeyList, nil }
go
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 if serverManaged { remote := r.getRemoteStore() pubKey, err = rotateRemoteKey(role, remote) pubKeyList = make(data.KeyList, 0, 1) pubKeyList = append(pubKeyList, pubKey) if err != nil { return nil, fmt.Errorf("unable to rotate remote key: %s", err) } return pubKeyList, nil } // If no new keys are passed in, we generate one if len(newKeys) == 0 { pubKeyList = make(data.KeyList, 0, 1) pubKey, err = r.GetCryptoService().Create(role, r.gun, data.ECDSAKey) pubKeyList = append(pubKeyList, pubKey) } if err != nil { return nil, fmt.Errorf("unable to generate key: %s", err) } // If a list of keys to rotate to are provided, we add those if len(newKeys) > 0 { pubKeyList = make(data.KeyList, 0, len(newKeys)) for _, keyID := range newKeys { pubKey = r.GetCryptoService().GetKey(keyID) if pubKey == nil { return nil, fmt.Errorf("unable to find key: %s", keyID) } pubKeyList = append(pubKeyList, pubKey) } } // Convert to certs (for root keys) if pubKeyList, err = r.pubKeysToCerts(role, pubKeyList); err != nil { return nil, err } return pubKeyList, nil }
[ "func", "(", "r", "*", "repository", ")", "pubKeyListForRotation", "(", "role", "data", ".", "RoleName", ",", "serverManaged", "bool", ",", "newKeys", "[", "]", "string", ")", "(", "pubKeyList", "data", ".", "KeyList", ",", "err", "error", ")", "{", "var...
// Given a set of new keys to rotate to and a set of keys to drop, returns the list of current keys to use
[ "Given", "a", "set", "of", "new", "keys", "to", "rotate", "to", "and", "a", "set", "of", "keys", "to", "drop", "returns", "the", "list", "of", "current", "keys", "to", "use" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L866-L909
train
theupdateframework/notary
client/client.go
DeleteTrustData
func DeleteTrustData(baseDir string, gun data.GUN, URL string, rt http.RoundTripper, deleteRemote bool) error { localRepo := filepath.Join(baseDir, tufDir, filepath.FromSlash(gun.String())) // Remove the tufRepoPath directory, which includes local TUF metadata files and changelist information if err := os.RemoveAll(localRepo); err != nil { return fmt.Errorf("error clearing TUF repo data: %v", err) } // Note that this will require admin permission for the gun in the roundtripper if deleteRemote { remote, err := getRemoteStore(URL, gun, rt) if err != nil { logrus.Errorf("unable to instantiate a remote store: %v", err) return err } if err := remote.RemoveAll(); err != nil { return err } } return nil }
go
func DeleteTrustData(baseDir string, gun data.GUN, URL string, rt http.RoundTripper, deleteRemote bool) error { localRepo := filepath.Join(baseDir, tufDir, filepath.FromSlash(gun.String())) // Remove the tufRepoPath directory, which includes local TUF metadata files and changelist information if err := os.RemoveAll(localRepo); err != nil { return fmt.Errorf("error clearing TUF repo data: %v", err) } // Note that this will require admin permission for the gun in the roundtripper if deleteRemote { remote, err := getRemoteStore(URL, gun, rt) if err != nil { logrus.Errorf("unable to instantiate a remote store: %v", err) return err } if err := remote.RemoveAll(); err != nil { return err } } return nil }
[ "func", "DeleteTrustData", "(", "baseDir", "string", ",", "gun", "data", ".", "GUN", ",", "URL", "string", ",", "rt", "http", ".", "RoundTripper", ",", "deleteRemote", "bool", ")", "error", "{", "localRepo", ":=", "filepath", ".", "Join", "(", "baseDir", ...
// DeleteTrustData removes the trust data stored for this repo in the TUF cache on the client side // Note that we will not delete any private key material from local storage
[ "DeleteTrustData", "removes", "the", "trust", "data", "stored", "for", "this", "repo", "in", "the", "TUF", "cache", "on", "the", "client", "side", "Note", "that", "we", "will", "not", "delete", "any", "private", "key", "material", "from", "local", "storage" ...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L974-L992
train
theupdateframework/notary
tuf/tuf.go
NewRepo
func NewRepo(cryptoService signed.CryptoService) *Repo { return &Repo{ Targets: make(map[data.RoleName]*data.SignedTargets), cryptoService: cryptoService, } }
go
func NewRepo(cryptoService signed.CryptoService) *Repo { return &Repo{ Targets: make(map[data.RoleName]*data.SignedTargets), cryptoService: cryptoService, } }
[ "func", "NewRepo", "(", "cryptoService", "signed", ".", "CryptoService", ")", "*", "Repo", "{", "return", "&", "Repo", "{", "Targets", ":", "make", "(", "map", "[", "data", ".", "RoleName", "]", "*", "data", ".", "SignedTargets", ")", ",", "cryptoService...
// NewRepo initializes a Repo instance with a CryptoService. // If the Repo will only be used for reading, the CryptoService // can be nil.
[ "NewRepo", "initializes", "a", "Repo", "instance", "with", "a", "CryptoService", ".", "If", "the", "Repo", "will", "only", "be", "used", "for", "reading", "the", "CryptoService", "can", "be", "nil", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L76-L81
train
theupdateframework/notary
tuf/tuf.go
AddBaseKeys
func (tr *Repo) AddBaseKeys(role data.RoleName, keys ...data.PublicKey) error { if tr.Root == nil { return ErrNotLoaded{Role: data.CanonicalRootRole} } ids := []string{} for _, k := range keys { // Store only the public portion tr.Root.Signed.Keys[k.ID()] = k tr.Root.Signed.Roles[role].KeyIDs = append(tr.Root.Signed.Roles[role].KeyIDs, k.ID()) ids = append(ids, k.ID()) } tr.Root.Dirty = true // also, whichever role was switched out needs to be re-signed // root has already been marked dirty. switch role { case data.CanonicalSnapshotRole: if tr.Snapshot != nil { tr.Snapshot.Dirty = true } case data.CanonicalTargetsRole: if target, ok := tr.Targets[data.CanonicalTargetsRole]; ok { target.Dirty = true } case data.CanonicalTimestampRole: if tr.Timestamp != nil { tr.Timestamp.Dirty = true } } return nil }
go
func (tr *Repo) AddBaseKeys(role data.RoleName, keys ...data.PublicKey) error { if tr.Root == nil { return ErrNotLoaded{Role: data.CanonicalRootRole} } ids := []string{} for _, k := range keys { // Store only the public portion tr.Root.Signed.Keys[k.ID()] = k tr.Root.Signed.Roles[role].KeyIDs = append(tr.Root.Signed.Roles[role].KeyIDs, k.ID()) ids = append(ids, k.ID()) } tr.Root.Dirty = true // also, whichever role was switched out needs to be re-signed // root has already been marked dirty. switch role { case data.CanonicalSnapshotRole: if tr.Snapshot != nil { tr.Snapshot.Dirty = true } case data.CanonicalTargetsRole: if target, ok := tr.Targets[data.CanonicalTargetsRole]; ok { target.Dirty = true } case data.CanonicalTimestampRole: if tr.Timestamp != nil { tr.Timestamp.Dirty = true } } return nil }
[ "func", "(", "tr", "*", "Repo", ")", "AddBaseKeys", "(", "role", "data", ".", "RoleName", ",", "keys", "...", "data", ".", "PublicKey", ")", "error", "{", "if", "tr", ".", "Root", "==", "nil", "{", "return", "ErrNotLoaded", "{", "Role", ":", "data", ...
// AddBaseKeys is used to add keys to the role in root.json
[ "AddBaseKeys", "is", "used", "to", "add", "keys", "to", "the", "role", "in", "root", ".", "json" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L84-L114
train
theupdateframework/notary
tuf/tuf.go
ReplaceBaseKeys
func (tr *Repo) ReplaceBaseKeys(role data.RoleName, keys ...data.PublicKey) error { r, err := tr.GetBaseRole(role) if err != nil { return err } err = tr.RemoveBaseKeys(role, r.ListKeyIDs()...) if err != nil { return err } return tr.AddBaseKeys(role, keys...) }
go
func (tr *Repo) ReplaceBaseKeys(role data.RoleName, keys ...data.PublicKey) error { r, err := tr.GetBaseRole(role) if err != nil { return err } err = tr.RemoveBaseKeys(role, r.ListKeyIDs()...) if err != nil { return err } return tr.AddBaseKeys(role, keys...) }
[ "func", "(", "tr", "*", "Repo", ")", "ReplaceBaseKeys", "(", "role", "data", ".", "RoleName", ",", "keys", "...", "data", ".", "PublicKey", ")", "error", "{", "r", ",", "err", ":=", "tr", ".", "GetBaseRole", "(", "role", ")", "\n", "if", "err", "!=...
// ReplaceBaseKeys is used to replace all keys for the given role with the new keys
[ "ReplaceBaseKeys", "is", "used", "to", "replace", "all", "keys", "for", "the", "given", "role", "with", "the", "new", "keys" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L117-L127
train
theupdateframework/notary
tuf/tuf.go
RemoveBaseKeys
func (tr *Repo) RemoveBaseKeys(role data.RoleName, keyIDs ...string) error { if tr.Root == nil { return ErrNotLoaded{Role: data.CanonicalRootRole} } var keep []string toDelete := make(map[string]struct{}) emptyStruct := struct{}{} // remove keys from specified role for _, k := range keyIDs { toDelete[k] = emptyStruct } oldKeyIDs := tr.Root.Signed.Roles[role].KeyIDs for _, rk := range oldKeyIDs { if _, ok := toDelete[rk]; !ok { keep = append(keep, rk) } } tr.Root.Signed.Roles[role].KeyIDs = keep // also, whichever role had keys removed needs to be re-signed // root has already been marked dirty. tr.markRoleDirty(role) // determine which keys are no longer in use by any roles for roleName, r := range tr.Root.Signed.Roles { if roleName == role { continue } for _, rk := range r.KeyIDs { if _, ok := toDelete[rk]; ok { delete(toDelete, rk) } } } // Remove keys no longer in use by any roles, except for root keys. // Root private keys must be kept in tr.cryptoService to be able to sign // for rotation, and root certificates must be kept in tr.Root.SignedKeys // because we are not necessarily storing them elsewhere (tuf.Repo does not // depend on certs.Manager, that is an upper layer), and without storing // the certificates in their x509 form we are not able to do the // util.CanonicalKeyID conversion. if role != data.CanonicalRootRole { for k := range toDelete { delete(tr.Root.Signed.Keys, k) tr.cryptoService.RemoveKey(k) } } tr.Root.Dirty = true return nil }
go
func (tr *Repo) RemoveBaseKeys(role data.RoleName, keyIDs ...string) error { if tr.Root == nil { return ErrNotLoaded{Role: data.CanonicalRootRole} } var keep []string toDelete := make(map[string]struct{}) emptyStruct := struct{}{} // remove keys from specified role for _, k := range keyIDs { toDelete[k] = emptyStruct } oldKeyIDs := tr.Root.Signed.Roles[role].KeyIDs for _, rk := range oldKeyIDs { if _, ok := toDelete[rk]; !ok { keep = append(keep, rk) } } tr.Root.Signed.Roles[role].KeyIDs = keep // also, whichever role had keys removed needs to be re-signed // root has already been marked dirty. tr.markRoleDirty(role) // determine which keys are no longer in use by any roles for roleName, r := range tr.Root.Signed.Roles { if roleName == role { continue } for _, rk := range r.KeyIDs { if _, ok := toDelete[rk]; ok { delete(toDelete, rk) } } } // Remove keys no longer in use by any roles, except for root keys. // Root private keys must be kept in tr.cryptoService to be able to sign // for rotation, and root certificates must be kept in tr.Root.SignedKeys // because we are not necessarily storing them elsewhere (tuf.Repo does not // depend on certs.Manager, that is an upper layer), and without storing // the certificates in their x509 form we are not able to do the // util.CanonicalKeyID conversion. if role != data.CanonicalRootRole { for k := range toDelete { delete(tr.Root.Signed.Keys, k) tr.cryptoService.RemoveKey(k) } } tr.Root.Dirty = true return nil }
[ "func", "(", "tr", "*", "Repo", ")", "RemoveBaseKeys", "(", "role", "data", ".", "RoleName", ",", "keyIDs", "...", "string", ")", "error", "{", "if", "tr", ".", "Root", "==", "nil", "{", "return", "ErrNotLoaded", "{", "Role", ":", "data", ".", "Canon...
// RemoveBaseKeys is used to remove keys from the roles in root.json
[ "RemoveBaseKeys", "is", "used", "to", "remove", "keys", "from", "the", "roles", "in", "root", ".", "json" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L130-L183
train
theupdateframework/notary
tuf/tuf.go
GetBaseRole
func (tr *Repo) GetBaseRole(name data.RoleName) (data.BaseRole, error) { if !data.ValidRole(name) { return data.BaseRole{}, data.ErrInvalidRole{Role: name, Reason: "invalid base role name"} } if tr.Root == nil { return data.BaseRole{}, ErrNotLoaded{data.CanonicalRootRole} } // Find the role data public keys for the base role from TUF metadata baseRole, err := tr.Root.BuildBaseRole(name) if err != nil { return data.BaseRole{}, err } return baseRole, nil }
go
func (tr *Repo) GetBaseRole(name data.RoleName) (data.BaseRole, error) { if !data.ValidRole(name) { return data.BaseRole{}, data.ErrInvalidRole{Role: name, Reason: "invalid base role name"} } if tr.Root == nil { return data.BaseRole{}, ErrNotLoaded{data.CanonicalRootRole} } // Find the role data public keys for the base role from TUF metadata baseRole, err := tr.Root.BuildBaseRole(name) if err != nil { return data.BaseRole{}, err } return baseRole, nil }
[ "func", "(", "tr", "*", "Repo", ")", "GetBaseRole", "(", "name", "data", ".", "RoleName", ")", "(", "data", ".", "BaseRole", ",", "error", ")", "{", "if", "!", "data", ".", "ValidRole", "(", "name", ")", "{", "return", "data", ".", "BaseRole", "{",...
// GetBaseRole gets a base role from this repo's metadata
[ "GetBaseRole", "gets", "a", "base", "role", "from", "this", "repo", "s", "metadata" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L203-L217
train
theupdateframework/notary
tuf/tuf.go
GetDelegationRole
func (tr *Repo) GetDelegationRole(name data.RoleName) (data.DelegationRole, error) { if !data.IsDelegation(name) { return data.DelegationRole{}, data.ErrInvalidRole{Role: name, Reason: "invalid delegation name"} } if tr.Root == nil { return data.DelegationRole{}, ErrNotLoaded{data.CanonicalRootRole} } _, ok := tr.Root.Signed.Roles[data.CanonicalTargetsRole] if !ok { return data.DelegationRole{}, ErrNotLoaded{data.CanonicalTargetsRole} } // Traverse target metadata, down to delegation itself // Get all public keys for the base role from TUF metadata _, ok = tr.Targets[data.CanonicalTargetsRole] if !ok { return data.DelegationRole{}, ErrNotLoaded{data.CanonicalTargetsRole} } // Start with top level roles in targets. Walk the chain of ancestors // until finding the desired role, or we run out of targets files to search. var foundRole *data.DelegationRole buildDelegationRoleVisitor := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { // Try to find the delegation and build a DelegationRole structure for _, role := range tgt.Signed.Delegations.Roles { if role.Name == name { delgRole, err := tgt.BuildDelegationRole(name) if err != nil { return err } // Check all public key certificates in the role for expiry // Currently we do not reject expired delegation keys but warn if they might expire soon or have already for _, pubKey := range delgRole.Keys { certFromKey, err := utils.LoadCertFromPEM(pubKey.Public()) if err != nil { continue } //Don't check the delegation certificate expiry once added, use the TUF role expiry instead if err := utils.ValidateCertificate(certFromKey, false); err != nil { return err } } foundRole = &delgRole return StopWalk{} } } return nil } // Walk to the parent of this delegation, since that is where its role metadata exists err := tr.WalkTargets("", name.Parent(), buildDelegationRoleVisitor) if err != nil { return data.DelegationRole{}, err } // We never found the delegation. In the context of this repo it is considered // invalid. N.B. it may be that it existed at one point but an ancestor has since // been modified/removed. if foundRole == nil { return data.DelegationRole{}, data.ErrInvalidRole{Role: name, Reason: "delegation does not exist"} } return *foundRole, nil }
go
func (tr *Repo) GetDelegationRole(name data.RoleName) (data.DelegationRole, error) { if !data.IsDelegation(name) { return data.DelegationRole{}, data.ErrInvalidRole{Role: name, Reason: "invalid delegation name"} } if tr.Root == nil { return data.DelegationRole{}, ErrNotLoaded{data.CanonicalRootRole} } _, ok := tr.Root.Signed.Roles[data.CanonicalTargetsRole] if !ok { return data.DelegationRole{}, ErrNotLoaded{data.CanonicalTargetsRole} } // Traverse target metadata, down to delegation itself // Get all public keys for the base role from TUF metadata _, ok = tr.Targets[data.CanonicalTargetsRole] if !ok { return data.DelegationRole{}, ErrNotLoaded{data.CanonicalTargetsRole} } // Start with top level roles in targets. Walk the chain of ancestors // until finding the desired role, or we run out of targets files to search. var foundRole *data.DelegationRole buildDelegationRoleVisitor := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { // Try to find the delegation and build a DelegationRole structure for _, role := range tgt.Signed.Delegations.Roles { if role.Name == name { delgRole, err := tgt.BuildDelegationRole(name) if err != nil { return err } // Check all public key certificates in the role for expiry // Currently we do not reject expired delegation keys but warn if they might expire soon or have already for _, pubKey := range delgRole.Keys { certFromKey, err := utils.LoadCertFromPEM(pubKey.Public()) if err != nil { continue } //Don't check the delegation certificate expiry once added, use the TUF role expiry instead if err := utils.ValidateCertificate(certFromKey, false); err != nil { return err } } foundRole = &delgRole return StopWalk{} } } return nil } // Walk to the parent of this delegation, since that is where its role metadata exists err := tr.WalkTargets("", name.Parent(), buildDelegationRoleVisitor) if err != nil { return data.DelegationRole{}, err } // We never found the delegation. In the context of this repo it is considered // invalid. N.B. it may be that it existed at one point but an ancestor has since // been modified/removed. if foundRole == nil { return data.DelegationRole{}, data.ErrInvalidRole{Role: name, Reason: "delegation does not exist"} } return *foundRole, nil }
[ "func", "(", "tr", "*", "Repo", ")", "GetDelegationRole", "(", "name", "data", ".", "RoleName", ")", "(", "data", ".", "DelegationRole", ",", "error", ")", "{", "if", "!", "data", ".", "IsDelegation", "(", "name", ")", "{", "return", "data", ".", "De...
// GetDelegationRole gets a delegation role from this repo's metadata, walking from the targets role down to the delegation itself
[ "GetDelegationRole", "gets", "a", "delegation", "role", "from", "this", "repo", "s", "metadata", "walking", "from", "the", "targets", "role", "down", "to", "the", "delegation", "itself" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L220-L282
train
theupdateframework/notary
tuf/tuf.go
GetAllLoadedRoles
func (tr *Repo) GetAllLoadedRoles() []*data.Role { var res []*data.Role if tr.Root == nil { // if root isn't loaded, we should consider we have no loaded roles because we can't // trust any other state that might be present return res } for name, rr := range tr.Root.Signed.Roles { res = append(res, &data.Role{ RootRole: *rr, Name: name, }) } for _, delegate := range tr.Targets { for _, r := range delegate.Signed.Delegations.Roles { res = append(res, r) } } return res }
go
func (tr *Repo) GetAllLoadedRoles() []*data.Role { var res []*data.Role if tr.Root == nil { // if root isn't loaded, we should consider we have no loaded roles because we can't // trust any other state that might be present return res } for name, rr := range tr.Root.Signed.Roles { res = append(res, &data.Role{ RootRole: *rr, Name: name, }) } for _, delegate := range tr.Targets { for _, r := range delegate.Signed.Delegations.Roles { res = append(res, r) } } return res }
[ "func", "(", "tr", "*", "Repo", ")", "GetAllLoadedRoles", "(", ")", "[", "]", "*", "data", ".", "Role", "{", "var", "res", "[", "]", "*", "data", ".", "Role", "\n", "if", "tr", ".", "Root", "==", "nil", "{", "return", "res", "\n", "}", "\n", ...
// GetAllLoadedRoles returns a list of all role entries loaded in this TUF repo, could be empty
[ "GetAllLoadedRoles", "returns", "a", "list", "of", "all", "role", "entries", "loaded", "in", "this", "TUF", "repo", "could", "be", "empty" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L285-L304
train
theupdateframework/notary
tuf/tuf.go
delegationUpdateVisitor
func delegationUpdateVisitor(roleName data.RoleName, addKeys data.KeyList, removeKeys, addPaths, removePaths []string, clearAllPaths bool, newThreshold int) walkVisitorFunc { return func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { var err error // Validate the changes underneath this restricted validRole for adding paths, reject invalid path additions if len(addPaths) != len(data.RestrictDelegationPathPrefixes(validRole.Paths, addPaths)) { return data.ErrInvalidRole{Role: roleName, Reason: "invalid paths to add to role"} } // Try to find the delegation and amend it using our changelist var delgRole *data.Role for _, role := range tgt.Signed.Delegations.Roles { if role.Name == roleName { // Make a copy and operate on this role until we validate the changes keyIDCopy := make([]string, len(role.KeyIDs)) copy(keyIDCopy, role.KeyIDs) pathsCopy := make([]string, len(role.Paths)) copy(pathsCopy, role.Paths) delgRole = &data.Role{ RootRole: data.RootRole{ KeyIDs: keyIDCopy, Threshold: role.Threshold, }, Name: role.Name, Paths: pathsCopy, } delgRole.RemovePaths(removePaths) if clearAllPaths { delgRole.Paths = []string{} } delgRole.AddPaths(addPaths) delgRole.RemoveKeys(removeKeys) break } } // We didn't find the role earlier, so create it. if addKeys == nil { addKeys = data.KeyList{} // initialize to empty list if necessary so calling .IDs() below won't panic } if delgRole == nil { delgRole, err = data.NewRole(roleName, newThreshold, addKeys.IDs(), addPaths) if err != nil { return err } } // Add the key IDs to the role and the keys themselves to the parent for _, k := range addKeys { if !utils.StrSliceContains(delgRole.KeyIDs, k.ID()) { delgRole.KeyIDs = append(delgRole.KeyIDs, k.ID()) } } // Make sure we have a valid role still if len(delgRole.KeyIDs) < delgRole.Threshold { logrus.Warnf("role %s has fewer keys than its threshold of %d; it will not be usable until keys are added to it", delgRole.Name, delgRole.Threshold) } // NOTE: this closure CANNOT error after this point, as we've committed to editing the SignedTargets metadata in the repo object. // Any errors related to updating this delegation must occur before this point. // If all of our changes were valid, we should edit the actual SignedTargets to match our copy for _, k := range addKeys { tgt.Signed.Delegations.Keys[k.ID()] = k } foundAt := utils.FindRoleIndex(tgt.Signed.Delegations.Roles, delgRole.Name) if foundAt < 0 { tgt.Signed.Delegations.Roles = append(tgt.Signed.Delegations.Roles, delgRole) } else { tgt.Signed.Delegations.Roles[foundAt] = delgRole } tgt.Dirty = true utils.RemoveUnusedKeys(tgt) return StopWalk{} } }
go
func delegationUpdateVisitor(roleName data.RoleName, addKeys data.KeyList, removeKeys, addPaths, removePaths []string, clearAllPaths bool, newThreshold int) walkVisitorFunc { return func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { var err error // Validate the changes underneath this restricted validRole for adding paths, reject invalid path additions if len(addPaths) != len(data.RestrictDelegationPathPrefixes(validRole.Paths, addPaths)) { return data.ErrInvalidRole{Role: roleName, Reason: "invalid paths to add to role"} } // Try to find the delegation and amend it using our changelist var delgRole *data.Role for _, role := range tgt.Signed.Delegations.Roles { if role.Name == roleName { // Make a copy and operate on this role until we validate the changes keyIDCopy := make([]string, len(role.KeyIDs)) copy(keyIDCopy, role.KeyIDs) pathsCopy := make([]string, len(role.Paths)) copy(pathsCopy, role.Paths) delgRole = &data.Role{ RootRole: data.RootRole{ KeyIDs: keyIDCopy, Threshold: role.Threshold, }, Name: role.Name, Paths: pathsCopy, } delgRole.RemovePaths(removePaths) if clearAllPaths { delgRole.Paths = []string{} } delgRole.AddPaths(addPaths) delgRole.RemoveKeys(removeKeys) break } } // We didn't find the role earlier, so create it. if addKeys == nil { addKeys = data.KeyList{} // initialize to empty list if necessary so calling .IDs() below won't panic } if delgRole == nil { delgRole, err = data.NewRole(roleName, newThreshold, addKeys.IDs(), addPaths) if err != nil { return err } } // Add the key IDs to the role and the keys themselves to the parent for _, k := range addKeys { if !utils.StrSliceContains(delgRole.KeyIDs, k.ID()) { delgRole.KeyIDs = append(delgRole.KeyIDs, k.ID()) } } // Make sure we have a valid role still if len(delgRole.KeyIDs) < delgRole.Threshold { logrus.Warnf("role %s has fewer keys than its threshold of %d; it will not be usable until keys are added to it", delgRole.Name, delgRole.Threshold) } // NOTE: this closure CANNOT error after this point, as we've committed to editing the SignedTargets metadata in the repo object. // Any errors related to updating this delegation must occur before this point. // If all of our changes were valid, we should edit the actual SignedTargets to match our copy for _, k := range addKeys { tgt.Signed.Delegations.Keys[k.ID()] = k } foundAt := utils.FindRoleIndex(tgt.Signed.Delegations.Roles, delgRole.Name) if foundAt < 0 { tgt.Signed.Delegations.Roles = append(tgt.Signed.Delegations.Roles, delgRole) } else { tgt.Signed.Delegations.Roles[foundAt] = delgRole } tgt.Dirty = true utils.RemoveUnusedKeys(tgt) return StopWalk{} } }
[ "func", "delegationUpdateVisitor", "(", "roleName", "data", ".", "RoleName", ",", "addKeys", "data", ".", "KeyList", ",", "removeKeys", ",", "addPaths", ",", "removePaths", "[", "]", "string", ",", "clearAllPaths", "bool", ",", "newThreshold", "int", ")", "wal...
// Walk to parent, and either create or update this delegation. We can only create a new delegation if we're given keys // Ensure all updates are valid, by checking against parent ancestor paths and ensuring the keys meet the role threshold.
[ "Walk", "to", "parent", "and", "either", "create", "or", "update", "this", "delegation", ".", "We", "can", "only", "create", "a", "new", "delegation", "if", "we", "re", "given", "keys", "Ensure", "all", "updates", "are", "valid", "by", "checking", "against...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L308-L378
train
theupdateframework/notary
tuf/tuf.go
UpdateDelegationPaths
func (tr *Repo) UpdateDelegationPaths(roleName data.RoleName, addPaths, removePaths []string, clearPaths bool) error { if !data.IsDelegation(roleName) { return data.ErrInvalidRole{Role: roleName, Reason: "not a valid delegated role"} } parent := roleName.Parent() if err := tr.VerifyCanSign(parent); err != nil { return err } // check the parent role's metadata _, ok := tr.Targets[parent] if !ok { // the parent targetfile may not exist yet // if not, this is an error because a delegation must exist to edit only paths return data.ErrInvalidRole{Role: roleName, Reason: "no valid delegated role exists"} } // Walk to the parent of this delegation, since that is where its role metadata exists // We do not have to verify that the walker reached its desired role in this scenario // since we've already done another walk to the parent role in VerifyCanSign err := tr.WalkTargets("", parent, delegationUpdateVisitor(roleName, data.KeyList{}, []string{}, addPaths, removePaths, clearPaths, notary.MinThreshold)) if err != nil { return err } return nil }
go
func (tr *Repo) UpdateDelegationPaths(roleName data.RoleName, addPaths, removePaths []string, clearPaths bool) error { if !data.IsDelegation(roleName) { return data.ErrInvalidRole{Role: roleName, Reason: "not a valid delegated role"} } parent := roleName.Parent() if err := tr.VerifyCanSign(parent); err != nil { return err } // check the parent role's metadata _, ok := tr.Targets[parent] if !ok { // the parent targetfile may not exist yet // if not, this is an error because a delegation must exist to edit only paths return data.ErrInvalidRole{Role: roleName, Reason: "no valid delegated role exists"} } // Walk to the parent of this delegation, since that is where its role metadata exists // We do not have to verify that the walker reached its desired role in this scenario // since we've already done another walk to the parent role in VerifyCanSign err := tr.WalkTargets("", parent, delegationUpdateVisitor(roleName, data.KeyList{}, []string{}, addPaths, removePaths, clearPaths, notary.MinThreshold)) if err != nil { return err } return nil }
[ "func", "(", "tr", "*", "Repo", ")", "UpdateDelegationPaths", "(", "roleName", "data", ".", "RoleName", ",", "addPaths", ",", "removePaths", "[", "]", "string", ",", "clearPaths", "bool", ")", "error", "{", "if", "!", "data", ".", "IsDelegation", "(", "r...
// UpdateDelegationPaths updates the appropriate delegation's paths. // It is not allowed to create a new delegation.
[ "UpdateDelegationPaths", "updates", "the", "appropriate", "delegation", "s", "paths", ".", "It", "is", "not", "allowed", "to", "create", "a", "new", "delegation", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L482-L507
train
theupdateframework/notary
tuf/tuf.go
DeleteDelegation
func (tr *Repo) DeleteDelegation(roleName data.RoleName) error { if !data.IsDelegation(roleName) { return data.ErrInvalidRole{Role: roleName, Reason: "not a valid delegated role"} } parent := roleName.Parent() if err := tr.VerifyCanSign(parent); err != nil { return err } // delete delegated data from Targets map and Snapshot - if they don't // exist, these are no-op delete(tr.Targets, roleName) tr.Snapshot.DeleteMeta(roleName) p, ok := tr.Targets[parent] if !ok { // if there is no parent metadata (the role exists though), then this // is as good as done. return nil } foundAt := utils.FindRoleIndex(p.Signed.Delegations.Roles, roleName) if foundAt >= 0 { var roles []*data.Role // slice out deleted role roles = append(roles, p.Signed.Delegations.Roles[:foundAt]...) if foundAt+1 < len(p.Signed.Delegations.Roles) { roles = append(roles, p.Signed.Delegations.Roles[foundAt+1:]...) } p.Signed.Delegations.Roles = roles utils.RemoveUnusedKeys(p) p.Dirty = true } // if the role wasn't found, it's a good as deleted return nil }
go
func (tr *Repo) DeleteDelegation(roleName data.RoleName) error { if !data.IsDelegation(roleName) { return data.ErrInvalidRole{Role: roleName, Reason: "not a valid delegated role"} } parent := roleName.Parent() if err := tr.VerifyCanSign(parent); err != nil { return err } // delete delegated data from Targets map and Snapshot - if they don't // exist, these are no-op delete(tr.Targets, roleName) tr.Snapshot.DeleteMeta(roleName) p, ok := tr.Targets[parent] if !ok { // if there is no parent metadata (the role exists though), then this // is as good as done. return nil } foundAt := utils.FindRoleIndex(p.Signed.Delegations.Roles, roleName) if foundAt >= 0 { var roles []*data.Role // slice out deleted role roles = append(roles, p.Signed.Delegations.Roles[:foundAt]...) if foundAt+1 < len(p.Signed.Delegations.Roles) { roles = append(roles, p.Signed.Delegations.Roles[foundAt+1:]...) } p.Signed.Delegations.Roles = roles utils.RemoveUnusedKeys(p) p.Dirty = true } // if the role wasn't found, it's a good as deleted return nil }
[ "func", "(", "tr", "*", "Repo", ")", "DeleteDelegation", "(", "roleName", "data", ".", "RoleName", ")", "error", "{", "if", "!", "data", ".", "IsDelegation", "(", "roleName", ")", "{", "return", "data", ".", "ErrInvalidRole", "{", "Role", ":", "roleName"...
// DeleteDelegation removes a delegated targets role from its parent // targets object. It also deletes the delegation from the snapshot. // DeleteDelegation will only make use of the role Name field.
[ "DeleteDelegation", "removes", "a", "delegated", "targets", "role", "from", "its", "parent", "targets", "object", ".", "It", "also", "deletes", "the", "delegation", "from", "the", "snapshot", ".", "DeleteDelegation", "will", "only", "make", "use", "of", "the", ...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L512-L551
train
theupdateframework/notary
tuf/tuf.go
InitRoot
func (tr *Repo) InitRoot(root, timestamp, snapshot, targets data.BaseRole, consistent bool) error { rootRoles := make(map[data.RoleName]*data.RootRole) rootKeys := make(map[string]data.PublicKey) for _, r := range []data.BaseRole{root, timestamp, snapshot, targets} { rootRoles[r.Name] = &data.RootRole{ Threshold: r.Threshold, KeyIDs: r.ListKeyIDs(), } for kid, k := range r.Keys { rootKeys[kid] = k } } r, err := data.NewRoot(rootKeys, rootRoles, consistent) if err != nil { return err } tr.Root = r tr.originalRootRole = root return nil }
go
func (tr *Repo) InitRoot(root, timestamp, snapshot, targets data.BaseRole, consistent bool) error { rootRoles := make(map[data.RoleName]*data.RootRole) rootKeys := make(map[string]data.PublicKey) for _, r := range []data.BaseRole{root, timestamp, snapshot, targets} { rootRoles[r.Name] = &data.RootRole{ Threshold: r.Threshold, KeyIDs: r.ListKeyIDs(), } for kid, k := range r.Keys { rootKeys[kid] = k } } r, err := data.NewRoot(rootKeys, rootRoles, consistent) if err != nil { return err } tr.Root = r tr.originalRootRole = root return nil }
[ "func", "(", "tr", "*", "Repo", ")", "InitRoot", "(", "root", ",", "timestamp", ",", "snapshot", ",", "targets", "data", ".", "BaseRole", ",", "consistent", "bool", ")", "error", "{", "rootRoles", ":=", "make", "(", "map", "[", "data", ".", "RoleName",...
// InitRoot initializes an empty root file with the 4 core roles passed to the // method, and the consistent flag.
[ "InitRoot", "initializes", "an", "empty", "root", "file", "with", "the", "4", "core", "roles", "passed", "to", "the", "method", "and", "the", "consistent", "flag", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L555-L575
train
theupdateframework/notary
tuf/tuf.go
InitTargets
func (tr *Repo) InitTargets(role data.RoleName) (*data.SignedTargets, error) { if !data.IsDelegation(role) && role != data.CanonicalTargetsRole { return nil, data.ErrInvalidRole{ Role: role, Reason: fmt.Sprintf("role is not a valid targets role name: %s", role.String()), } } targets := data.NewTargets() tr.Targets[role] = targets return targets, nil }
go
func (tr *Repo) InitTargets(role data.RoleName) (*data.SignedTargets, error) { if !data.IsDelegation(role) && role != data.CanonicalTargetsRole { return nil, data.ErrInvalidRole{ Role: role, Reason: fmt.Sprintf("role is not a valid targets role name: %s", role.String()), } } targets := data.NewTargets() tr.Targets[role] = targets return targets, nil }
[ "func", "(", "tr", "*", "Repo", ")", "InitTargets", "(", "role", "data", ".", "RoleName", ")", "(", "*", "data", ".", "SignedTargets", ",", "error", ")", "{", "if", "!", "data", ".", "IsDelegation", "(", "role", ")", "&&", "role", "!=", "data", "."...
// InitTargets initializes an empty targets, and returns the new empty target
[ "InitTargets", "initializes", "an", "empty", "targets", "and", "returns", "the", "new", "empty", "target" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L578-L588
train
theupdateframework/notary
tuf/tuf.go
InitSnapshot
func (tr *Repo) InitSnapshot() error { if tr.Root == nil { return ErrNotLoaded{Role: data.CanonicalRootRole} } root, err := tr.Root.ToSigned() if err != nil { return err } if _, ok := tr.Targets[data.CanonicalTargetsRole]; !ok { return ErrNotLoaded{Role: data.CanonicalTargetsRole} } targets, err := tr.Targets[data.CanonicalTargetsRole].ToSigned() if err != nil { return err } snapshot, err := data.NewSnapshot(root, targets) if err != nil { return err } tr.Snapshot = snapshot return nil }
go
func (tr *Repo) InitSnapshot() error { if tr.Root == nil { return ErrNotLoaded{Role: data.CanonicalRootRole} } root, err := tr.Root.ToSigned() if err != nil { return err } if _, ok := tr.Targets[data.CanonicalTargetsRole]; !ok { return ErrNotLoaded{Role: data.CanonicalTargetsRole} } targets, err := tr.Targets[data.CanonicalTargetsRole].ToSigned() if err != nil { return err } snapshot, err := data.NewSnapshot(root, targets) if err != nil { return err } tr.Snapshot = snapshot return nil }
[ "func", "(", "tr", "*", "Repo", ")", "InitSnapshot", "(", ")", "error", "{", "if", "tr", ".", "Root", "==", "nil", "{", "return", "ErrNotLoaded", "{", "Role", ":", "data", ".", "CanonicalRootRole", "}", "\n", "}", "\n", "root", ",", "err", ":=", "t...
// InitSnapshot initializes a snapshot based on the current root and targets
[ "InitSnapshot", "initializes", "a", "snapshot", "based", "on", "the", "current", "root", "and", "targets" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L591-L613
train
theupdateframework/notary
tuf/tuf.go
InitTimestamp
func (tr *Repo) InitTimestamp() error { snap, err := tr.Snapshot.ToSigned() if err != nil { return err } timestamp, err := data.NewTimestamp(snap) if err != nil { return err } tr.Timestamp = timestamp return nil }
go
func (tr *Repo) InitTimestamp() error { snap, err := tr.Snapshot.ToSigned() if err != nil { return err } timestamp, err := data.NewTimestamp(snap) if err != nil { return err } tr.Timestamp = timestamp return nil }
[ "func", "(", "tr", "*", "Repo", ")", "InitTimestamp", "(", ")", "error", "{", "snap", ",", "err", ":=", "tr", ".", "Snapshot", ".", "ToSigned", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "timestamp", ",", "er...
// InitTimestamp initializes a timestamp based on the current snapshot
[ "InitTimestamp", "initializes", "a", "timestamp", "based", "on", "the", "current", "snapshot" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L616-L628
train
theupdateframework/notary
tuf/tuf.go
TargetMeta
func (tr Repo) TargetMeta(role data.RoleName, path string) *data.FileMeta { if t, ok := tr.Targets[role]; ok { if m, ok := t.Signed.Targets[path]; ok { return &m } } return nil }
go
func (tr Repo) TargetMeta(role data.RoleName, path string) *data.FileMeta { if t, ok := tr.Targets[role]; ok { if m, ok := t.Signed.Targets[path]; ok { return &m } } return nil }
[ "func", "(", "tr", "Repo", ")", "TargetMeta", "(", "role", "data", ".", "RoleName", ",", "path", "string", ")", "*", "data", ".", "FileMeta", "{", "if", "t", ",", "ok", ":=", "tr", ".", "Targets", "[", "role", "]", ";", "ok", "{", "if", "m", ",...
// TargetMeta returns the FileMeta entry for the given path in the // targets file associated with the given role. This may be nil if // the target isn't found in the targets file.
[ "TargetMeta", "returns", "the", "FileMeta", "entry", "for", "the", "given", "path", "in", "the", "targets", "file", "associated", "with", "the", "given", "role", ".", "This", "may", "be", "nil", "if", "the", "target", "isn", "t", "found", "in", "the", "t...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L633-L640
train
theupdateframework/notary
tuf/tuf.go
TargetDelegations
func (tr Repo) TargetDelegations(role data.RoleName, path string) []*data.Role { var roles []*data.Role if t, ok := tr.Targets[role]; ok { for _, r := range t.Signed.Delegations.Roles { if r.CheckPaths(path) { roles = append(roles, r) } } } return roles }
go
func (tr Repo) TargetDelegations(role data.RoleName, path string) []*data.Role { var roles []*data.Role if t, ok := tr.Targets[role]; ok { for _, r := range t.Signed.Delegations.Roles { if r.CheckPaths(path) { roles = append(roles, r) } } } return roles }
[ "func", "(", "tr", "Repo", ")", "TargetDelegations", "(", "role", "data", ".", "RoleName", ",", "path", "string", ")", "[", "]", "*", "data", ".", "Role", "{", "var", "roles", "[", "]", "*", "data", ".", "Role", "\n", "if", "t", ",", "ok", ":=", ...
// TargetDelegations returns a slice of Roles that are valid publishers // for the target path provided.
[ "TargetDelegations", "returns", "a", "slice", "of", "Roles", "that", "are", "valid", "publishers", "for", "the", "target", "path", "provided", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L644-L654
train
theupdateframework/notary
tuf/tuf.go
VerifyCanSign
func (tr *Repo) VerifyCanSign(roleName data.RoleName) error { var ( role data.BaseRole err error canonicalKeyIDs []string ) // we only need the BaseRole part of a delegation because we're just // checking KeyIDs if data.IsDelegation(roleName) { r, err := tr.GetDelegationRole(roleName) if err != nil { return err } role = r.BaseRole } else { role, err = tr.GetBaseRole(roleName) } if err != nil { return data.ErrInvalidRole{Role: roleName, Reason: "does not exist"} } for keyID, k := range role.Keys { check := []string{keyID} if canonicalID, err := utils.CanonicalKeyID(k); err == nil { check = append(check, canonicalID) canonicalKeyIDs = append(canonicalKeyIDs, canonicalID) } for _, id := range check { p, _, err := tr.cryptoService.GetPrivateKey(id) if err == nil && p != nil { return nil } } } return signed.ErrNoKeys{KeyIDs: canonicalKeyIDs} }
go
func (tr *Repo) VerifyCanSign(roleName data.RoleName) error { var ( role data.BaseRole err error canonicalKeyIDs []string ) // we only need the BaseRole part of a delegation because we're just // checking KeyIDs if data.IsDelegation(roleName) { r, err := tr.GetDelegationRole(roleName) if err != nil { return err } role = r.BaseRole } else { role, err = tr.GetBaseRole(roleName) } if err != nil { return data.ErrInvalidRole{Role: roleName, Reason: "does not exist"} } for keyID, k := range role.Keys { check := []string{keyID} if canonicalID, err := utils.CanonicalKeyID(k); err == nil { check = append(check, canonicalID) canonicalKeyIDs = append(canonicalKeyIDs, canonicalID) } for _, id := range check { p, _, err := tr.cryptoService.GetPrivateKey(id) if err == nil && p != nil { return nil } } } return signed.ErrNoKeys{KeyIDs: canonicalKeyIDs} }
[ "func", "(", "tr", "*", "Repo", ")", "VerifyCanSign", "(", "roleName", "data", ".", "RoleName", ")", "error", "{", "var", "(", "role", "data", ".", "BaseRole", "\n", "err", "error", "\n", "canonicalKeyIDs", "[", "]", "string", "\n", ")", "\n", "if", ...
// VerifyCanSign returns nil if the role exists and we have at least one // signing key for the role, false otherwise. This does not check that we have // enough signing keys to meet the threshold, since we want to support the use // case of multiple signers for a role. It returns an error if the role doesn't // exist or if there are no signing keys.
[ "VerifyCanSign", "returns", "nil", "if", "the", "role", "exists", "and", "we", "have", "at", "least", "one", "signing", "key", "for", "the", "role", "false", "otherwise", ".", "This", "does", "not", "check", "that", "we", "have", "enough", "signing", "keys...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L661-L696
train
theupdateframework/notary
tuf/tuf.go
isValidPath
func isValidPath(candidatePath string, delgRole data.DelegationRole) bool { return candidatePath == "" || delgRole.CheckPaths(candidatePath) }
go
func isValidPath(candidatePath string, delgRole data.DelegationRole) bool { return candidatePath == "" || delgRole.CheckPaths(candidatePath) }
[ "func", "isValidPath", "(", "candidatePath", "string", ",", "delgRole", "data", ".", "DelegationRole", ")", "bool", "{", "return", "candidatePath", "==", "\"\"", "||", "delgRole", ".", "CheckPaths", "(", "candidatePath", ")", "\n", "}" ]
// helper function that returns whether the delegation Role is valid against the given path // Will return true if given an empty candidatePath
[ "helper", "function", "that", "returns", "whether", "the", "delegation", "Role", "is", "valid", "against", "the", "given", "path", "Will", "return", "true", "if", "given", "an", "empty", "candidatePath" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L771-L773
train
theupdateframework/notary
tuf/tuf.go
AddTargets
func (tr *Repo) AddTargets(role data.RoleName, targets data.Files) (data.Files, error) { cantSignErr := tr.VerifyCanSign(role) if _, ok := cantSignErr.(data.ErrInvalidRole); ok { return nil, cantSignErr } var needSign bool // check existence of the role's metadata _, ok := tr.Targets[role] if !ok { // the targetfile may not exist yet - if not, then create it var err error _, err = tr.InitTargets(role) if err != nil { return nil, err } } addedTargets := make(data.Files) addTargetVisitor := func(targetPath string, targetMeta data.FileMeta) func(*data.SignedTargets, data.DelegationRole) interface{} { return func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { // We've already validated the role's target path in our walk, so just modify the metadata if targetMeta.Equals(tgt.Signed.Targets[targetPath]) { // Also add to our new addedTargets map because this target was "added" successfully addedTargets[targetPath] = targetMeta return StopWalk{} } needSign = true if cantSignErr == nil { tgt.Signed.Targets[targetPath] = targetMeta tgt.Dirty = true // Also add to our new addedTargets map to keep track of every target we've added successfully addedTargets[targetPath] = targetMeta } return StopWalk{} } } // Walk the role tree while validating the target paths, and add all of our targets for path, target := range targets { tr.WalkTargets(path, role, addTargetVisitor(path, target)) if needSign && cantSignErr != nil { return nil, cantSignErr } } if len(addedTargets) != len(targets) { return nil, fmt.Errorf("Could not add all targets") } return nil, nil }
go
func (tr *Repo) AddTargets(role data.RoleName, targets data.Files) (data.Files, error) { cantSignErr := tr.VerifyCanSign(role) if _, ok := cantSignErr.(data.ErrInvalidRole); ok { return nil, cantSignErr } var needSign bool // check existence of the role's metadata _, ok := tr.Targets[role] if !ok { // the targetfile may not exist yet - if not, then create it var err error _, err = tr.InitTargets(role) if err != nil { return nil, err } } addedTargets := make(data.Files) addTargetVisitor := func(targetPath string, targetMeta data.FileMeta) func(*data.SignedTargets, data.DelegationRole) interface{} { return func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { // We've already validated the role's target path in our walk, so just modify the metadata if targetMeta.Equals(tgt.Signed.Targets[targetPath]) { // Also add to our new addedTargets map because this target was "added" successfully addedTargets[targetPath] = targetMeta return StopWalk{} } needSign = true if cantSignErr == nil { tgt.Signed.Targets[targetPath] = targetMeta tgt.Dirty = true // Also add to our new addedTargets map to keep track of every target we've added successfully addedTargets[targetPath] = targetMeta } return StopWalk{} } } // Walk the role tree while validating the target paths, and add all of our targets for path, target := range targets { tr.WalkTargets(path, role, addTargetVisitor(path, target)) if needSign && cantSignErr != nil { return nil, cantSignErr } } if len(addedTargets) != len(targets) { return nil, fmt.Errorf("Could not add all targets") } return nil, nil }
[ "func", "(", "tr", "*", "Repo", ")", "AddTargets", "(", "role", "data", ".", "RoleName", ",", "targets", "data", ".", "Files", ")", "(", "data", ".", "Files", ",", "error", ")", "{", "cantSignErr", ":=", "tr", ".", "VerifyCanSign", "(", "role", ")", ...
// AddTargets will attempt to add the given targets specifically to // the directed role. If the metadata for the role doesn't exist yet, // AddTargets will create one.
[ "AddTargets", "will", "attempt", "to", "add", "the", "given", "targets", "specifically", "to", "the", "directed", "role", ".", "If", "the", "metadata", "for", "the", "role", "doesn", "t", "exist", "yet", "AddTargets", "will", "create", "one", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L778-L826
train
theupdateframework/notary
tuf/tuf.go
UpdateSnapshot
func (tr *Repo) UpdateSnapshot(role data.RoleName, s *data.Signed) error { jsonData, err := json.Marshal(s) if err != nil { return err } meta, err := data.NewFileMeta(bytes.NewReader(jsonData), data.NotaryDefaultHashes...) if err != nil { return err } tr.Snapshot.Signed.Meta[role.String()] = meta tr.Snapshot.Dirty = true return nil }
go
func (tr *Repo) UpdateSnapshot(role data.RoleName, s *data.Signed) error { jsonData, err := json.Marshal(s) if err != nil { return err } meta, err := data.NewFileMeta(bytes.NewReader(jsonData), data.NotaryDefaultHashes...) if err != nil { return err } tr.Snapshot.Signed.Meta[role.String()] = meta tr.Snapshot.Dirty = true return nil }
[ "func", "(", "tr", "*", "Repo", ")", "UpdateSnapshot", "(", "role", "data", ".", "RoleName", ",", "s", "*", "data", ".", "Signed", ")", "error", "{", "jsonData", ",", "err", ":=", "json", ".", "Marshal", "(", "s", ")", "\n", "if", "err", "!=", "n...
// UpdateSnapshot updates the FileMeta for the given role based on the Signed object
[ "UpdateSnapshot", "updates", "the", "FileMeta", "for", "the", "given", "role", "based", "on", "the", "Signed", "object" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L863-L875
train
theupdateframework/notary
tuf/tuf.go
UpdateTimestamp
func (tr *Repo) UpdateTimestamp(s *data.Signed) error { jsonData, err := json.Marshal(s) if err != nil { return err } meta, err := data.NewFileMeta(bytes.NewReader(jsonData), data.NotaryDefaultHashes...) if err != nil { return err } tr.Timestamp.Signed.Meta[data.CanonicalSnapshotRole.String()] = meta tr.Timestamp.Dirty = true return nil }
go
func (tr *Repo) UpdateTimestamp(s *data.Signed) error { jsonData, err := json.Marshal(s) if err != nil { return err } meta, err := data.NewFileMeta(bytes.NewReader(jsonData), data.NotaryDefaultHashes...) if err != nil { return err } tr.Timestamp.Signed.Meta[data.CanonicalSnapshotRole.String()] = meta tr.Timestamp.Dirty = true return nil }
[ "func", "(", "tr", "*", "Repo", ")", "UpdateTimestamp", "(", "s", "*", "data", ".", "Signed", ")", "error", "{", "jsonData", ",", "err", ":=", "json", ".", "Marshal", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}",...
// UpdateTimestamp updates the snapshot meta in the timestamp based on the Signed object
[ "UpdateTimestamp", "updates", "the", "snapshot", "meta", "in", "the", "timestamp", "based", "on", "the", "Signed", "object" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L878-L890
train
theupdateframework/notary
tuf/tuf.go
SignTargets
func (tr *Repo) SignTargets(role data.RoleName, expires time.Time) (*data.Signed, error) { logrus.Debugf("sign targets called for role %s", role) if _, ok := tr.Targets[role]; !ok { return nil, data.ErrInvalidRole{ Role: role, Reason: "SignTargets called with non-existent targets role", } } tr.Targets[role].Signed.Expires = expires tr.Targets[role].Signed.Version++ signed, err := tr.Targets[role].ToSigned() if err != nil { logrus.Debug("errored getting targets data.Signed object") return nil, err } var targets data.BaseRole if role == data.CanonicalTargetsRole { targets, err = tr.GetBaseRole(role) } else { tr, err := tr.GetDelegationRole(role) if err != nil { return nil, err } targets = tr.BaseRole } if err != nil { return nil, err } signed, err = tr.sign(signed, []data.BaseRole{targets}, nil) if err != nil { logrus.Debug("errored signing ", role) return nil, err } tr.Targets[role].Signatures = signed.Signatures return signed, nil }
go
func (tr *Repo) SignTargets(role data.RoleName, expires time.Time) (*data.Signed, error) { logrus.Debugf("sign targets called for role %s", role) if _, ok := tr.Targets[role]; !ok { return nil, data.ErrInvalidRole{ Role: role, Reason: "SignTargets called with non-existent targets role", } } tr.Targets[role].Signed.Expires = expires tr.Targets[role].Signed.Version++ signed, err := tr.Targets[role].ToSigned() if err != nil { logrus.Debug("errored getting targets data.Signed object") return nil, err } var targets data.BaseRole if role == data.CanonicalTargetsRole { targets, err = tr.GetBaseRole(role) } else { tr, err := tr.GetDelegationRole(role) if err != nil { return nil, err } targets = tr.BaseRole } if err != nil { return nil, err } signed, err = tr.sign(signed, []data.BaseRole{targets}, nil) if err != nil { logrus.Debug("errored signing ", role) return nil, err } tr.Targets[role].Signatures = signed.Signatures return signed, nil }
[ "func", "(", "tr", "*", "Repo", ")", "SignTargets", "(", "role", "data", ".", "RoleName", ",", "expires", "time", ".", "Time", ")", "(", "*", "data", ".", "Signed", ",", "error", ")", "{", "logrus", ".", "Debugf", "(", "\"sign targets called for role %s\...
// SignTargets signs the targets file for the given top level or delegated targets role
[ "SignTargets", "signs", "the", "targets", "file", "for", "the", "given", "top", "level", "or", "delegated", "targets", "role" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L949-L986
train
theupdateframework/notary
tuf/tuf.go
SignSnapshot
func (tr *Repo) SignSnapshot(expires time.Time) (*data.Signed, error) { logrus.Debug("signing snapshot...") signedRoot, err := tr.Root.ToSigned() if err != nil { return nil, err } err = tr.UpdateSnapshot(data.CanonicalRootRole, signedRoot) if err != nil { return nil, err } tr.Root.Dirty = false // root dirty until changes captures in snapshot for role, targets := range tr.Targets { signedTargets, err := targets.ToSigned() if err != nil { return nil, err } err = tr.UpdateSnapshot(role, signedTargets) if err != nil { return nil, err } targets.Dirty = false } tr.Snapshot.Signed.Expires = expires tr.Snapshot.Signed.Version++ signed, err := tr.Snapshot.ToSigned() if err != nil { return nil, err } snapshot, err := tr.GetBaseRole(data.CanonicalSnapshotRole) if err != nil { return nil, err } signed, err = tr.sign(signed, []data.BaseRole{snapshot}, nil) if err != nil { return nil, err } tr.Snapshot.Signatures = signed.Signatures return signed, nil }
go
func (tr *Repo) SignSnapshot(expires time.Time) (*data.Signed, error) { logrus.Debug("signing snapshot...") signedRoot, err := tr.Root.ToSigned() if err != nil { return nil, err } err = tr.UpdateSnapshot(data.CanonicalRootRole, signedRoot) if err != nil { return nil, err } tr.Root.Dirty = false // root dirty until changes captures in snapshot for role, targets := range tr.Targets { signedTargets, err := targets.ToSigned() if err != nil { return nil, err } err = tr.UpdateSnapshot(role, signedTargets) if err != nil { return nil, err } targets.Dirty = false } tr.Snapshot.Signed.Expires = expires tr.Snapshot.Signed.Version++ signed, err := tr.Snapshot.ToSigned() if err != nil { return nil, err } snapshot, err := tr.GetBaseRole(data.CanonicalSnapshotRole) if err != nil { return nil, err } signed, err = tr.sign(signed, []data.BaseRole{snapshot}, nil) if err != nil { return nil, err } tr.Snapshot.Signatures = signed.Signatures return signed, nil }
[ "func", "(", "tr", "*", "Repo", ")", "SignSnapshot", "(", "expires", "time", ".", "Time", ")", "(", "*", "data", ".", "Signed", ",", "error", ")", "{", "logrus", ".", "Debug", "(", "\"signing snapshot...\"", ")", "\n", "signedRoot", ",", "err", ":=", ...
// SignSnapshot updates the snapshot based on the current targets and root then signs it
[ "SignSnapshot", "updates", "the", "snapshot", "based", "on", "the", "current", "targets", "and", "root", "then", "signs", "it" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L989-L1027
train
theupdateframework/notary
tuf/tuf.go
SignTimestamp
func (tr *Repo) SignTimestamp(expires time.Time) (*data.Signed, error) { logrus.Debug("SignTimestamp") signedSnapshot, err := tr.Snapshot.ToSigned() if err != nil { return nil, err } err = tr.UpdateTimestamp(signedSnapshot) if err != nil { return nil, err } tr.Timestamp.Signed.Expires = expires tr.Timestamp.Signed.Version++ signed, err := tr.Timestamp.ToSigned() if err != nil { return nil, err } timestamp, err := tr.GetBaseRole(data.CanonicalTimestampRole) if err != nil { return nil, err } signed, err = tr.sign(signed, []data.BaseRole{timestamp}, nil) if err != nil { return nil, err } tr.Timestamp.Signatures = signed.Signatures tr.Snapshot.Dirty = false // snapshot is dirty until changes have been captured in timestamp return signed, nil }
go
func (tr *Repo) SignTimestamp(expires time.Time) (*data.Signed, error) { logrus.Debug("SignTimestamp") signedSnapshot, err := tr.Snapshot.ToSigned() if err != nil { return nil, err } err = tr.UpdateTimestamp(signedSnapshot) if err != nil { return nil, err } tr.Timestamp.Signed.Expires = expires tr.Timestamp.Signed.Version++ signed, err := tr.Timestamp.ToSigned() if err != nil { return nil, err } timestamp, err := tr.GetBaseRole(data.CanonicalTimestampRole) if err != nil { return nil, err } signed, err = tr.sign(signed, []data.BaseRole{timestamp}, nil) if err != nil { return nil, err } tr.Timestamp.Signatures = signed.Signatures tr.Snapshot.Dirty = false // snapshot is dirty until changes have been captured in timestamp return signed, nil }
[ "func", "(", "tr", "*", "Repo", ")", "SignTimestamp", "(", "expires", "time", ".", "Time", ")", "(", "*", "data", ".", "Signed", ",", "error", ")", "{", "logrus", ".", "Debug", "(", "\"SignTimestamp\"", ")", "\n", "signedSnapshot", ",", "err", ":=", ...
// SignTimestamp updates the timestamp based on the current snapshot then signs it
[ "SignTimestamp", "updates", "the", "timestamp", "based", "on", "the", "current", "snapshot", "then", "signs", "it" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L1030-L1057
train
theupdateframework/notary
tuf/data/targets.go
isValidTargetsStructure
func isValidTargetsStructure(t Targets, roleName RoleName) error { if roleName != CanonicalTargetsRole && !IsDelegation(roleName) { return ErrInvalidRole{Role: roleName} } // even if it's a delegated role, the metadata type is "Targets" expectedType := TUFTypes[CanonicalTargetsRole] if t.Type != expectedType { return ErrInvalidMetadata{ role: roleName, msg: fmt.Sprintf("expected type %s, not %s", expectedType, t.Type)} } if t.Version < 1 { return ErrInvalidMetadata{role: roleName, msg: "version cannot be less than one"} } for _, roleObj := range t.Delegations.Roles { if !IsDelegation(roleObj.Name) || path.Dir(roleObj.Name.String()) != roleName.String() { return ErrInvalidMetadata{ role: roleName, msg: fmt.Sprintf("delegation role %s invalid", roleObj.Name)} } if err := isValidRootRoleStructure(roleName, roleObj.Name, roleObj.RootRole, t.Delegations.Keys); err != nil { return err } } return nil }
go
func isValidTargetsStructure(t Targets, roleName RoleName) error { if roleName != CanonicalTargetsRole && !IsDelegation(roleName) { return ErrInvalidRole{Role: roleName} } // even if it's a delegated role, the metadata type is "Targets" expectedType := TUFTypes[CanonicalTargetsRole] if t.Type != expectedType { return ErrInvalidMetadata{ role: roleName, msg: fmt.Sprintf("expected type %s, not %s", expectedType, t.Type)} } if t.Version < 1 { return ErrInvalidMetadata{role: roleName, msg: "version cannot be less than one"} } for _, roleObj := range t.Delegations.Roles { if !IsDelegation(roleObj.Name) || path.Dir(roleObj.Name.String()) != roleName.String() { return ErrInvalidMetadata{ role: roleName, msg: fmt.Sprintf("delegation role %s invalid", roleObj.Name)} } if err := isValidRootRoleStructure(roleName, roleObj.Name, roleObj.RootRole, t.Delegations.Keys); err != nil { return err } } return nil }
[ "func", "isValidTargetsStructure", "(", "t", "Targets", ",", "roleName", "RoleName", ")", "error", "{", "if", "roleName", "!=", "CanonicalTargetsRole", "&&", "!", "IsDelegation", "(", "roleName", ")", "{", "return", "ErrInvalidRole", "{", "Role", ":", "roleName"...
// isValidTargetsStructure returns an error, or nil, depending on whether the content of the struct // is valid for targets metadata. This does not check signatures or expiry, just that // the metadata content is valid.
[ "isValidTargetsStructure", "returns", "an", "error", "or", "nil", "depending", "on", "whether", "the", "content", "of", "the", "struct", "is", "valid", "for", "targets", "metadata", ".", "This", "does", "not", "check", "signatures", "or", "expiry", "just", "th...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/targets.go#L29-L55
train
theupdateframework/notary
tuf/data/targets.go
NewTargets
func NewTargets() *SignedTargets { return &SignedTargets{ Signatures: make([]Signature, 0), Signed: Targets{ SignedCommon: SignedCommon{ Type: TUFTypes["targets"], Version: 0, Expires: DefaultExpires("targets"), }, Targets: make(Files), Delegations: *NewDelegations(), }, Dirty: true, } }
go
func NewTargets() *SignedTargets { return &SignedTargets{ Signatures: make([]Signature, 0), Signed: Targets{ SignedCommon: SignedCommon{ Type: TUFTypes["targets"], Version: 0, Expires: DefaultExpires("targets"), }, Targets: make(Files), Delegations: *NewDelegations(), }, Dirty: true, } }
[ "func", "NewTargets", "(", ")", "*", "SignedTargets", "{", "return", "&", "SignedTargets", "{", "Signatures", ":", "make", "(", "[", "]", "Signature", ",", "0", ")", ",", "Signed", ":", "Targets", "{", "SignedCommon", ":", "SignedCommon", "{", "Type", ":...
// NewTargets initializes a new empty SignedTargets object
[ "NewTargets", "initializes", "a", "new", "empty", "SignedTargets", "object" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/targets.go#L58-L72
train
theupdateframework/notary
tuf/data/targets.go
GetMeta
func (t SignedTargets) GetMeta(path string) *FileMeta { for p, meta := range t.Signed.Targets { if p == path { return &meta } } return nil }
go
func (t SignedTargets) GetMeta(path string) *FileMeta { for p, meta := range t.Signed.Targets { if p == path { return &meta } } return nil }
[ "func", "(", "t", "SignedTargets", ")", "GetMeta", "(", "path", "string", ")", "*", "FileMeta", "{", "for", "p", ",", "meta", ":=", "range", "t", ".", "Signed", ".", "Targets", "{", "if", "p", "==", "path", "{", "return", "&", "meta", "\n", "}", ...
// GetMeta attempts to find the targets entry for the path. It // will return nil in the case of the target not being found.
[ "GetMeta", "attempts", "to", "find", "the", "targets", "entry", "for", "the", "path", ".", "It", "will", "return", "nil", "in", "the", "case", "of", "the", "target", "not", "being", "found", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/targets.go#L76-L83
train
theupdateframework/notary
tuf/data/targets.go
GetValidDelegations
func (t SignedTargets) GetValidDelegations(parent DelegationRole) []DelegationRole { roles := t.buildDelegationRoles() result := []DelegationRole{} for _, r := range roles { validRole, err := parent.Restrict(r) if err != nil { continue } result = append(result, validRole) } return result }
go
func (t SignedTargets) GetValidDelegations(parent DelegationRole) []DelegationRole { roles := t.buildDelegationRoles() result := []DelegationRole{} for _, r := range roles { validRole, err := parent.Restrict(r) if err != nil { continue } result = append(result, validRole) } return result }
[ "func", "(", "t", "SignedTargets", ")", "GetValidDelegations", "(", "parent", "DelegationRole", ")", "[", "]", "DelegationRole", "{", "roles", ":=", "t", ".", "buildDelegationRoles", "(", ")", "\n", "result", ":=", "[", "]", "DelegationRole", "{", "}", "\n",...
// GetValidDelegations filters the delegation roles specified in the signed targets, and // only returns roles that are direct children and restricts their paths
[ "GetValidDelegations", "filters", "the", "delegation", "roles", "specified", "in", "the", "signed", "targets", "and", "only", "returns", "roles", "that", "are", "direct", "children", "and", "restricts", "their", "paths" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/targets.go#L87-L98
train
theupdateframework/notary
tuf/data/targets.go
BuildDelegationRole
func (t *SignedTargets) BuildDelegationRole(roleName RoleName) (DelegationRole, error) { for _, role := range t.Signed.Delegations.Roles { if role.Name == roleName { pubKeys := make(map[string]PublicKey) for _, keyID := range role.KeyIDs { pubKey, ok := t.Signed.Delegations.Keys[keyID] if !ok { // Couldn't retrieve all keys, so stop walking and return invalid role return DelegationRole{}, ErrInvalidRole{ Role: roleName, Reason: "role lists unknown key " + keyID + " as a signing key", } } pubKeys[keyID] = pubKey } return DelegationRole{ BaseRole: BaseRole{ Name: role.Name, Keys: pubKeys, Threshold: role.Threshold, }, Paths: role.Paths, }, nil } } return DelegationRole{}, ErrNoSuchRole{Role: roleName} }
go
func (t *SignedTargets) BuildDelegationRole(roleName RoleName) (DelegationRole, error) { for _, role := range t.Signed.Delegations.Roles { if role.Name == roleName { pubKeys := make(map[string]PublicKey) for _, keyID := range role.KeyIDs { pubKey, ok := t.Signed.Delegations.Keys[keyID] if !ok { // Couldn't retrieve all keys, so stop walking and return invalid role return DelegationRole{}, ErrInvalidRole{ Role: roleName, Reason: "role lists unknown key " + keyID + " as a signing key", } } pubKeys[keyID] = pubKey } return DelegationRole{ BaseRole: BaseRole{ Name: role.Name, Keys: pubKeys, Threshold: role.Threshold, }, Paths: role.Paths, }, nil } } return DelegationRole{}, ErrNoSuchRole{Role: roleName} }
[ "func", "(", "t", "*", "SignedTargets", ")", "BuildDelegationRole", "(", "roleName", "RoleName", ")", "(", "DelegationRole", ",", "error", ")", "{", "for", "_", ",", "role", ":=", "range", "t", ".", "Signed", ".", "Delegations", ".", "Roles", "{", "if", ...
// BuildDelegationRole returns a copy of a DelegationRole using the information in this SignedTargets for the specified role name. // Will error for invalid role name or key metadata within this SignedTargets. Path data is not validated.
[ "BuildDelegationRole", "returns", "a", "copy", "of", "a", "DelegationRole", "using", "the", "information", "in", "this", "SignedTargets", "for", "the", "specified", "role", "name", ".", "Will", "error", "for", "invalid", "role", "name", "or", "key", "metadata", ...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/targets.go#L102-L128
train
theupdateframework/notary
tuf/data/targets.go
buildDelegationRoles
func (t SignedTargets) buildDelegationRoles() []DelegationRole { var roles []DelegationRole for _, roleData := range t.Signed.Delegations.Roles { delgRole, err := t.BuildDelegationRole(roleData.Name) if err != nil { continue } roles = append(roles, delgRole) } return roles }
go
func (t SignedTargets) buildDelegationRoles() []DelegationRole { var roles []DelegationRole for _, roleData := range t.Signed.Delegations.Roles { delgRole, err := t.BuildDelegationRole(roleData.Name) if err != nil { continue } roles = append(roles, delgRole) } return roles }
[ "func", "(", "t", "SignedTargets", ")", "buildDelegationRoles", "(", ")", "[", "]", "DelegationRole", "{", "var", "roles", "[", "]", "DelegationRole", "\n", "for", "_", ",", "roleData", ":=", "range", "t", ".", "Signed", ".", "Delegations", ".", "Roles", ...
// helper function to create DelegationRole structures from all delegations in a SignedTargets, // these delegations are read directly from the SignedTargets and not modified or validated
[ "helper", "function", "to", "create", "DelegationRole", "structures", "from", "all", "delegations", "in", "a", "SignedTargets", "these", "delegations", "are", "read", "directly", "from", "the", "SignedTargets", "and", "not", "modified", "or", "validated" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/targets.go#L132-L142
train
theupdateframework/notary
tuf/data/targets.go
AddTarget
func (t *SignedTargets) AddTarget(path string, meta FileMeta) { t.Signed.Targets[path] = meta t.Dirty = true }
go
func (t *SignedTargets) AddTarget(path string, meta FileMeta) { t.Signed.Targets[path] = meta t.Dirty = true }
[ "func", "(", "t", "*", "SignedTargets", ")", "AddTarget", "(", "path", "string", ",", "meta", "FileMeta", ")", "{", "t", ".", "Signed", ".", "Targets", "[", "path", "]", "=", "meta", "\n", "t", ".", "Dirty", "=", "true", "\n", "}" ]
// AddTarget adds or updates the meta for the given path
[ "AddTarget", "adds", "or", "updates", "the", "meta", "for", "the", "given", "path" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/targets.go#L145-L148
train
theupdateframework/notary
tuf/data/targets.go
AddDelegation
func (t *SignedTargets) AddDelegation(role *Role, keys []*PublicKey) error { return errors.New("Not Implemented") }
go
func (t *SignedTargets) AddDelegation(role *Role, keys []*PublicKey) error { return errors.New("Not Implemented") }
[ "func", "(", "t", "*", "SignedTargets", ")", "AddDelegation", "(", "role", "*", "Role", ",", "keys", "[", "]", "*", "PublicKey", ")", "error", "{", "return", "errors", ".", "New", "(", "\"Not Implemented\"", ")", "\n", "}" ]
// AddDelegation will add a new delegated role with the given keys, // ensuring the keys either already exist, or are added to the map // of delegation keys
[ "AddDelegation", "will", "add", "a", "new", "delegated", "role", "with", "the", "given", "keys", "ensuring", "the", "keys", "either", "already", "exist", "or", "are", "added", "to", "the", "map", "of", "delegation", "keys" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/targets.go#L153-L155
train
theupdateframework/notary
tuf/data/targets.go
MarshalJSON
func (t *SignedTargets) MarshalJSON() ([]byte, error) { signed, err := t.ToSigned() if err != nil { return nil, err } return defaultSerializer.Marshal(signed) }
go
func (t *SignedTargets) MarshalJSON() ([]byte, error) { signed, err := t.ToSigned() if err != nil { return nil, err } return defaultSerializer.Marshal(signed) }
[ "func", "(", "t", "*", "SignedTargets", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "signed", ",", "err", ":=", "t", ".", "ToSigned", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "...
// MarshalJSON returns the serialized form of SignedTargets as bytes
[ "MarshalJSON", "returns", "the", "serialized", "form", "of", "SignedTargets", "as", "bytes" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/targets.go#L177-L183
train
theupdateframework/notary
tuf/builder.go
ChecksumKnown
func (c ConsistentInfo) ChecksumKnown() bool { // empty hash, no size : this is the zero value return len(c.fileMeta.Hashes) > 0 || c.fileMeta.Length != 0 }
go
func (c ConsistentInfo) ChecksumKnown() bool { // empty hash, no size : this is the zero value return len(c.fileMeta.Hashes) > 0 || c.fileMeta.Length != 0 }
[ "func", "(", "c", "ConsistentInfo", ")", "ChecksumKnown", "(", ")", "bool", "{", "return", "len", "(", "c", ".", "fileMeta", ".", "Hashes", ")", ">", "0", "||", "c", ".", "fileMeta", ".", "Length", "!=", "0", "\n", "}" ]
// ChecksumKnown determines whether or not we know enough to provide a size and // consistent name
[ "ChecksumKnown", "determines", "whether", "or", "not", "we", "know", "enough", "to", "provide", "a", "size", "and", "consistent", "name" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/builder.go#L37-L40
train
theupdateframework/notary
tuf/builder.go
NewRepoBuilder
func NewRepoBuilder(gun data.GUN, cs signed.CryptoService, trustpin trustpinning.TrustPinConfig) RepoBuilder { return NewBuilderFromRepo(gun, NewRepo(cs), trustpin) }
go
func NewRepoBuilder(gun data.GUN, cs signed.CryptoService, trustpin trustpinning.TrustPinConfig) RepoBuilder { return NewBuilderFromRepo(gun, NewRepo(cs), trustpin) }
[ "func", "NewRepoBuilder", "(", "gun", "data", ".", "GUN", ",", "cs", "signed", ".", "CryptoService", ",", "trustpin", "trustpinning", ".", "TrustPinConfig", ")", "RepoBuilder", "{", "return", "NewBuilderFromRepo", "(", "gun", ",", "NewRepo", "(", "cs", ")", ...
// NewRepoBuilder is the only way to get a pre-built RepoBuilder
[ "NewRepoBuilder", "is", "the", "only", "way", "to", "get", "a", "pre", "-", "built", "RepoBuilder" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/builder.go#L100-L102
train
theupdateframework/notary
tuf/builder.go
NewBuilderFromRepo
func NewBuilderFromRepo(gun data.GUN, repo *Repo, trustpin trustpinning.TrustPinConfig) RepoBuilder { return &repoBuilderWrapper{ RepoBuilder: &repoBuilder{ repo: repo, invalidRoles: NewRepo(nil), gun: gun, trustpin: trustpin, loadedNotChecksummed: make(map[data.RoleName][]byte), }, } }
go
func NewBuilderFromRepo(gun data.GUN, repo *Repo, trustpin trustpinning.TrustPinConfig) RepoBuilder { return &repoBuilderWrapper{ RepoBuilder: &repoBuilder{ repo: repo, invalidRoles: NewRepo(nil), gun: gun, trustpin: trustpin, loadedNotChecksummed: make(map[data.RoleName][]byte), }, } }
[ "func", "NewBuilderFromRepo", "(", "gun", "data", ".", "GUN", ",", "repo", "*", "Repo", ",", "trustpin", "trustpinning", ".", "TrustPinConfig", ")", "RepoBuilder", "{", "return", "&", "repoBuilderWrapper", "{", "RepoBuilder", ":", "&", "repoBuilder", "{", "rep...
// NewBuilderFromRepo allows us to bootstrap a builder given existing repo data. // YOU PROBABLY SHOULDN'T BE USING THIS OUTSIDE OF TESTING CODE!!!
[ "NewBuilderFromRepo", "allows", "us", "to", "bootstrap", "a", "builder", "given", "existing", "repo", "data", ".", "YOU", "PROBABLY", "SHOULDN", "T", "BE", "USING", "THIS", "OUTSIDE", "OF", "TESTING", "CODE!!!" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/builder.go#L106-L116
train
theupdateframework/notary
tuf/builder.go
IsLoaded
func (rb *repoBuilder) IsLoaded(roleName data.RoleName) bool { switch roleName { case data.CanonicalRootRole: return rb.repo.Root != nil case data.CanonicalSnapshotRole: return rb.repo.Snapshot != nil case data.CanonicalTimestampRole: return rb.repo.Timestamp != nil default: return rb.repo.Targets[roleName] != nil } }
go
func (rb *repoBuilder) IsLoaded(roleName data.RoleName) bool { switch roleName { case data.CanonicalRootRole: return rb.repo.Root != nil case data.CanonicalSnapshotRole: return rb.repo.Snapshot != nil case data.CanonicalTimestampRole: return rb.repo.Timestamp != nil default: return rb.repo.Targets[roleName] != nil } }
[ "func", "(", "rb", "*", "repoBuilder", ")", "IsLoaded", "(", "roleName", "data", ".", "RoleName", ")", "bool", "{", "switch", "roleName", "{", "case", "data", ".", "CanonicalRootRole", ":", "return", "rb", ".", "repo", ".", "Root", "!=", "nil", "\n", "...
// IsLoaded returns whether a particular role has already been loaded
[ "IsLoaded", "returns", "whether", "a", "particular", "role", "has", "already", "been", "loaded" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/builder.go#L187-L198
train
theupdateframework/notary
tuf/builder.go
LoadRootForUpdate
func (rb *repoBuilder) LoadRootForUpdate(content []byte, minVersion int, isFinal bool) error { if err := rb.loadOptions(data.CanonicalRootRole, content, minVersion, !isFinal, !isFinal, true); err != nil { return err } if !isFinal { rb.prevRoot = rb.repo.Root } return nil }
go
func (rb *repoBuilder) LoadRootForUpdate(content []byte, minVersion int, isFinal bool) error { if err := rb.loadOptions(data.CanonicalRootRole, content, minVersion, !isFinal, !isFinal, true); err != nil { return err } if !isFinal { rb.prevRoot = rb.repo.Root } return nil }
[ "func", "(", "rb", "*", "repoBuilder", ")", "LoadRootForUpdate", "(", "content", "[", "]", "byte", ",", "minVersion", "int", ",", "isFinal", "bool", ")", "error", "{", "if", "err", ":=", "rb", ".", "loadOptions", "(", "data", ".", "CanonicalRootRole", ",...
// LoadRootForUpdate adds additional flags for updating the root.json file
[ "LoadRootForUpdate", "adds", "additional", "flags", "for", "updating", "the", "root", ".", "json", "file" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/builder.go#L253-L261
train
theupdateframework/notary
tuf/builder.go
loadOptions
func (rb *repoBuilder) loadOptions(roleName data.RoleName, content []byte, minVersion int, allowExpired, skipChecksum, allowLoaded bool) error { if !data.ValidRole(roleName) { return ErrInvalidBuilderInput{msg: fmt.Sprintf("%s is an invalid role", roleName)} } if !allowLoaded && rb.IsLoaded(roleName) { return ErrInvalidBuilderInput{msg: fmt.Sprintf("%s has already been loaded", roleName)} } var err error switch roleName { case data.CanonicalRootRole: break case data.CanonicalTimestampRole, data.CanonicalSnapshotRole, data.CanonicalTargetsRole: err = rb.checkPrereqsLoaded([]data.RoleName{data.CanonicalRootRole}) default: // delegations err = rb.checkPrereqsLoaded([]data.RoleName{data.CanonicalRootRole, data.CanonicalTargetsRole}) } if err != nil { return err } switch roleName { case data.CanonicalRootRole: return rb.loadRoot(content, minVersion, allowExpired, skipChecksum) case data.CanonicalSnapshotRole: return rb.loadSnapshot(content, minVersion, allowExpired) case data.CanonicalTimestampRole: return rb.loadTimestamp(content, minVersion, allowExpired) case data.CanonicalTargetsRole: return rb.loadTargets(content, minVersion, allowExpired) default: return rb.loadDelegation(roleName, content, minVersion, allowExpired) } }
go
func (rb *repoBuilder) loadOptions(roleName data.RoleName, content []byte, minVersion int, allowExpired, skipChecksum, allowLoaded bool) error { if !data.ValidRole(roleName) { return ErrInvalidBuilderInput{msg: fmt.Sprintf("%s is an invalid role", roleName)} } if !allowLoaded && rb.IsLoaded(roleName) { return ErrInvalidBuilderInput{msg: fmt.Sprintf("%s has already been loaded", roleName)} } var err error switch roleName { case data.CanonicalRootRole: break case data.CanonicalTimestampRole, data.CanonicalSnapshotRole, data.CanonicalTargetsRole: err = rb.checkPrereqsLoaded([]data.RoleName{data.CanonicalRootRole}) default: // delegations err = rb.checkPrereqsLoaded([]data.RoleName{data.CanonicalRootRole, data.CanonicalTargetsRole}) } if err != nil { return err } switch roleName { case data.CanonicalRootRole: return rb.loadRoot(content, minVersion, allowExpired, skipChecksum) case data.CanonicalSnapshotRole: return rb.loadSnapshot(content, minVersion, allowExpired) case data.CanonicalTimestampRole: return rb.loadTimestamp(content, minVersion, allowExpired) case data.CanonicalTargetsRole: return rb.loadTargets(content, minVersion, allowExpired) default: return rb.loadDelegation(roleName, content, minVersion, allowExpired) } }
[ "func", "(", "rb", "*", "repoBuilder", ")", "loadOptions", "(", "roleName", "data", ".", "RoleName", ",", "content", "[", "]", "byte", ",", "minVersion", "int", ",", "allowExpired", ",", "skipChecksum", ",", "allowLoaded", "bool", ")", "error", "{", "if", ...
// loadOptions adds additional flags that should only be used for updating the root.json
[ "loadOptions", "adds", "additional", "flags", "that", "should", "only", "be", "used", "for", "updating", "the", "root", ".", "json" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/builder.go#L264-L298
train
theupdateframework/notary
tuf/builder.go
loadRoot
func (rb *repoBuilder) loadRoot(content []byte, minVersion int, allowExpired, skipChecksum bool) error { roleName := data.CanonicalRootRole signedObj, err := rb.bytesToSigned(content, data.CanonicalRootRole, skipChecksum) if err != nil { return err } // ValidateRoot validates against the previous root's role, as well as validates that the root // itself is self-consistent with its own signatures and thresholds. // This assumes that ValidateRoot calls data.RootFromSigned, which validates // the metadata, rather than just unmarshalling signedObject into a SignedRoot object itself. signedRoot, err := trustpinning.ValidateRoot(rb.prevRoot, signedObj, rb.gun, rb.trustpin) if err != nil { return err } if err := signed.VerifyVersion(&(signedRoot.Signed.SignedCommon), minVersion); err != nil { return err } if !allowExpired { // check must go at the end because all other validation should pass if err := signed.VerifyExpiry(&(signedRoot.Signed.SignedCommon), roleName); err != nil { return err } } rootRole, err := signedRoot.BuildBaseRole(data.CanonicalRootRole) if err != nil { // this should never happen since the root has been validated return err } rb.repo.Root = signedRoot rb.repo.originalRootRole = rootRole return nil }
go
func (rb *repoBuilder) loadRoot(content []byte, minVersion int, allowExpired, skipChecksum bool) error { roleName := data.CanonicalRootRole signedObj, err := rb.bytesToSigned(content, data.CanonicalRootRole, skipChecksum) if err != nil { return err } // ValidateRoot validates against the previous root's role, as well as validates that the root // itself is self-consistent with its own signatures and thresholds. // This assumes that ValidateRoot calls data.RootFromSigned, which validates // the metadata, rather than just unmarshalling signedObject into a SignedRoot object itself. signedRoot, err := trustpinning.ValidateRoot(rb.prevRoot, signedObj, rb.gun, rb.trustpin) if err != nil { return err } if err := signed.VerifyVersion(&(signedRoot.Signed.SignedCommon), minVersion); err != nil { return err } if !allowExpired { // check must go at the end because all other validation should pass if err := signed.VerifyExpiry(&(signedRoot.Signed.SignedCommon), roleName); err != nil { return err } } rootRole, err := signedRoot.BuildBaseRole(data.CanonicalRootRole) if err != nil { // this should never happen since the root has been validated return err } rb.repo.Root = signedRoot rb.repo.originalRootRole = rootRole return nil }
[ "func", "(", "rb", "*", "repoBuilder", ")", "loadRoot", "(", "content", "[", "]", "byte", ",", "minVersion", "int", ",", "allowExpired", ",", "skipChecksum", "bool", ")", "error", "{", "roleName", ":=", "data", ".", "CanonicalRootRole", "\n", "signedObj", ...
// loadRoot loads a root if one has not been loaded
[ "loadRoot", "loads", "a", "root", "if", "one", "has", "not", "been", "loaded" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/builder.go#L431-L464
train
theupdateframework/notary
server/storage/sql_models.go
CreateTUFTable
func CreateTUFTable(db gorm.DB) error { // TODO: gorm query := db.AutoMigrate(&TUFFile{}) if query.Error != nil { return query.Error } query = db.Model(&TUFFile{}).AddUniqueIndex( "idx_gun", "gun", "role", "version") return query.Error }
go
func CreateTUFTable(db gorm.DB) error { // TODO: gorm query := db.AutoMigrate(&TUFFile{}) if query.Error != nil { return query.Error } query = db.Model(&TUFFile{}).AddUniqueIndex( "idx_gun", "gun", "role", "version") return query.Error }
[ "func", "CreateTUFTable", "(", "db", "gorm", ".", "DB", ")", "error", "{", "query", ":=", "db", ".", "AutoMigrate", "(", "&", "TUFFile", "{", "}", ")", "\n", "if", "query", ".", "Error", "!=", "nil", "{", "return", "query", ".", "Error", "\n", "}",...
// CreateTUFTable creates the DB table for TUFFile
[ "CreateTUFTable", "creates", "the", "DB", "table", "for", "TUFFile" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sql_models.go#L51-L60
train
theupdateframework/notary
server/storage/sql_models.go
CreateChangefeedTable
func CreateChangefeedTable(db gorm.DB) error { query := db.AutoMigrate(&SQLChange{}) return query.Error }
go
func CreateChangefeedTable(db gorm.DB) error { query := db.AutoMigrate(&SQLChange{}) return query.Error }
[ "func", "CreateChangefeedTable", "(", "db", "gorm", ".", "DB", ")", "error", "{", "query", ":=", "db", ".", "AutoMigrate", "(", "&", "SQLChange", "{", "}", ")", "\n", "return", "query", ".", "Error", "\n", "}" ]
// CreateChangefeedTable creates the DB table for Changefeed
[ "CreateChangefeedTable", "creates", "the", "DB", "table", "for", "Changefeed" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sql_models.go#L63-L66
train
theupdateframework/notary
server/server.go
Run
func Run(ctx context.Context, conf Config) error { tcpAddr, err := net.ResolveTCPAddr("tcp", conf.Addr) if err != nil { return err } var lsnr net.Listener lsnr, err = net.ListenTCP("tcp", tcpAddr) if err != nil { return err } if conf.TLSConfig != nil { logrus.Info("Enabling TLS") lsnr = tls.NewListener(lsnr, conf.TLSConfig) } var ac auth.AccessController if conf.AuthMethod == "token" { authOptions, ok := conf.AuthOpts.(map[string]interface{}) if !ok { return fmt.Errorf("auth.options must be a map[string]interface{}") } ac, err = auth.GetAccessController(conf.AuthMethod, authOptions) if err != nil { return err } } svr := http.Server{ Addr: conf.Addr, Handler: RootHandler( ctx, ac, conf.Trust, conf.ConsistentCacheControlConfig, conf.CurrentCacheControlConfig, conf.RepoPrefixes), } logrus.Info("Starting on ", conf.Addr) err = svr.Serve(lsnr) return err }
go
func Run(ctx context.Context, conf Config) error { tcpAddr, err := net.ResolveTCPAddr("tcp", conf.Addr) if err != nil { return err } var lsnr net.Listener lsnr, err = net.ListenTCP("tcp", tcpAddr) if err != nil { return err } if conf.TLSConfig != nil { logrus.Info("Enabling TLS") lsnr = tls.NewListener(lsnr, conf.TLSConfig) } var ac auth.AccessController if conf.AuthMethod == "token" { authOptions, ok := conf.AuthOpts.(map[string]interface{}) if !ok { return fmt.Errorf("auth.options must be a map[string]interface{}") } ac, err = auth.GetAccessController(conf.AuthMethod, authOptions) if err != nil { return err } } svr := http.Server{ Addr: conf.Addr, Handler: RootHandler( ctx, ac, conf.Trust, conf.ConsistentCacheControlConfig, conf.CurrentCacheControlConfig, conf.RepoPrefixes), } logrus.Info("Starting on ", conf.Addr) err = svr.Serve(lsnr) return err }
[ "func", "Run", "(", "ctx", "context", ".", "Context", ",", "conf", "Config", ")", "error", "{", "tcpAddr", ",", "err", ":=", "net", ".", "ResolveTCPAddr", "(", "\"tcp\"", ",", "conf", ".", "Addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", ...
// Run sets up and starts a TLS server that can be cancelled using the // given configuration. The context it is passed is the context it should // use directly for the TLS server, and generate children off for requests
[ "Run", "sets", "up", "and", "starts", "a", "TLS", "server", "that", "can", "be", "cancelled", "using", "the", "given", "configuration", ".", "The", "context", "it", "is", "passed", "is", "the", "context", "it", "should", "use", "directly", "for", "the", ...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/server.go#L51-L92
train
theupdateframework/notary
server/server.go
filterImagePrefixes
func filterImagePrefixes(requiredPrefixes []string, err error, handler http.Handler) http.Handler { if len(requiredPrefixes) == 0 { return handler } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gun := mux.Vars(r)["gun"] if gun == "" { handler.ServeHTTP(w, r) return } for _, prefix := range requiredPrefixes { if strings.HasPrefix(gun, prefix) { handler.ServeHTTP(w, r) return } } errcode.ServeJSON(w, err) }) }
go
func filterImagePrefixes(requiredPrefixes []string, err error, handler http.Handler) http.Handler { if len(requiredPrefixes) == 0 { return handler } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gun := mux.Vars(r)["gun"] if gun == "" { handler.ServeHTTP(w, r) return } for _, prefix := range requiredPrefixes { if strings.HasPrefix(gun, prefix) { handler.ServeHTTP(w, r) return } } errcode.ServeJSON(w, err) }) }
[ "func", "filterImagePrefixes", "(", "requiredPrefixes", "[", "]", "string", ",", "err", "error", ",", "handler", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "if", "len", "(", "requiredPrefixes", ")", "==", "0", "{", "return", "handler", "\n",...
// assumes that required prefixes is not empty
[ "assumes", "that", "required", "prefixes", "is", "not", "empty" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/server.go#L95-L117
train
theupdateframework/notary
server/server.go
CreateHandler
func CreateHandler(operationName string, serverHandler utils.ContextHandler, errorIfGUNInvalid error, includeCacheHeaders bool, cacheControlConfig utils.CacheControlConfig, permissionsRequired []string, authWrapper utils.AuthWrapper, repoPrefixes []string) http.Handler { var wrapped http.Handler wrapped = authWrapper(serverHandler, permissionsRequired...) if includeCacheHeaders { wrapped = utils.WrapWithCacheHandler(cacheControlConfig, wrapped) } wrapped = filterImagePrefixes(repoPrefixes, errorIfGUNInvalid, wrapped) return prometheus.InstrumentHandlerWithOpts(prometheusOpts(operationName), wrapped) }
go
func CreateHandler(operationName string, serverHandler utils.ContextHandler, errorIfGUNInvalid error, includeCacheHeaders bool, cacheControlConfig utils.CacheControlConfig, permissionsRequired []string, authWrapper utils.AuthWrapper, repoPrefixes []string) http.Handler { var wrapped http.Handler wrapped = authWrapper(serverHandler, permissionsRequired...) if includeCacheHeaders { wrapped = utils.WrapWithCacheHandler(cacheControlConfig, wrapped) } wrapped = filterImagePrefixes(repoPrefixes, errorIfGUNInvalid, wrapped) return prometheus.InstrumentHandlerWithOpts(prometheusOpts(operationName), wrapped) }
[ "func", "CreateHandler", "(", "operationName", "string", ",", "serverHandler", "utils", ".", "ContextHandler", ",", "errorIfGUNInvalid", "error", ",", "includeCacheHeaders", "bool", ",", "cacheControlConfig", "utils", ".", "CacheControlConfig", ",", "permissionsRequired",...
// CreateHandler creates a server handler, wrapping with auth, caching, and monitoring
[ "CreateHandler", "creates", "a", "server", "handler", "wrapping", "with", "auth", "caching", "and", "monitoring" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/server.go#L120-L128
train
theupdateframework/notary
cmd/notary/keys.go
keyRemove
func (k *keyCommander) keyRemove(cmd *cobra.Command, args []string) error { if len(args) < 1 { cmd.Usage() return fmt.Errorf("must specify the key ID of the key to remove") } config, err := k.configGetter() if err != nil { return err } ks, err := k.getKeyStores(config, true, false) if err != nil { return err } keyID := args[0] // This is an invalid ID if len(keyID) != notary.SHA256HexSize { return fmt.Errorf("invalid key ID provided: %s", keyID) } cmd.Println("") err = removeKeyInteractively(ks, keyID, k.input, cmd.OutOrStdout()) cmd.Println("") return err }
go
func (k *keyCommander) keyRemove(cmd *cobra.Command, args []string) error { if len(args) < 1 { cmd.Usage() return fmt.Errorf("must specify the key ID of the key to remove") } config, err := k.configGetter() if err != nil { return err } ks, err := k.getKeyStores(config, true, false) if err != nil { return err } keyID := args[0] // This is an invalid ID if len(keyID) != notary.SHA256HexSize { return fmt.Errorf("invalid key ID provided: %s", keyID) } cmd.Println("") err = removeKeyInteractively(ks, keyID, k.input, cmd.OutOrStdout()) cmd.Println("") return err }
[ "func", "(", "k", "*", "keyCommander", ")", "keyRemove", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "if", "len", "(", "args", ")", "<", "1", "{", "cmd", ".", "Usage", "(", ")", "\n", "return", ...
// keyRemove deletes a private key based on ID
[ "keyRemove", "deletes", "a", "private", "key", "based", "on", "ID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/keys.go#L415-L439
train
theupdateframework/notary
cmd/notary/keys.go
keyPassphraseChange
func (k *keyCommander) keyPassphraseChange(cmd *cobra.Command, args []string) error { if len(args) < 1 { cmd.Usage() return fmt.Errorf("must specify the key ID of the key to change the passphrase of") } config, err := k.configGetter() if err != nil { return err } ks, err := k.getKeyStores(config, true, false) if err != nil { return err } keyID := args[0] // This is an invalid ID if len(keyID) != notary.SHA256HexSize { return fmt.Errorf("invalid key ID provided: %s", keyID) } // Find which keyStore we should replace the key password in, and replace if we find it var foundKeyStore trustmanager.KeyStore var privKey data.PrivateKey var keyInfo trustmanager.KeyInfo var cs *cryptoservice.CryptoService for _, keyStore := range ks { cs = cryptoservice.NewCryptoService(keyStore) if privKey, _, err = cs.GetPrivateKey(keyID); err == nil { foundKeyStore = keyStore break } } if foundKeyStore == nil { return fmt.Errorf("could not retrieve local key for key ID provided: %s", keyID) } // Must use a different passphrase retriever to avoid caching the // unlocking passphrase and reusing that. passChangeRetriever := k.getRetriever() var addingKeyStore trustmanager.KeyStore switch foundKeyStore.Name() { case "yubikey": addingKeyStore, err = getYubiStore(nil, passChangeRetriever) keyInfo = trustmanager.KeyInfo{Role: data.CanonicalRootRole} default: addingKeyStore, err = trustmanager.NewKeyFileStore(config.GetString("trust_dir"), passChangeRetriever) if err != nil { return err } keyInfo, err = foundKeyStore.GetKeyInfo(keyID) } if err != nil { return err } err = addingKeyStore.AddKey(keyInfo, privKey) if err != nil { return err } cmd.Printf("\nSuccessfully updated passphrase for key ID: %s\n", keyID) return nil }
go
func (k *keyCommander) keyPassphraseChange(cmd *cobra.Command, args []string) error { if len(args) < 1 { cmd.Usage() return fmt.Errorf("must specify the key ID of the key to change the passphrase of") } config, err := k.configGetter() if err != nil { return err } ks, err := k.getKeyStores(config, true, false) if err != nil { return err } keyID := args[0] // This is an invalid ID if len(keyID) != notary.SHA256HexSize { return fmt.Errorf("invalid key ID provided: %s", keyID) } // Find which keyStore we should replace the key password in, and replace if we find it var foundKeyStore trustmanager.KeyStore var privKey data.PrivateKey var keyInfo trustmanager.KeyInfo var cs *cryptoservice.CryptoService for _, keyStore := range ks { cs = cryptoservice.NewCryptoService(keyStore) if privKey, _, err = cs.GetPrivateKey(keyID); err == nil { foundKeyStore = keyStore break } } if foundKeyStore == nil { return fmt.Errorf("could not retrieve local key for key ID provided: %s", keyID) } // Must use a different passphrase retriever to avoid caching the // unlocking passphrase and reusing that. passChangeRetriever := k.getRetriever() var addingKeyStore trustmanager.KeyStore switch foundKeyStore.Name() { case "yubikey": addingKeyStore, err = getYubiStore(nil, passChangeRetriever) keyInfo = trustmanager.KeyInfo{Role: data.CanonicalRootRole} default: addingKeyStore, err = trustmanager.NewKeyFileStore(config.GetString("trust_dir"), passChangeRetriever) if err != nil { return err } keyInfo, err = foundKeyStore.GetKeyInfo(keyID) } if err != nil { return err } err = addingKeyStore.AddKey(keyInfo, privKey) if err != nil { return err } cmd.Printf("\nSuccessfully updated passphrase for key ID: %s\n", keyID) return nil }
[ "func", "(", "k", "*", "keyCommander", ")", "keyPassphraseChange", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "if", "len", "(", "args", ")", "<", "1", "{", "cmd", ".", "Usage", "(", ")", "\n", "r...
// keyPassphraseChange changes the passphrase for a private key based on ID
[ "keyPassphraseChange", "changes", "the", "passphrase", "for", "a", "private", "key", "based", "on", "ID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/keys.go#L442-L503
train
theupdateframework/notary
cmd/notary-signer/main.go
debugServer
func debugServer(addr string) { logrus.Infof("Debug server listening on %s", addr) if err := http.ListenAndServe(addr, nil); err != nil { logrus.Fatalf("error listening on debug interface: %v", err) } }
go
func debugServer(addr string) { logrus.Infof("Debug server listening on %s", addr) if err := http.ListenAndServe(addr, nil); err != nil { logrus.Fatalf("error listening on debug interface: %v", err) } }
[ "func", "debugServer", "(", "addr", "string", ")", "{", "logrus", ".", "Infof", "(", "\"Debug server listening on %s\"", ",", "addr", ")", "\n", "if", "err", ":=", "http", ".", "ListenAndServe", "(", "addr", ",", "nil", ")", ";", "err", "!=", "nil", "{",...
// debugServer starts the debug server with pprof, expvar among other // endpoints. The addr should not be exposed externally. For most of these to // work, tls cannot be enabled on the endpoint, so it is generally separate.
[ "debugServer", "starts", "the", "debug", "server", "with", "pprof", "expvar", "among", "other", "endpoints", ".", "The", "addr", "should", "not", "be", "exposed", "externally", ".", "For", "most", "of", "these", "to", "work", "tls", "cannot", "be", "enabled"...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-signer/main.go#L93-L98
train
theupdateframework/notary
utils/http.go
RootHandlerFactory
func RootHandlerFactory(ctx context.Context, auth auth.AccessController, trust signed.CryptoService) func(ContextHandler, ...string) *rootHandler { return func(handler ContextHandler, actions ...string) *rootHandler { return &rootHandler{ handler: handler, auth: auth, actions: actions, context: ctx, trust: trust, } } }
go
func RootHandlerFactory(ctx context.Context, auth auth.AccessController, trust signed.CryptoService) func(ContextHandler, ...string) *rootHandler { return func(handler ContextHandler, actions ...string) *rootHandler { return &rootHandler{ handler: handler, auth: auth, actions: actions, context: ctx, trust: trust, } } }
[ "func", "RootHandlerFactory", "(", "ctx", "context", ".", "Context", ",", "auth", "auth", ".", "AccessController", ",", "trust", "signed", ".", "CryptoService", ")", "func", "(", "ContextHandler", ",", "...", "string", ")", "*", "rootHandler", "{", "return", ...
// RootHandlerFactory creates a new rootHandler factory using the given // Context creator and authorizer. The returned factory allows creating // new rootHandlers from the alternate http handler contextHandler and // a scope.
[ "RootHandlerFactory", "creates", "a", "new", "rootHandler", "factory", "using", "the", "given", "Context", "creator", "and", "authorizer", ".", "The", "returned", "factory", "allows", "creating", "new", "rootHandlers", "from", "the", "alternate", "http", "handler", ...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/http.go#L39-L49
train
theupdateframework/notary
utils/http.go
ServeHTTP
func (root *rootHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var ( err error ctx = ctxu.WithRequest(root.context, r) log = ctxu.GetRequestLogger(ctx) vars = mux.Vars(r) ) ctx, w = ctxu.WithResponseWriter(ctx, w) ctx = ctxu.WithLogger(ctx, log) ctx = context.WithValue(ctx, notary.CtxKeyCryptoSvc, root.trust) defer func(ctx context.Context) { ctxu.GetResponseLogger(ctx).Info("response completed") }(ctx) if root.auth != nil { ctx = context.WithValue(ctx, notary.CtxKeyRepo, vars["gun"]) if ctx, err = root.doAuth(ctx, vars["gun"], w); err != nil { // errors have already been logged/output to w inside doAuth // just return return } } if err := root.handler(ctx, w, r); err != nil { serveError(log, w, err) } }
go
func (root *rootHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var ( err error ctx = ctxu.WithRequest(root.context, r) log = ctxu.GetRequestLogger(ctx) vars = mux.Vars(r) ) ctx, w = ctxu.WithResponseWriter(ctx, w) ctx = ctxu.WithLogger(ctx, log) ctx = context.WithValue(ctx, notary.CtxKeyCryptoSvc, root.trust) defer func(ctx context.Context) { ctxu.GetResponseLogger(ctx).Info("response completed") }(ctx) if root.auth != nil { ctx = context.WithValue(ctx, notary.CtxKeyRepo, vars["gun"]) if ctx, err = root.doAuth(ctx, vars["gun"], w); err != nil { // errors have already been logged/output to w inside doAuth // just return return } } if err := root.handler(ctx, w, r); err != nil { serveError(log, w, err) } }
[ "func", "(", "root", "*", "rootHandler", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "var", "(", "err", "error", "\n", "ctx", "=", "ctxu", ".", "WithRequest", "(", "root", ".", "context"...
// ServeHTTP serves an HTTP request and implements the http.Handler interface.
[ "ServeHTTP", "serves", "an", "HTTP", "request", "and", "implements", "the", "http", ".", "Handler", "interface", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/http.go#L52-L78
train
theupdateframework/notary
utils/http.go
buildCatalogRecord
func buildCatalogRecord(actions ...string) []auth.Access { requiredAccess := []auth.Access{{ Resource: auth.Resource{ Type: "registry", Name: "catalog", }, Action: "*", }} return requiredAccess }
go
func buildCatalogRecord(actions ...string) []auth.Access { requiredAccess := []auth.Access{{ Resource: auth.Resource{ Type: "registry", Name: "catalog", }, Action: "*", }} return requiredAccess }
[ "func", "buildCatalogRecord", "(", "actions", "...", "string", ")", "[", "]", "auth", ".", "Access", "{", "requiredAccess", ":=", "[", "]", "auth", ".", "Access", "{", "{", "Resource", ":", "auth", ".", "Resource", "{", "Type", ":", "\"registry\"", ",", ...
// buildCatalogRecord returns the only valid format for the catalog // resource. Only admins can get this access level from the token // server.
[ "buildCatalogRecord", "returns", "the", "only", "valid", "format", "for", "the", "catalog", "resource", ".", "Only", "admins", "can", "get", "this", "access", "level", "from", "the", "token", "server", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/http.go#L143-L153
train
theupdateframework/notary
utils/http.go
NewCacheControlConfig
func NewCacheControlConfig(maxAgeInSeconds int, mustRevalidate bool) CacheControlConfig { if maxAgeInSeconds > 0 { return PublicCacheControl{MustReValidate: mustRevalidate, MaxAgeInSeconds: maxAgeInSeconds} } return NoCacheControl{} }
go
func NewCacheControlConfig(maxAgeInSeconds int, mustRevalidate bool) CacheControlConfig { if maxAgeInSeconds > 0 { return PublicCacheControl{MustReValidate: mustRevalidate, MaxAgeInSeconds: maxAgeInSeconds} } return NoCacheControl{} }
[ "func", "NewCacheControlConfig", "(", "maxAgeInSeconds", "int", ",", "mustRevalidate", "bool", ")", "CacheControlConfig", "{", "if", "maxAgeInSeconds", ">", "0", "{", "return", "PublicCacheControl", "{", "MustReValidate", ":", "mustRevalidate", ",", "MaxAgeInSeconds", ...
// NewCacheControlConfig returns CacheControlConfig interface for either setting // cache control or disabling cache control entirely
[ "NewCacheControlConfig", "returns", "CacheControlConfig", "interface", "for", "either", "setting", "cache", "control", "or", "disabling", "cache", "control", "entirely" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/http.go#L164-L169
train
theupdateframework/notary
utils/http.go
SetHeaders
func (p PublicCacheControl) SetHeaders(headers http.Header) { cacheControlValue := fmt.Sprintf("public, max-age=%v, s-maxage=%v", p.MaxAgeInSeconds, p.MaxAgeInSeconds) if p.MustReValidate { cacheControlValue = fmt.Sprintf("%s, must-revalidate", cacheControlValue) } headers.Set("Cache-Control", cacheControlValue) // delete the Pragma directive, because the only valid value in HTTP is // "no-cache" headers.Del("Pragma") if headers.Get("Last-Modified") == "" { SetLastModifiedHeader(headers, time.Time{}) } }
go
func (p PublicCacheControl) SetHeaders(headers http.Header) { cacheControlValue := fmt.Sprintf("public, max-age=%v, s-maxage=%v", p.MaxAgeInSeconds, p.MaxAgeInSeconds) if p.MustReValidate { cacheControlValue = fmt.Sprintf("%s, must-revalidate", cacheControlValue) } headers.Set("Cache-Control", cacheControlValue) // delete the Pragma directive, because the only valid value in HTTP is // "no-cache" headers.Del("Pragma") if headers.Get("Last-Modified") == "" { SetLastModifiedHeader(headers, time.Time{}) } }
[ "func", "(", "p", "PublicCacheControl", ")", "SetHeaders", "(", "headers", "http", ".", "Header", ")", "{", "cacheControlValue", ":=", "fmt", ".", "Sprintf", "(", "\"public, max-age=%v, s-maxage=%v\"", ",", "p", ".", "MaxAgeInSeconds", ",", "p", ".", "MaxAgeInSe...
// SetHeaders sets the public headers with an optional must-revalidate header
[ "SetHeaders", "sets", "the", "public", "headers", "with", "an", "optional", "must", "-", "revalidate", "header" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/http.go#L178-L192
train
theupdateframework/notary
utils/http.go
SetHeaders
func (n NoCacheControl) SetHeaders(headers http.Header) { headers.Set("Cache-Control", "max-age=0, no-cache, no-store") headers.Set("Pragma", "no-cache") }
go
func (n NoCacheControl) SetHeaders(headers http.Header) { headers.Set("Cache-Control", "max-age=0, no-cache, no-store") headers.Set("Pragma", "no-cache") }
[ "func", "(", "n", "NoCacheControl", ")", "SetHeaders", "(", "headers", "http", ".", "Header", ")", "{", "headers", ".", "Set", "(", "\"Cache-Control\"", ",", "\"max-age=0, no-cache, no-store\"", ")", "\n", "headers", ".", "Set", "(", "\"Pragma\"", ",", "\"no-c...
// SetHeaders sets the public headers cache-control headers and pragma to no-cache
[ "SetHeaders", "sets", "the", "public", "headers", "cache", "-", "control", "headers", "and", "pragma", "to", "no", "-", "cache" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/http.go#L198-L201
train
theupdateframework/notary
utils/http.go
WriteHeader
func (c *cacheControlResponseWriter) WriteHeader(statusCode int) { c.statusCode = statusCode c.ResponseWriter.WriteHeader(statusCode) }
go
func (c *cacheControlResponseWriter) WriteHeader(statusCode int) { c.statusCode = statusCode c.ResponseWriter.WriteHeader(statusCode) }
[ "func", "(", "c", "*", "cacheControlResponseWriter", ")", "WriteHeader", "(", "statusCode", "int", ")", "{", "c", ".", "statusCode", "=", "statusCode", "\n", "c", ".", "ResponseWriter", ".", "WriteHeader", "(", "statusCode", ")", "\n", "}" ]
// WriteHeader stores the header before writing it, so we can tell if it's been set // to a non-200 status code
[ "WriteHeader", "stores", "the", "header", "before", "writing", "it", "so", "we", "can", "tell", "if", "it", "s", "been", "set", "to", "a", "non", "-", "200", "status", "code" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/http.go#L213-L216
train
theupdateframework/notary
utils/http.go
Write
func (c *cacheControlResponseWriter) Write(data []byte) (int, error) { if c.statusCode == http.StatusOK || c.statusCode == 0 { headers := c.ResponseWriter.Header() if headers.Get("Cache-Control") == "" { c.config.SetHeaders(headers) } } return c.ResponseWriter.Write(data) }
go
func (c *cacheControlResponseWriter) Write(data []byte) (int, error) { if c.statusCode == http.StatusOK || c.statusCode == 0 { headers := c.ResponseWriter.Header() if headers.Get("Cache-Control") == "" { c.config.SetHeaders(headers) } } return c.ResponseWriter.Write(data) }
[ "func", "(", "c", "*", "cacheControlResponseWriter", ")", "Write", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "c", ".", "statusCode", "==", "http", ".", "StatusOK", "||", "c", ".", "statusCode", "==", "0", "{", "h...
// Write will set the cache headers if they haven't already been set and if the status // code has either not been set or set to 200
[ "Write", "will", "set", "the", "cache", "headers", "if", "they", "haven", "t", "already", "been", "set", "and", "if", "the", "status", "code", "has", "either", "not", "been", "set", "or", "set", "to", "200" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/http.go#L220-L228
train
theupdateframework/notary
utils/http.go
WrapWithCacheHandler
func WrapWithCacheHandler(ccc CacheControlConfig, handler http.Handler) http.Handler { if ccc != nil { return cacheControlHandler{Handler: handler, config: ccc} } return handler }
go
func WrapWithCacheHandler(ccc CacheControlConfig, handler http.Handler) http.Handler { if ccc != nil { return cacheControlHandler{Handler: handler, config: ccc} } return handler }
[ "func", "WrapWithCacheHandler", "(", "ccc", "CacheControlConfig", ",", "handler", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "if", "ccc", "!=", "nil", "{", "return", "cacheControlHandler", "{", "Handler", ":", "handler", ",", "config", ":", "c...
// WrapWithCacheHandler wraps another handler in one that can add cache control headers // given a 200 response
[ "WrapWithCacheHandler", "wraps", "another", "handler", "in", "one", "that", "can", "add", "cache", "control", "headers", "given", "a", "200", "response" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/http.go#L241-L246
train
theupdateframework/notary
utils/http.go
SetLastModifiedHeader
func SetLastModifiedHeader(headers http.Header, lmt time.Time) { headers.Set("Last-Modified", lmt.Format(time.RFC1123)) }
go
func SetLastModifiedHeader(headers http.Header, lmt time.Time) { headers.Set("Last-Modified", lmt.Format(time.RFC1123)) }
[ "func", "SetLastModifiedHeader", "(", "headers", "http", ".", "Header", ",", "lmt", "time", ".", "Time", ")", "{", "headers", ".", "Set", "(", "\"Last-Modified\"", ",", "lmt", ".", "Format", "(", "time", ".", "RFC1123", ")", ")", "\n", "}" ]
// SetLastModifiedHeader takes a time and uses it to set the LastModified header using // the right date format
[ "SetLastModifiedHeader", "takes", "a", "time", "and", "uses", "it", "to", "set", "the", "LastModified", "header", "using", "the", "right", "date", "format" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/http.go#L250-L252
train
theupdateframework/notary
client/tufclient.go
Update
func (c *tufClient) Update() (*tuf.Repo, *tuf.Repo, error) { // 1. Get timestamp // a. If timestamp error (verification, expired, etc...) download new root and return to 1. // 2. Check if local snapshot is up to date // a. If out of date, get updated snapshot // i. If snapshot error, download new root and return to 1. // 3. Check if root correct against snapshot // a. If incorrect, download new root and return to 1. // 4. Iteratively download and search targets and delegations to find target meta logrus.Debug("updating TUF client") err := c.update() if err != nil { logrus.Debug("Error occurred. Root will be downloaded and another update attempted") logrus.Debug("Resetting the TUF builder...") c.newBuilder = c.newBuilder.BootstrapNewBuilder() if err := c.updateRoot(); err != nil { logrus.Debug("Client Update (Root): ", err) return nil, nil, err } // If we error again, we now have the latest root and just want to fail // out as there's no expectation the problem can be resolved automatically logrus.Debug("retrying TUF client update") if err := c.update(); err != nil { return nil, nil, err } } return c.newBuilder.Finish() }
go
func (c *tufClient) Update() (*tuf.Repo, *tuf.Repo, error) { // 1. Get timestamp // a. If timestamp error (verification, expired, etc...) download new root and return to 1. // 2. Check if local snapshot is up to date // a. If out of date, get updated snapshot // i. If snapshot error, download new root and return to 1. // 3. Check if root correct against snapshot // a. If incorrect, download new root and return to 1. // 4. Iteratively download and search targets and delegations to find target meta logrus.Debug("updating TUF client") err := c.update() if err != nil { logrus.Debug("Error occurred. Root will be downloaded and another update attempted") logrus.Debug("Resetting the TUF builder...") c.newBuilder = c.newBuilder.BootstrapNewBuilder() if err := c.updateRoot(); err != nil { logrus.Debug("Client Update (Root): ", err) return nil, nil, err } // If we error again, we now have the latest root and just want to fail // out as there's no expectation the problem can be resolved automatically logrus.Debug("retrying TUF client update") if err := c.update(); err != nil { return nil, nil, err } } return c.newBuilder.Finish() }
[ "func", "(", "c", "*", "tufClient", ")", "Update", "(", ")", "(", "*", "tuf", ".", "Repo", ",", "*", "tuf", ".", "Repo", ",", "error", ")", "{", "logrus", ".", "Debug", "(", "\"updating TUF client\"", ")", "\n", "err", ":=", "c", ".", "update", "...
// Update performs an update to the TUF repo as defined by the TUF spec
[ "Update", "performs", "an", "update", "to", "the", "TUF", "repo", "as", "defined", "by", "the", "TUF", "spec" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/tufclient.go#L27-L56
train
theupdateframework/notary
client/tufclient.go
updateRoot
func (c *tufClient) updateRoot() error { // Get current root version currentRootConsistentInfo := c.oldBuilder.GetConsistentInfo(data.CanonicalRootRole) currentVersion := c.oldBuilder.GetLoadedVersion(currentRootConsistentInfo.RoleName) // Get new root version raw, err := c.downloadRoot() switch err.(type) { case *trustpinning.ErrRootRotationFail: // Rotation errors are okay since we haven't yet downloaded // all intermediate root files break case nil: // No error updating root - we were at most 1 version behind return nil default: // Return any non-rotation error. return err } // Load current version into newBuilder currentRaw, err := c.cache.GetSized(data.CanonicalRootRole.String(), -1) if err != nil { logrus.Debugf("error loading %d.%s: %s", currentVersion, data.CanonicalRootRole, err) return err } if err := c.newBuilder.LoadRootForUpdate(currentRaw, currentVersion, false); err != nil { logrus.Debugf("%d.%s is invalid: %s", currentVersion, data.CanonicalRootRole, err) return err } // Extract newest version number signedRoot := &data.Signed{} if err := json.Unmarshal(raw, signedRoot); err != nil { return err } newestRoot, err := data.RootFromSigned(signedRoot) if err != nil { return err } newestVersion := newestRoot.Signed.SignedCommon.Version // Update from current + 1 (current already loaded) to newest - 1 (newest loaded below) if err := c.updateRootVersions(currentVersion+1, newestVersion-1); err != nil { return err } // Already downloaded newest, verify it against newest - 1 if err := c.newBuilder.LoadRootForUpdate(raw, newestVersion, true); err != nil { logrus.Debugf("downloaded %d.%s is invalid: %s", newestVersion, data.CanonicalRootRole, err) return err } logrus.Debugf("successfully verified downloaded %d.%s", newestVersion, data.CanonicalRootRole) // Write newest to cache if err := c.cache.Set(data.CanonicalRootRole.String(), raw); err != nil { logrus.Debugf("unable to write %d.%s to cache: %s", newestVersion, data.CanonicalRootRole, err) } logrus.Debugf("finished updating root files") return nil }
go
func (c *tufClient) updateRoot() error { // Get current root version currentRootConsistentInfo := c.oldBuilder.GetConsistentInfo(data.CanonicalRootRole) currentVersion := c.oldBuilder.GetLoadedVersion(currentRootConsistentInfo.RoleName) // Get new root version raw, err := c.downloadRoot() switch err.(type) { case *trustpinning.ErrRootRotationFail: // Rotation errors are okay since we haven't yet downloaded // all intermediate root files break case nil: // No error updating root - we were at most 1 version behind return nil default: // Return any non-rotation error. return err } // Load current version into newBuilder currentRaw, err := c.cache.GetSized(data.CanonicalRootRole.String(), -1) if err != nil { logrus.Debugf("error loading %d.%s: %s", currentVersion, data.CanonicalRootRole, err) return err } if err := c.newBuilder.LoadRootForUpdate(currentRaw, currentVersion, false); err != nil { logrus.Debugf("%d.%s is invalid: %s", currentVersion, data.CanonicalRootRole, err) return err } // Extract newest version number signedRoot := &data.Signed{} if err := json.Unmarshal(raw, signedRoot); err != nil { return err } newestRoot, err := data.RootFromSigned(signedRoot) if err != nil { return err } newestVersion := newestRoot.Signed.SignedCommon.Version // Update from current + 1 (current already loaded) to newest - 1 (newest loaded below) if err := c.updateRootVersions(currentVersion+1, newestVersion-1); err != nil { return err } // Already downloaded newest, verify it against newest - 1 if err := c.newBuilder.LoadRootForUpdate(raw, newestVersion, true); err != nil { logrus.Debugf("downloaded %d.%s is invalid: %s", newestVersion, data.CanonicalRootRole, err) return err } logrus.Debugf("successfully verified downloaded %d.%s", newestVersion, data.CanonicalRootRole) // Write newest to cache if err := c.cache.Set(data.CanonicalRootRole.String(), raw); err != nil { logrus.Debugf("unable to write %d.%s to cache: %s", newestVersion, data.CanonicalRootRole, err) } logrus.Debugf("finished updating root files") return nil }
[ "func", "(", "c", "*", "tufClient", ")", "updateRoot", "(", ")", "error", "{", "currentRootConsistentInfo", ":=", "c", ".", "oldBuilder", ".", "GetConsistentInfo", "(", "data", ".", "CanonicalRootRole", ")", "\n", "currentVersion", ":=", "c", ".", "oldBuilder"...
// updateRoot checks if there is a newer version of the root available, and if so // downloads all intermediate root files to allow proper key rotation.
[ "updateRoot", "checks", "if", "there", "is", "a", "newer", "version", "of", "the", "root", "available", "and", "if", "so", "downloads", "all", "intermediate", "root", "files", "to", "allow", "proper", "key", "rotation", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/tufclient.go#L77-L138
train
theupdateframework/notary
client/tufclient.go
updateRootVersions
func (c *tufClient) updateRootVersions(fromVersion, toVersion int) error { for v := fromVersion; v <= toVersion; v++ { logrus.Debugf("updating root from version %d to version %d, currently fetching %d", fromVersion, toVersion, v) versionedRole := fmt.Sprintf("%d.%s", v, data.CanonicalRootRole) raw, err := c.remote.GetSized(versionedRole, -1) if err != nil { logrus.Debugf("error downloading %s: %s", versionedRole, err) return err } if err := c.newBuilder.LoadRootForUpdate(raw, v, false); err != nil { logrus.Debugf("downloaded %s is invalid: %s", versionedRole, err) return err } logrus.Debugf("successfully verified downloaded %s", versionedRole) } return nil }
go
func (c *tufClient) updateRootVersions(fromVersion, toVersion int) error { for v := fromVersion; v <= toVersion; v++ { logrus.Debugf("updating root from version %d to version %d, currently fetching %d", fromVersion, toVersion, v) versionedRole := fmt.Sprintf("%d.%s", v, data.CanonicalRootRole) raw, err := c.remote.GetSized(versionedRole, -1) if err != nil { logrus.Debugf("error downloading %s: %s", versionedRole, err) return err } if err := c.newBuilder.LoadRootForUpdate(raw, v, false); err != nil { logrus.Debugf("downloaded %s is invalid: %s", versionedRole, err) return err } logrus.Debugf("successfully verified downloaded %s", versionedRole) } return nil }
[ "func", "(", "c", "*", "tufClient", ")", "updateRootVersions", "(", "fromVersion", ",", "toVersion", "int", ")", "error", "{", "for", "v", ":=", "fromVersion", ";", "v", "<=", "toVersion", ";", "v", "++", "{", "logrus", ".", "Debugf", "(", "\"updating ro...
// updateRootVersions updates the root from it's current version to a target, rotating keys // as they are found
[ "updateRootVersions", "updates", "the", "root", "from", "it", "s", "current", "version", "to", "a", "target", "rotating", "keys", "as", "they", "are", "found" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/tufclient.go#L142-L160
train
theupdateframework/notary
client/tufclient.go
downloadSnapshot
func (c *tufClient) downloadSnapshot() error { logrus.Debug("Loading snapshot...") role := data.CanonicalSnapshotRole consistentInfo := c.newBuilder.GetConsistentInfo(role) _, err := c.tryLoadCacheThenRemote(consistentInfo) return err }
go
func (c *tufClient) downloadSnapshot() error { logrus.Debug("Loading snapshot...") role := data.CanonicalSnapshotRole consistentInfo := c.newBuilder.GetConsistentInfo(role) _, err := c.tryLoadCacheThenRemote(consistentInfo) return err }
[ "func", "(", "c", "*", "tufClient", ")", "downloadSnapshot", "(", ")", "error", "{", "logrus", ".", "Debug", "(", "\"Loading snapshot...\"", ")", "\n", "role", ":=", "data", ".", "CanonicalSnapshotRole", "\n", "consistentInfo", ":=", "c", ".", "newBuilder", ...
// downloadSnapshot is responsible for downloading the snapshot.json
[ "downloadSnapshot", "is", "responsible", "for", "downloading", "the", "snapshot", ".", "json" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/tufclient.go#L201-L208
train
theupdateframework/notary
client/tufclient.go
downloadTargets
func (c *tufClient) downloadTargets() error { toDownload := []data.DelegationRole{{ BaseRole: data.BaseRole{Name: data.CanonicalTargetsRole}, Paths: []string{""}, }} for len(toDownload) > 0 { role := toDownload[0] toDownload = toDownload[1:] consistentInfo := c.newBuilder.GetConsistentInfo(role.Name) if !consistentInfo.ChecksumKnown() { logrus.Debugf("skipping %s because there is no checksum for it", role.Name) continue } children, err := c.getTargetsFile(role, consistentInfo) switch err.(type) { case signed.ErrExpired, signed.ErrRoleThreshold: if role.Name == data.CanonicalTargetsRole { return err } logrus.Warnf("Error getting %s: %s", role.Name, err) break case nil: toDownload = append(children, toDownload...) default: return err } } return nil }
go
func (c *tufClient) downloadTargets() error { toDownload := []data.DelegationRole{{ BaseRole: data.BaseRole{Name: data.CanonicalTargetsRole}, Paths: []string{""}, }} for len(toDownload) > 0 { role := toDownload[0] toDownload = toDownload[1:] consistentInfo := c.newBuilder.GetConsistentInfo(role.Name) if !consistentInfo.ChecksumKnown() { logrus.Debugf("skipping %s because there is no checksum for it", role.Name) continue } children, err := c.getTargetsFile(role, consistentInfo) switch err.(type) { case signed.ErrExpired, signed.ErrRoleThreshold: if role.Name == data.CanonicalTargetsRole { return err } logrus.Warnf("Error getting %s: %s", role.Name, err) break case nil: toDownload = append(children, toDownload...) default: return err } } return nil }
[ "func", "(", "c", "*", "tufClient", ")", "downloadTargets", "(", ")", "error", "{", "toDownload", ":=", "[", "]", "data", ".", "DelegationRole", "{", "{", "BaseRole", ":", "data", ".", "BaseRole", "{", "Name", ":", "data", ".", "CanonicalTargetsRole", "}...
// downloadTargets downloads all targets and delegated targets for the repository. // It uses a pre-order tree traversal as it's necessary to download parents first // to obtain the keys to validate children.
[ "downloadTargets", "downloads", "all", "targets", "and", "delegated", "targets", "for", "the", "repository", ".", "It", "uses", "a", "pre", "-", "order", "tree", "traversal", "as", "it", "s", "necessary", "to", "download", "parents", "first", "to", "obtain", ...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/tufclient.go#L213-L244
train
theupdateframework/notary
client/tufclient.go
downloadRoot
func (c *tufClient) downloadRoot() ([]byte, error) { role := data.CanonicalRootRole consistentInfo := c.newBuilder.GetConsistentInfo(role) // We can't read an exact size for the root metadata without risking getting stuck in the TUF update cycle // since it's possible that downloading timestamp/snapshot metadata may fail due to a signature mismatch if !consistentInfo.ChecksumKnown() { logrus.Debugf("Loading root with no expected checksum") // get the cached root, if it exists, just for version checking cachedRoot, _ := c.cache.GetSized(role.String(), -1) // prefer to download a new root return c.tryLoadRemote(consistentInfo, cachedRoot) } return c.tryLoadCacheThenRemote(consistentInfo) }
go
func (c *tufClient) downloadRoot() ([]byte, error) { role := data.CanonicalRootRole consistentInfo := c.newBuilder.GetConsistentInfo(role) // We can't read an exact size for the root metadata without risking getting stuck in the TUF update cycle // since it's possible that downloading timestamp/snapshot metadata may fail due to a signature mismatch if !consistentInfo.ChecksumKnown() { logrus.Debugf("Loading root with no expected checksum") // get the cached root, if it exists, just for version checking cachedRoot, _ := c.cache.GetSized(role.String(), -1) // prefer to download a new root return c.tryLoadRemote(consistentInfo, cachedRoot) } return c.tryLoadCacheThenRemote(consistentInfo) }
[ "func", "(", "c", "*", "tufClient", ")", "downloadRoot", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "role", ":=", "data", ".", "CanonicalRootRole", "\n", "consistentInfo", ":=", "c", ".", "newBuilder", ".", "GetConsistentInfo", "(", "role",...
// downloadRoot is responsible for downloading the root.json
[ "downloadRoot", "is", "responsible", "for", "downloading", "the", "root", ".", "json" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/tufclient.go#L262-L277
train
theupdateframework/notary
client/changelist/change.go
NewTUFChange
func NewTUFChange(action string, role data.RoleName, changeType, changePath string, content []byte) *TUFChange { return &TUFChange{ Actn: action, Role: role, ChangeType: changeType, ChangePath: changePath, Data: content, } }
go
func NewTUFChange(action string, role data.RoleName, changeType, changePath string, content []byte) *TUFChange { return &TUFChange{ Actn: action, Role: role, ChangeType: changeType, ChangePath: changePath, Data: content, } }
[ "func", "NewTUFChange", "(", "action", "string", ",", "role", "data", ".", "RoleName", ",", "changeType", ",", "changePath", "string", ",", "content", "[", "]", "byte", ")", "*", "TUFChange", "{", "return", "&", "TUFChange", "{", "Actn", ":", "action", "...
// NewTUFChange initializes a TUFChange object
[ "NewTUFChange", "initializes", "a", "TUFChange", "object" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/change.go#L45-L53
train
theupdateframework/notary
client/changelist/change.go
ToNewRole
func (td TUFDelegation) ToNewRole(scope data.RoleName) (*data.Role, error) { name := scope if td.NewName != "" { name = td.NewName } return data.NewRole(name, td.NewThreshold, td.AddKeys.IDs(), td.AddPaths) }
go
func (td TUFDelegation) ToNewRole(scope data.RoleName) (*data.Role, error) { name := scope if td.NewName != "" { name = td.NewName } return data.NewRole(name, td.NewThreshold, td.AddKeys.IDs(), td.AddPaths) }
[ "func", "(", "td", "TUFDelegation", ")", "ToNewRole", "(", "scope", "data", ".", "RoleName", ")", "(", "*", "data", ".", "Role", ",", "error", ")", "{", "name", ":=", "scope", "\n", "if", "td", ".", "NewName", "!=", "\"\"", "{", "name", "=", "td", ...
// ToNewRole creates a fresh role object from the TUFDelegation data
[ "ToNewRole", "creates", "a", "fresh", "role", "object", "from", "the", "TUFDelegation", "data" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/change.go#L94-L100
train
theupdateframework/notary
signer/keydbstore/rethink_keydbstore.go
NewRethinkDBKeyStore
func NewRethinkDBKeyStore(dbName, username, password string, passphraseRetriever notary.PassRetriever, defaultPassAlias string, rethinkSession *gorethink.Session) *RethinkDBKeyStore { return &RethinkDBKeyStore{ sess: rethinkSession, defaultPassAlias: defaultPassAlias, dbName: dbName, retriever: passphraseRetriever, user: username, password: password, nowFunc: time.Now, } }
go
func NewRethinkDBKeyStore(dbName, username, password string, passphraseRetriever notary.PassRetriever, defaultPassAlias string, rethinkSession *gorethink.Session) *RethinkDBKeyStore { return &RethinkDBKeyStore{ sess: rethinkSession, defaultPassAlias: defaultPassAlias, dbName: dbName, retriever: passphraseRetriever, user: username, password: password, nowFunc: time.Now, } }
[ "func", "NewRethinkDBKeyStore", "(", "dbName", ",", "username", ",", "password", "string", ",", "passphraseRetriever", "notary", ".", "PassRetriever", ",", "defaultPassAlias", "string", ",", "rethinkSession", "*", "gorethink", ".", "Session", ")", "*", "RethinkDBKey...
// NewRethinkDBKeyStore returns a new RethinkDBKeyStore backed by a RethinkDB database
[ "NewRethinkDBKeyStore", "returns", "a", "new", "RethinkDBKeyStore", "backed", "by", "a", "RethinkDB", "database" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/rethink_keydbstore.go#L104-L114
train
theupdateframework/notary
signer/keydbstore/rethink_keydbstore.go
getKey
func (rdb *RethinkDBKeyStore) getKey(keyID string) (*RDBPrivateKey, string, error) { // Retrieve the RethinkDB private key from the database dbPrivateKey := RDBPrivateKey{} res, err := gorethink.DB(rdb.dbName).Table(dbPrivateKey.TableName()).Filter(gorethink.Row.Field("key_id").Eq(keyID)).Run(rdb.sess) if err != nil { return nil, "", err } defer res.Close() err = res.One(&dbPrivateKey) if err != nil { return nil, "", trustmanager.ErrKeyNotFound{} } // Get the passphrase to use for this key passphrase, _, err := rdb.retriever(dbPrivateKey.KeyID, dbPrivateKey.PassphraseAlias, false, 1) if err != nil { return nil, "", err } // Decrypt private bytes from the gorm key decryptedPrivKey, _, err := jose.Decode(string(dbPrivateKey.Private), passphrase) if err != nil { return nil, "", err } return &dbPrivateKey, decryptedPrivKey, nil }
go
func (rdb *RethinkDBKeyStore) getKey(keyID string) (*RDBPrivateKey, string, error) { // Retrieve the RethinkDB private key from the database dbPrivateKey := RDBPrivateKey{} res, err := gorethink.DB(rdb.dbName).Table(dbPrivateKey.TableName()).Filter(gorethink.Row.Field("key_id").Eq(keyID)).Run(rdb.sess) if err != nil { return nil, "", err } defer res.Close() err = res.One(&dbPrivateKey) if err != nil { return nil, "", trustmanager.ErrKeyNotFound{} } // Get the passphrase to use for this key passphrase, _, err := rdb.retriever(dbPrivateKey.KeyID, dbPrivateKey.PassphraseAlias, false, 1) if err != nil { return nil, "", err } // Decrypt private bytes from the gorm key decryptedPrivKey, _, err := jose.Decode(string(dbPrivateKey.Private), passphrase) if err != nil { return nil, "", err } return &dbPrivateKey, decryptedPrivKey, nil }
[ "func", "(", "rdb", "*", "RethinkDBKeyStore", ")", "getKey", "(", "keyID", "string", ")", "(", "*", "RDBPrivateKey", ",", "string", ",", "error", ")", "{", "dbPrivateKey", ":=", "RDBPrivateKey", "{", "}", "\n", "res", ",", "err", ":=", "gorethink", ".", ...
// getKeyBytes returns the RDBPrivateKey given a KeyID, as well as the decrypted private bytes
[ "getKeyBytes", "returns", "the", "RDBPrivateKey", "given", "a", "KeyID", "as", "well", "as", "the", "decrypted", "private", "bytes" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/rethink_keydbstore.go#L161-L188
train
theupdateframework/notary
signer/keydbstore/rethink_keydbstore.go
GetKey
func (rdb *RethinkDBKeyStore) GetKey(keyID string) data.PublicKey { dbPrivateKey, _, err := rdb.getKey(keyID) if err != nil { return nil } return data.NewPublicKey(dbPrivateKey.Algorithm, dbPrivateKey.Public) }
go
func (rdb *RethinkDBKeyStore) GetKey(keyID string) data.PublicKey { dbPrivateKey, _, err := rdb.getKey(keyID) if err != nil { return nil } return data.NewPublicKey(dbPrivateKey.Algorithm, dbPrivateKey.Public) }
[ "func", "(", "rdb", "*", "RethinkDBKeyStore", ")", "GetKey", "(", "keyID", "string", ")", "data", ".", "PublicKey", "{", "dbPrivateKey", ",", "_", ",", "err", ":=", "rdb", ".", "getKey", "(", "keyID", ")", "\n", "if", "err", "!=", "nil", "{", "return...
// GetKey returns the PublicKey given a KeyID, and does not activate the key
[ "GetKey", "returns", "the", "PublicKey", "given", "a", "KeyID", "and", "does", "not", "activate", "the", "key" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/rethink_keydbstore.go#L209-L216
train
theupdateframework/notary
signer/keydbstore/rethink_keydbstore.go
RemoveKey
func (rdb RethinkDBKeyStore) RemoveKey(keyID string) error { // Delete the key from the database dbPrivateKey := RDBPrivateKey{KeyID: keyID} _, err := gorethink.DB(rdb.dbName).Table(dbPrivateKey.TableName()).Filter(gorethink.Row.Field("key_id").Eq(keyID)).Delete().RunWrite(rdb.sess) if err != nil { return fmt.Errorf("unable to delete private key %s from database: %s", keyID, err.Error()) } return nil }
go
func (rdb RethinkDBKeyStore) RemoveKey(keyID string) error { // Delete the key from the database dbPrivateKey := RDBPrivateKey{KeyID: keyID} _, err := gorethink.DB(rdb.dbName).Table(dbPrivateKey.TableName()).Filter(gorethink.Row.Field("key_id").Eq(keyID)).Delete().RunWrite(rdb.sess) if err != nil { return fmt.Errorf("unable to delete private key %s from database: %s", keyID, err.Error()) } return nil }
[ "func", "(", "rdb", "RethinkDBKeyStore", ")", "RemoveKey", "(", "keyID", "string", ")", "error", "{", "dbPrivateKey", ":=", "RDBPrivateKey", "{", "KeyID", ":", "keyID", "}", "\n", "_", ",", "err", ":=", "gorethink", ".", "DB", "(", "rdb", ".", "dbName", ...
// RemoveKey removes the key from the table
[ "RemoveKey", "removes", "the", "key", "from", "the", "table" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/rethink_keydbstore.go#L229-L238
train
theupdateframework/notary
signer/keydbstore/rethink_keydbstore.go
Bootstrap
func (rdb RethinkDBKeyStore) Bootstrap() error { if err := rethinkdb.SetupDB(rdb.sess, rdb.dbName, []rethinkdb.Table{ PrivateKeysRethinkTable, }); err != nil { return err } return rethinkdb.CreateAndGrantDBUser(rdb.sess, rdb.dbName, rdb.user, rdb.password) }
go
func (rdb RethinkDBKeyStore) Bootstrap() error { if err := rethinkdb.SetupDB(rdb.sess, rdb.dbName, []rethinkdb.Table{ PrivateKeysRethinkTable, }); err != nil { return err } return rethinkdb.CreateAndGrantDBUser(rdb.sess, rdb.dbName, rdb.user, rdb.password) }
[ "func", "(", "rdb", "RethinkDBKeyStore", ")", "Bootstrap", "(", ")", "error", "{", "if", "err", ":=", "rethinkdb", ".", "SetupDB", "(", "rdb", ".", "sess", ",", "rdb", ".", "dbName", ",", "[", "]", "rethinkdb", ".", "Table", "{", "PrivateKeysRethinkTable...
// Bootstrap sets up the database and tables, also creating the notary signer user with appropriate db permission
[ "Bootstrap", "sets", "up", "the", "database", "and", "tables", "also", "creating", "the", "notary", "signer", "user", "with", "appropriate", "db", "permission" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/rethink_keydbstore.go#L310-L317
train
theupdateframework/notary
tuf/signed/verify.go
VerifyExpiry
func VerifyExpiry(s *data.SignedCommon, role data.RoleName) error { if IsExpired(s.Expires) { logrus.Errorf("Metadata for %s expired", role) return ErrExpired{Role: role, Expired: s.Expires.Format("Mon Jan 2 15:04:05 MST 2006")} } return nil }
go
func VerifyExpiry(s *data.SignedCommon, role data.RoleName) error { if IsExpired(s.Expires) { logrus.Errorf("Metadata for %s expired", role) return ErrExpired{Role: role, Expired: s.Expires.Format("Mon Jan 2 15:04:05 MST 2006")} } return nil }
[ "func", "VerifyExpiry", "(", "s", "*", "data", ".", "SignedCommon", ",", "role", "data", ".", "RoleName", ")", "error", "{", "if", "IsExpired", "(", "s", ".", "Expires", ")", "{", "logrus", ".", "Errorf", "(", "\"Metadata for %s expired\"", ",", "role", ...
// VerifyExpiry returns ErrExpired if the metadata is expired
[ "VerifyExpiry", "returns", "ErrExpired", "if", "the", "metadata", "is", "expired" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/verify.go#L28-L34
train
theupdateframework/notary
tuf/signed/verify.go
VerifyVersion
func VerifyVersion(s *data.SignedCommon, minVersion int) error { if s.Version < minVersion { return ErrLowVersion{Actual: s.Version, Current: minVersion} } return nil }
go
func VerifyVersion(s *data.SignedCommon, minVersion int) error { if s.Version < minVersion { return ErrLowVersion{Actual: s.Version, Current: minVersion} } return nil }
[ "func", "VerifyVersion", "(", "s", "*", "data", ".", "SignedCommon", ",", "minVersion", "int", ")", "error", "{", "if", "s", ".", "Version", "<", "minVersion", "{", "return", "ErrLowVersion", "{", "Actual", ":", "s", ".", "Version", ",", "Current", ":", ...
// VerifyVersion returns ErrLowVersion if the metadata version is lower than the min version
[ "VerifyVersion", "returns", "ErrLowVersion", "if", "the", "metadata", "version", "is", "lower", "than", "the", "min", "version" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/verify.go#L37-L42
train
theupdateframework/notary
tuf/signed/verify.go
VerifySignatures
func VerifySignatures(s *data.Signed, roleData data.BaseRole) error { if len(s.Signatures) == 0 { return ErrNoSignatures } if roleData.Threshold < 1 { return ErrRoleThreshold{} } logrus.Debugf("%s role has key IDs: %s", roleData.Name, strings.Join(roleData.ListKeyIDs(), ",")) // remarshal the signed part so we can verify the signature, since the signature has // to be of a canonically marshalled signed object var decoded map[string]interface{} if err := json.Unmarshal(*s.Signed, &decoded); err != nil { return err } msg, err := json.MarshalCanonical(decoded) if err != nil { return err } valid := make(map[string]struct{}) for i := range s.Signatures { sig := &(s.Signatures[i]) logrus.Debug("verifying signature for key ID: ", sig.KeyID) key, ok := roleData.Keys[sig.KeyID] if !ok { logrus.Debugf("continuing b/c keyid lookup was nil: %s\n", sig.KeyID) continue } // Check that the signature key ID actually matches the content ID of the key if key.ID() != sig.KeyID { return ErrInvalidKeyID{} } if err := VerifySignature(msg, sig, key); err != nil { logrus.Debugf("continuing b/c %s", err.Error()) continue } valid[sig.KeyID] = struct{}{} } if len(valid) < roleData.Threshold { return ErrRoleThreshold{ Msg: fmt.Sprintf("valid signatures did not meet threshold for %s", roleData.Name), } } return nil }
go
func VerifySignatures(s *data.Signed, roleData data.BaseRole) error { if len(s.Signatures) == 0 { return ErrNoSignatures } if roleData.Threshold < 1 { return ErrRoleThreshold{} } logrus.Debugf("%s role has key IDs: %s", roleData.Name, strings.Join(roleData.ListKeyIDs(), ",")) // remarshal the signed part so we can verify the signature, since the signature has // to be of a canonically marshalled signed object var decoded map[string]interface{} if err := json.Unmarshal(*s.Signed, &decoded); err != nil { return err } msg, err := json.MarshalCanonical(decoded) if err != nil { return err } valid := make(map[string]struct{}) for i := range s.Signatures { sig := &(s.Signatures[i]) logrus.Debug("verifying signature for key ID: ", sig.KeyID) key, ok := roleData.Keys[sig.KeyID] if !ok { logrus.Debugf("continuing b/c keyid lookup was nil: %s\n", sig.KeyID) continue } // Check that the signature key ID actually matches the content ID of the key if key.ID() != sig.KeyID { return ErrInvalidKeyID{} } if err := VerifySignature(msg, sig, key); err != nil { logrus.Debugf("continuing b/c %s", err.Error()) continue } valid[sig.KeyID] = struct{}{} } if len(valid) < roleData.Threshold { return ErrRoleThreshold{ Msg: fmt.Sprintf("valid signatures did not meet threshold for %s", roleData.Name), } } return nil }
[ "func", "VerifySignatures", "(", "s", "*", "data", ".", "Signed", ",", "roleData", "data", ".", "BaseRole", ")", "error", "{", "if", "len", "(", "s", ".", "Signatures", ")", "==", "0", "{", "return", "ErrNoSignatures", "\n", "}", "\n", "if", "roleData"...
// VerifySignatures checks the we have sufficient valid signatures for the given role
[ "VerifySignatures", "checks", "the", "we", "have", "sufficient", "valid", "signatures", "for", "the", "given", "role" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/verify.go#L45-L92
train
theupdateframework/notary
tuf/signed/verify.go
VerifySignature
func VerifySignature(msg []byte, sig *data.Signature, pk data.PublicKey) error { // method lookup is consistent due to Unmarshal JSON doing lower case for us. method := sig.Method verifier, ok := Verifiers[method] if !ok { return fmt.Errorf("signing method is not supported: %s", sig.Method) } if err := verifier.Verify(pk, sig.Signature, msg); err != nil { return fmt.Errorf("signature was invalid") } sig.IsValid = true return nil }
go
func VerifySignature(msg []byte, sig *data.Signature, pk data.PublicKey) error { // method lookup is consistent due to Unmarshal JSON doing lower case for us. method := sig.Method verifier, ok := Verifiers[method] if !ok { return fmt.Errorf("signing method is not supported: %s", sig.Method) } if err := verifier.Verify(pk, sig.Signature, msg); err != nil { return fmt.Errorf("signature was invalid") } sig.IsValid = true return nil }
[ "func", "VerifySignature", "(", "msg", "[", "]", "byte", ",", "sig", "*", "data", ".", "Signature", ",", "pk", "data", ".", "PublicKey", ")", "error", "{", "method", ":=", "sig", ".", "Method", "\n", "verifier", ",", "ok", ":=", "Verifiers", "[", "me...
// VerifySignature checks a single signature and public key against a payload // If the signature is verified, the signature's is valid field will actually // be mutated to be equal to the boolean true
[ "VerifySignature", "checks", "a", "single", "signature", "and", "public", "key", "against", "a", "payload", "If", "the", "signature", "is", "verified", "the", "signature", "s", "is", "valid", "field", "will", "actually", "be", "mutated", "to", "be", "equal", ...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/verify.go#L97-L110
train
theupdateframework/notary
tuf/signed/verify.go
VerifyPublicKeyMatchesPrivateKey
func VerifyPublicKeyMatchesPrivateKey(privKey data.PrivateKey, pubKey data.PublicKey) error { pubKeyID, err := utils.CanonicalKeyID(pubKey) if err != nil { return fmt.Errorf("could not verify key pair: %v", err) } if privKey == nil || pubKeyID != privKey.ID() { return fmt.Errorf("private key is nil or does not match public key") } return nil }
go
func VerifyPublicKeyMatchesPrivateKey(privKey data.PrivateKey, pubKey data.PublicKey) error { pubKeyID, err := utils.CanonicalKeyID(pubKey) if err != nil { return fmt.Errorf("could not verify key pair: %v", err) } if privKey == nil || pubKeyID != privKey.ID() { return fmt.Errorf("private key is nil or does not match public key") } return nil }
[ "func", "VerifyPublicKeyMatchesPrivateKey", "(", "privKey", "data", ".", "PrivateKey", ",", "pubKey", "data", ".", "PublicKey", ")", "error", "{", "pubKeyID", ",", "err", ":=", "utils", ".", "CanonicalKeyID", "(", "pubKey", ")", "\n", "if", "err", "!=", "nil...
// VerifyPublicKeyMatchesPrivateKey checks if the private key and the public keys forms valid key pairs. // Supports both x509 certificate PublicKeys and non-certificate PublicKeys
[ "VerifyPublicKeyMatchesPrivateKey", "checks", "if", "the", "private", "key", "and", "the", "public", "keys", "forms", "valid", "key", "pairs", ".", "Supports", "both", "x509", "certificate", "PublicKeys", "and", "non", "-", "certificate", "PublicKeys" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/verify.go#L114-L123
train
theupdateframework/notary
cmd/notary/repo_factory.go
ConfigureRepo
func ConfigureRepo(v *viper.Viper, retriever notary.PassRetriever, onlineOperation bool, permission httpAccess) RepoFactory { localRepo := func(gun data.GUN) (client.Repository, error) { var rt http.RoundTripper trustPin, err := getTrustPinning(v) if err != nil { return nil, err } if onlineOperation { rt, err = getTransport(v, gun, permission) if err != nil { return nil, err } } return client.NewFileCachedRepository( v.GetString("trust_dir"), gun, getRemoteTrustServer(v), rt, retriever, trustPin, ) } return localRepo }
go
func ConfigureRepo(v *viper.Viper, retriever notary.PassRetriever, onlineOperation bool, permission httpAccess) RepoFactory { localRepo := func(gun data.GUN) (client.Repository, error) { var rt http.RoundTripper trustPin, err := getTrustPinning(v) if err != nil { return nil, err } if onlineOperation { rt, err = getTransport(v, gun, permission) if err != nil { return nil, err } } return client.NewFileCachedRepository( v.GetString("trust_dir"), gun, getRemoteTrustServer(v), rt, retriever, trustPin, ) } return localRepo }
[ "func", "ConfigureRepo", "(", "v", "*", "viper", ".", "Viper", ",", "retriever", "notary", ".", "PassRetriever", ",", "onlineOperation", "bool", ",", "permission", "httpAccess", ")", "RepoFactory", "{", "localRepo", ":=", "func", "(", "gun", "data", ".", "GU...
// ConfigureRepo takes in the configuration parameters and returns a repoFactory that can // initialize new client.Repository objects with the correct upstreams and password // retrieval mechanisms.
[ "ConfigureRepo", "takes", "in", "the", "configuration", "parameters", "and", "returns", "a", "repoFactory", "that", "can", "initialize", "new", "client", ".", "Repository", "objects", "with", "the", "correct", "upstreams", "and", "password", "retrieval", "mechanisms...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/repo_factory.go#L21-L45
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
SetYubikeyKeyMode
func SetYubikeyKeyMode(keyMode int) error { // technically 7 (1 | 2 | 4) is valid, but KeymodePinOnce + // KeymdoePinAlways don't really make sense together if keyMode < 0 || keyMode > 5 { return errors.New("Invalid key mode") } yubikeyKeymode = keyMode return nil }
go
func SetYubikeyKeyMode(keyMode int) error { // technically 7 (1 | 2 | 4) is valid, but KeymodePinOnce + // KeymdoePinAlways don't really make sense together if keyMode < 0 || keyMode > 5 { return errors.New("Invalid key mode") } yubikeyKeymode = keyMode return nil }
[ "func", "SetYubikeyKeyMode", "(", "keyMode", "int", ")", "error", "{", "if", "keyMode", "<", "0", "||", "keyMode", ">", "5", "{", "return", "errors", ".", "New", "(", "\"Invalid key mode\"", ")", "\n", "}", "\n", "yubikeyKeymode", "=", "keyMode", "\n", "...
// SetYubikeyKeyMode - sets the mode when generating yubikey keys. // This is to be used for testing. It does nothing if not building with tag // pkcs11.
[ "SetYubikeyKeyMode", "-", "sets", "the", "mode", "when", "generating", "yubikey", "keys", ".", "This", "is", "to", "be", "used", "for", "testing", ".", "It", "does", "nothing", "if", "not", "building", "with", "tag", "pkcs11", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L63-L71
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
NewYubiPrivateKey
func NewYubiPrivateKey(slot []byte, pubKey data.ECDSAPublicKey, passRetriever notary.PassRetriever) *YubiPrivateKey { return &YubiPrivateKey{ ECDSAPublicKey: pubKey, passRetriever: passRetriever, slot: slot, libLoader: defaultLoader, } }
go
func NewYubiPrivateKey(slot []byte, pubKey data.ECDSAPublicKey, passRetriever notary.PassRetriever) *YubiPrivateKey { return &YubiPrivateKey{ ECDSAPublicKey: pubKey, passRetriever: passRetriever, slot: slot, libLoader: defaultLoader, } }
[ "func", "NewYubiPrivateKey", "(", "slot", "[", "]", "byte", ",", "pubKey", "data", ".", "ECDSAPublicKey", ",", "passRetriever", "notary", ".", "PassRetriever", ")", "*", "YubiPrivateKey", "{", "return", "&", "YubiPrivateKey", "{", "ECDSAPublicKey", ":", "pubKey"...
// NewYubiPrivateKey returns a YubiPrivateKey, which implements the data.PrivateKey // interface except that the private material is inaccessible
[ "NewYubiPrivateKey", "returns", "a", "YubiPrivateKey", "which", "implements", "the", "data", ".", "PrivateKey", "interface", "except", "that", "the", "private", "material", "is", "inaccessible" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L148-L157
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
Public
func (ys *yubikeySigner) Public() crypto.PublicKey { publicKey, err := x509.ParsePKIXPublicKey(ys.YubiPrivateKey.Public()) if err != nil { return nil } return publicKey }
go
func (ys *yubikeySigner) Public() crypto.PublicKey { publicKey, err := x509.ParsePKIXPublicKey(ys.YubiPrivateKey.Public()) if err != nil { return nil } return publicKey }
[ "func", "(", "ys", "*", "yubikeySigner", ")", "Public", "(", ")", "crypto", ".", "PublicKey", "{", "publicKey", ",", "err", ":=", "x509", ".", "ParsePKIXPublicKey", "(", "ys", ".", "YubiPrivateKey", ".", "Public", "(", ")", ")", "\n", "if", "err", "!="...
// Public is a required method of the crypto.Signer interface
[ "Public", "is", "a", "required", "method", "of", "the", "crypto", ".", "Signer", "interface" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L160-L167
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
Sign
func (y *YubiPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) { ctx, session, err := SetupHSMEnv(pkcs11Lib, y.libLoader) if err != nil { return nil, err } defer cleanup(ctx, session) v := signed.Verifiers[data.ECDSASignature] for i := 0; i < sigAttempts; i++ { sig, err := sign(ctx, session, y.slot, y.passRetriever, msg) if err != nil { return nil, fmt.Errorf("failed to sign using Yubikey: %v", err) } if err := v.Verify(&y.ECDSAPublicKey, sig, msg); err == nil { return sig, nil } } return nil, errors.New("failed to generate signature on Yubikey") }
go
func (y *YubiPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) { ctx, session, err := SetupHSMEnv(pkcs11Lib, y.libLoader) if err != nil { return nil, err } defer cleanup(ctx, session) v := signed.Verifiers[data.ECDSASignature] for i := 0; i < sigAttempts; i++ { sig, err := sign(ctx, session, y.slot, y.passRetriever, msg) if err != nil { return nil, fmt.Errorf("failed to sign using Yubikey: %v", err) } if err := v.Verify(&y.ECDSAPublicKey, sig, msg); err == nil { return sig, nil } } return nil, errors.New("failed to generate signature on Yubikey") }
[ "func", "(", "y", "*", "YubiPrivateKey", ")", "Sign", "(", "rand", "io", ".", "Reader", ",", "msg", "[", "]", "byte", ",", "opts", "crypto", ".", "SignerOpts", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "ctx", ",", "session", ",", "err",...
// Sign is a required method of the crypto.Signer interface and the data.PrivateKey // interface
[ "Sign", "is", "a", "required", "method", "of", "the", "crypto", ".", "Signer", "interface", "and", "the", "data", ".", "PrivateKey", "interface" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L194-L212
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
ensurePrivateKeySize
func ensurePrivateKeySize(payload []byte) []byte { final := payload if len(payload) < ecdsaPrivateKeySize { final = make([]byte, ecdsaPrivateKeySize) copy(final[ecdsaPrivateKeySize-len(payload):], payload) } return final }
go
func ensurePrivateKeySize(payload []byte) []byte { final := payload if len(payload) < ecdsaPrivateKeySize { final = make([]byte, ecdsaPrivateKeySize) copy(final[ecdsaPrivateKeySize-len(payload):], payload) } return final }
[ "func", "ensurePrivateKeySize", "(", "payload", "[", "]", "byte", ")", "[", "]", "byte", "{", "final", ":=", "payload", "\n", "if", "len", "(", "payload", ")", "<", "ecdsaPrivateKeySize", "{", "final", "=", "make", "(", "[", "]", "byte", ",", "ecdsaPri...
// If a byte array is less than the number of bytes specified by // ecdsaPrivateKeySize, left-zero-pad the byte array until // it is the required size.
[ "If", "a", "byte", "array", "is", "less", "than", "the", "number", "of", "bytes", "specified", "by", "ecdsaPrivateKeySize", "left", "-", "zero", "-", "pad", "the", "byte", "array", "until", "it", "is", "the", "required", "size", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L217-L224
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
addECDSAKey
func addECDSAKey( ctx IPKCS11Ctx, session pkcs11.SessionHandle, privKey data.PrivateKey, pkcs11KeyID []byte, passRetriever notary.PassRetriever, role data.RoleName, ) error { logrus.Debugf("Attempting to add key to yubikey with ID: %s", privKey.ID()) err := login(ctx, session, passRetriever, pkcs11.CKU_SO, SOUserPin) if err != nil { return err } defer ctx.Logout(session) // Create an ecdsa.PrivateKey out of the private key bytes ecdsaPrivKey, err := x509.ParseECPrivateKey(privKey.Private()) if err != nil { return err } ecdsaPrivKeyD := ensurePrivateKeySize(ecdsaPrivKey.D.Bytes()) // Hard-coded policy: the generated certificate expires in 10 years. startTime := time.Now() template, err := utils.NewCertificate(role.String(), startTime, startTime.AddDate(10, 0, 0)) if err != nil { return fmt.Errorf("failed to create the certificate template: %v", err) } certBytes, err := x509.CreateCertificate(rand.Reader, template, template, ecdsaPrivKey.Public(), ecdsaPrivKey) if err != nil { return fmt.Errorf("failed to create the certificate: %v", err) } certTemplate := []*pkcs11.Attribute{ pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_CERTIFICATE), pkcs11.NewAttribute(pkcs11.CKA_VALUE, certBytes), pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID), } privateKeyTemplate := []*pkcs11.Attribute{ pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY), pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_ECDSA), pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID), pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07}), pkcs11.NewAttribute(pkcs11.CKA_VALUE, ecdsaPrivKeyD), pkcs11.NewAttribute(pkcs11.CKA_VENDOR_DEFINED, yubikeyKeymode), } _, err = ctx.CreateObject(session, certTemplate) if err != nil { return fmt.Errorf("error importing: %v", err) } _, err = ctx.CreateObject(session, privateKeyTemplate) if err != nil { return fmt.Errorf("error importing: %v", err) } return nil }
go
func addECDSAKey( ctx IPKCS11Ctx, session pkcs11.SessionHandle, privKey data.PrivateKey, pkcs11KeyID []byte, passRetriever notary.PassRetriever, role data.RoleName, ) error { logrus.Debugf("Attempting to add key to yubikey with ID: %s", privKey.ID()) err := login(ctx, session, passRetriever, pkcs11.CKU_SO, SOUserPin) if err != nil { return err } defer ctx.Logout(session) // Create an ecdsa.PrivateKey out of the private key bytes ecdsaPrivKey, err := x509.ParseECPrivateKey(privKey.Private()) if err != nil { return err } ecdsaPrivKeyD := ensurePrivateKeySize(ecdsaPrivKey.D.Bytes()) // Hard-coded policy: the generated certificate expires in 10 years. startTime := time.Now() template, err := utils.NewCertificate(role.String(), startTime, startTime.AddDate(10, 0, 0)) if err != nil { return fmt.Errorf("failed to create the certificate template: %v", err) } certBytes, err := x509.CreateCertificate(rand.Reader, template, template, ecdsaPrivKey.Public(), ecdsaPrivKey) if err != nil { return fmt.Errorf("failed to create the certificate: %v", err) } certTemplate := []*pkcs11.Attribute{ pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_CERTIFICATE), pkcs11.NewAttribute(pkcs11.CKA_VALUE, certBytes), pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID), } privateKeyTemplate := []*pkcs11.Attribute{ pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY), pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_ECDSA), pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID), pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07}), pkcs11.NewAttribute(pkcs11.CKA_VALUE, ecdsaPrivKeyD), pkcs11.NewAttribute(pkcs11.CKA_VENDOR_DEFINED, yubikeyKeymode), } _, err = ctx.CreateObject(session, certTemplate) if err != nil { return fmt.Errorf("error importing: %v", err) } _, err = ctx.CreateObject(session, privateKeyTemplate) if err != nil { return fmt.Errorf("error importing: %v", err) } return nil }
[ "func", "addECDSAKey", "(", "ctx", "IPKCS11Ctx", ",", "session", "pkcs11", ".", "SessionHandle", ",", "privKey", "data", ".", "PrivateKey", ",", "pkcs11KeyID", "[", "]", "byte", ",", "passRetriever", "notary", ".", "PassRetriever", ",", "role", "data", ".", ...
// addECDSAKey adds a key to the yubikey
[ "addECDSAKey", "adds", "a", "key", "to", "the", "yubikey" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L227-L289
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
sign
func sign(ctx IPKCS11Ctx, session pkcs11.SessionHandle, pkcs11KeyID []byte, passRetriever notary.PassRetriever, payload []byte) ([]byte, error) { err := login(ctx, session, passRetriever, pkcs11.CKU_USER, UserPin) if err != nil { return nil, fmt.Errorf("error logging in: %v", err) } defer ctx.Logout(session) // Define the ECDSA Private key template class := pkcs11.CKO_PRIVATE_KEY privateKeyTemplate := []*pkcs11.Attribute{ pkcs11.NewAttribute(pkcs11.CKA_CLASS, class), pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_ECDSA), pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID), } if err := ctx.FindObjectsInit(session, privateKeyTemplate); err != nil { logrus.Debugf("Failed to init find objects: %s", err.Error()) return nil, err } obj, _, err := ctx.FindObjects(session, 1) if err != nil { logrus.Debugf("Failed to find objects: %v", err) return nil, err } if err = ctx.FindObjectsFinal(session); err != nil { logrus.Debugf("Failed to finalize find objects: %s", err.Error()) return nil, err } if len(obj) != 1 { return nil, errors.New("length of objects found not 1") } var sig []byte err = ctx.SignInit( session, []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_ECDSA, nil)}, obj[0]) if err != nil { return nil, err } // Get the SHA256 of the payload digest := sha256.Sum256(payload) if (yubikeyKeymode & KeymodeTouch) > 0 { touchToSignUI() defer touchDoneCallback() } // a call to Sign, whether or not Sign fails, will clear the SignInit sig, err = ctx.Sign(session, digest[:]) if err != nil { logrus.Debugf("Error while signing: %s", err) return nil, err } if sig == nil { return nil, errors.New("Failed to create signature") } return sig[:], nil }
go
func sign(ctx IPKCS11Ctx, session pkcs11.SessionHandle, pkcs11KeyID []byte, passRetriever notary.PassRetriever, payload []byte) ([]byte, error) { err := login(ctx, session, passRetriever, pkcs11.CKU_USER, UserPin) if err != nil { return nil, fmt.Errorf("error logging in: %v", err) } defer ctx.Logout(session) // Define the ECDSA Private key template class := pkcs11.CKO_PRIVATE_KEY privateKeyTemplate := []*pkcs11.Attribute{ pkcs11.NewAttribute(pkcs11.CKA_CLASS, class), pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_ECDSA), pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID), } if err := ctx.FindObjectsInit(session, privateKeyTemplate); err != nil { logrus.Debugf("Failed to init find objects: %s", err.Error()) return nil, err } obj, _, err := ctx.FindObjects(session, 1) if err != nil { logrus.Debugf("Failed to find objects: %v", err) return nil, err } if err = ctx.FindObjectsFinal(session); err != nil { logrus.Debugf("Failed to finalize find objects: %s", err.Error()) return nil, err } if len(obj) != 1 { return nil, errors.New("length of objects found not 1") } var sig []byte err = ctx.SignInit( session, []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_ECDSA, nil)}, obj[0]) if err != nil { return nil, err } // Get the SHA256 of the payload digest := sha256.Sum256(payload) if (yubikeyKeymode & KeymodeTouch) > 0 { touchToSignUI() defer touchDoneCallback() } // a call to Sign, whether or not Sign fails, will clear the SignInit sig, err = ctx.Sign(session, digest[:]) if err != nil { logrus.Debugf("Error while signing: %s", err) return nil, err } if sig == nil { return nil, errors.New("Failed to create signature") } return sig[:], nil }
[ "func", "sign", "(", "ctx", "IPKCS11Ctx", ",", "session", "pkcs11", ".", "SessionHandle", ",", "pkcs11KeyID", "[", "]", "byte", ",", "passRetriever", "notary", ".", "PassRetriever", ",", "payload", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "erro...
// sign returns a signature for a given signature request
[ "sign", "returns", "a", "signature", "for", "a", "given", "signature", "request" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L349-L406
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
ListKeys
func (s *YubiStore) ListKeys() map[string]trustmanager.KeyInfo { if len(s.keys) > 0 { return buildKeyMap(s.keys) } ctx, session, err := SetupHSMEnv(pkcs11Lib, s.libLoader) if err != nil { logrus.Debugf("No yubikey found, using alternative key storage: %s", err.Error()) return nil } defer cleanup(ctx, session) keys, err := yubiListKeys(ctx, session) if err != nil { logrus.Debugf("Failed to list key from the yubikey: %s", err.Error()) return nil } s.keys = keys return buildKeyMap(keys) }
go
func (s *YubiStore) ListKeys() map[string]trustmanager.KeyInfo { if len(s.keys) > 0 { return buildKeyMap(s.keys) } ctx, session, err := SetupHSMEnv(pkcs11Lib, s.libLoader) if err != nil { logrus.Debugf("No yubikey found, using alternative key storage: %s", err.Error()) return nil } defer cleanup(ctx, session) keys, err := yubiListKeys(ctx, session) if err != nil { logrus.Debugf("Failed to list key from the yubikey: %s", err.Error()) return nil } s.keys = keys return buildKeyMap(keys) }
[ "func", "(", "s", "*", "YubiStore", ")", "ListKeys", "(", ")", "map", "[", "string", "]", "trustmanager", ".", "KeyInfo", "{", "if", "len", "(", "s", ".", "keys", ")", ">", "0", "{", "return", "buildKeyMap", "(", "s", ".", "keys", ")", "\n", "}",...
// ListKeys returns a list of keys in the yubikey store
[ "ListKeys", "returns", "a", "list", "of", "keys", "in", "the", "yubikey", "store" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L661-L680
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
AddKey
func (s *YubiStore) AddKey(keyInfo trustmanager.KeyInfo, privKey data.PrivateKey) error { added, err := s.addKey(privKey.ID(), keyInfo.Role, privKey) if err != nil { return err } if added && s.backupStore != nil { err = s.backupStore.AddKey(keyInfo, privKey) if err != nil { defer s.RemoveKey(privKey.ID()) return ErrBackupFailed{err: err.Error()} } } return nil }
go
func (s *YubiStore) AddKey(keyInfo trustmanager.KeyInfo, privKey data.PrivateKey) error { added, err := s.addKey(privKey.ID(), keyInfo.Role, privKey) if err != nil { return err } if added && s.backupStore != nil { err = s.backupStore.AddKey(keyInfo, privKey) if err != nil { defer s.RemoveKey(privKey.ID()) return ErrBackupFailed{err: err.Error()} } } return nil }
[ "func", "(", "s", "*", "YubiStore", ")", "AddKey", "(", "keyInfo", "trustmanager", ".", "KeyInfo", ",", "privKey", "data", ".", "PrivateKey", ")", "error", "{", "added", ",", "err", ":=", "s", ".", "addKey", "(", "privKey", ".", "ID", "(", ")", ",", ...
// AddKey puts a key inside the Yubikey, as well as writing it to the backup store
[ "AddKey", "puts", "a", "key", "inside", "the", "Yubikey", "as", "well", "as", "writing", "it", "to", "the", "backup", "store" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L683-L696
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
addKey
func (s *YubiStore) addKey(keyID string, role data.RoleName, privKey data.PrivateKey) ( bool, error) { // We only allow adding root keys for now if role != data.CanonicalRootRole { return false, fmt.Errorf( "yubikey only supports storing root keys, got %s for key: %s", role, keyID) } ctx, session, err := SetupHSMEnv(pkcs11Lib, s.libLoader) if err != nil { logrus.Debugf("No yubikey found, using alternative key storage: %s", err.Error()) return false, err } defer cleanup(ctx, session) if k, ok := s.keys[keyID]; ok { if k.role == role { // already have the key and it's associated with the correct role return false, nil } } slot, err := getNextEmptySlot(ctx, session) if err != nil { logrus.Debugf("Failed to get an empty yubikey slot: %s", err.Error()) return false, err } logrus.Debugf("Attempting to store key using yubikey slot %v", slot) err = addECDSAKey( ctx, session, privKey, slot, s.passRetriever, role) if err == nil { s.keys[privKey.ID()] = yubiSlot{ role: role, slotID: slot, } return true, nil } logrus.Debugf("Failed to add key to yubikey: %v", err) return false, err }
go
func (s *YubiStore) addKey(keyID string, role data.RoleName, privKey data.PrivateKey) ( bool, error) { // We only allow adding root keys for now if role != data.CanonicalRootRole { return false, fmt.Errorf( "yubikey only supports storing root keys, got %s for key: %s", role, keyID) } ctx, session, err := SetupHSMEnv(pkcs11Lib, s.libLoader) if err != nil { logrus.Debugf("No yubikey found, using alternative key storage: %s", err.Error()) return false, err } defer cleanup(ctx, session) if k, ok := s.keys[keyID]; ok { if k.role == role { // already have the key and it's associated with the correct role return false, nil } } slot, err := getNextEmptySlot(ctx, session) if err != nil { logrus.Debugf("Failed to get an empty yubikey slot: %s", err.Error()) return false, err } logrus.Debugf("Attempting to store key using yubikey slot %v", slot) err = addECDSAKey( ctx, session, privKey, slot, s.passRetriever, role) if err == nil { s.keys[privKey.ID()] = yubiSlot{ role: role, slotID: slot, } return true, nil } logrus.Debugf("Failed to add key to yubikey: %v", err) return false, err }
[ "func", "(", "s", "*", "YubiStore", ")", "addKey", "(", "keyID", "string", ",", "role", "data", ".", "RoleName", ",", "privKey", "data", ".", "PrivateKey", ")", "(", "bool", ",", "error", ")", "{", "if", "role", "!=", "data", ".", "CanonicalRootRole", ...
// Only add if we haven't seen the key already. Return whether the key was // added.
[ "Only", "add", "if", "we", "haven", "t", "seen", "the", "key", "already", ".", "Return", "whether", "the", "key", "was", "added", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L700-L742
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
GetKeyInfo
func (s *YubiStore) GetKeyInfo(keyID string) (trustmanager.KeyInfo, error) { return trustmanager.KeyInfo{}, fmt.Errorf("Not yet implemented") }
go
func (s *YubiStore) GetKeyInfo(keyID string) (trustmanager.KeyInfo, error) { return trustmanager.KeyInfo{}, fmt.Errorf("Not yet implemented") }
[ "func", "(", "s", "*", "YubiStore", ")", "GetKeyInfo", "(", "keyID", "string", ")", "(", "trustmanager", ".", "KeyInfo", ",", "error", ")", "{", "return", "trustmanager", ".", "KeyInfo", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"Not yet implemented\"", ...
// GetKeyInfo is not yet implemented
[ "GetKeyInfo", "is", "not", "yet", "implemented" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L804-L806
train
theupdateframework/notary
trustmanager/yubikey/yubikeystore.go
SetupHSMEnv
func SetupHSMEnv(libraryPath string, libLoader pkcs11LibLoader) ( IPKCS11Ctx, pkcs11.SessionHandle, error) { if libraryPath == "" { return nil, 0, errHSMNotPresent{err: "no library found"} } p := libLoader(libraryPath) if p == nil { return nil, 0, fmt.Errorf("failed to load library %s", libraryPath) } if err := p.Initialize(); err != nil { defer finalizeAndDestroy(p) return nil, 0, fmt.Errorf("found library %s, but initialize error %s", libraryPath, err.Error()) } slots, err := p.GetSlotList(true) if err != nil { defer finalizeAndDestroy(p) return nil, 0, fmt.Errorf( "loaded library %s, but failed to list HSM slots %s", libraryPath, err) } // Check to see if we got any slots from the HSM. if len(slots) < 1 { defer finalizeAndDestroy(p) return nil, 0, fmt.Errorf( "loaded library %s, but no HSM slots found", libraryPath) } // CKF_SERIAL_SESSION: TRUE if cryptographic functions are performed in serial with the application; FALSE if the functions may be performed in parallel with the application. // CKF_RW_SESSION: TRUE if the session is read/write; FALSE if the session is read-only session, err := p.OpenSession(slots[0], pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION) if err != nil { defer cleanup(p, session) return nil, 0, fmt.Errorf( "loaded library %s, but failed to start session with HSM %s", libraryPath, err) } logrus.Debugf("Initialized PKCS11 library %s and started HSM session", libraryPath) return p, session, nil }
go
func SetupHSMEnv(libraryPath string, libLoader pkcs11LibLoader) ( IPKCS11Ctx, pkcs11.SessionHandle, error) { if libraryPath == "" { return nil, 0, errHSMNotPresent{err: "no library found"} } p := libLoader(libraryPath) if p == nil { return nil, 0, fmt.Errorf("failed to load library %s", libraryPath) } if err := p.Initialize(); err != nil { defer finalizeAndDestroy(p) return nil, 0, fmt.Errorf("found library %s, but initialize error %s", libraryPath, err.Error()) } slots, err := p.GetSlotList(true) if err != nil { defer finalizeAndDestroy(p) return nil, 0, fmt.Errorf( "loaded library %s, but failed to list HSM slots %s", libraryPath, err) } // Check to see if we got any slots from the HSM. if len(slots) < 1 { defer finalizeAndDestroy(p) return nil, 0, fmt.Errorf( "loaded library %s, but no HSM slots found", libraryPath) } // CKF_SERIAL_SESSION: TRUE if cryptographic functions are performed in serial with the application; FALSE if the functions may be performed in parallel with the application. // CKF_RW_SESSION: TRUE if the session is read/write; FALSE if the session is read-only session, err := p.OpenSession(slots[0], pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION) if err != nil { defer cleanup(p, session) return nil, 0, fmt.Errorf( "loaded library %s, but failed to start session with HSM %s", libraryPath, err) } logrus.Debugf("Initialized PKCS11 library %s and started HSM session", libraryPath) return p, session, nil }
[ "func", "SetupHSMEnv", "(", "libraryPath", "string", ",", "libLoader", "pkcs11LibLoader", ")", "(", "IPKCS11Ctx", ",", "pkcs11", ".", "SessionHandle", ",", "error", ")", "{", "if", "libraryPath", "==", "\"\"", "{", "return", "nil", ",", "0", ",", "errHSMNotP...
// SetupHSMEnv is a method that depends on the existences
[ "SetupHSMEnv", "is", "a", "method", "that", "depends", "on", "the", "existences" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/yubikey/yubikeystore.go#L825-L867
train