repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
theupdateframework/notary
signer/keydbstore/cachedcryptoservice.go
NewCachedKeyService
func NewCachedKeyService(baseKeyService signed.CryptoService) signed.CryptoService { return &cachedKeyService{ CryptoService: baseKeyService, lock: &sync.RWMutex{}, cachedKeys: make(map[string]*cachedKey), } }
go
func NewCachedKeyService(baseKeyService signed.CryptoService) signed.CryptoService { return &cachedKeyService{ CryptoService: baseKeyService, lock: &sync.RWMutex{}, cachedKeys: make(map[string]*cachedKey), } }
[ "func", "NewCachedKeyService", "(", "baseKeyService", "signed", ".", "CryptoService", ")", "signed", ".", "CryptoService", "{", "return", "&", "cachedKeyService", "{", "CryptoService", ":", "baseKeyService", ",", "lock", ":", "&", "sync", ".", "RWMutex", "{", "}", ",", "cachedKeys", ":", "make", "(", "map", "[", "string", "]", "*", "cachedKey", ")", ",", "}", "\n", "}" ]
// NewCachedKeyService returns a new signed.CryptoService that includes caching
[ "NewCachedKeyService", "returns", "a", "new", "signed", ".", "CryptoService", "that", "includes", "caching" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/cachedcryptoservice.go#L22-L28
train
theupdateframework/notary
cmd/notary/delegations.go
delegationsList
func (d *delegationCommander) delegationsList(cmd *cobra.Command, args []string) error { if len(args) != 1 { cmd.Usage() return fmt.Errorf( "Please provide a Global Unique Name as an argument to list") } config, err := d.configGetter() if err != nil { return err } gun := data.GUN(args[0]) rt, err := getTransport(config, gun, readOnly) if err != nil { return err } trustPin, err := getTrustPinning(config) if err != nil { return err } // initialize repo with transport to get latest state of the world before listing delegations nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), rt, d.retriever, trustPin) if err != nil { return err } delegationRoles, err := nRepo.GetDelegationRoles() if err != nil { return fmt.Errorf("Error retrieving delegation roles for repository %s: %v", gun, err) } cmd.Println("") prettyPrintRoles(delegationRoles, cmd.OutOrStdout(), "delegations") cmd.Println("") return nil }
go
func (d *delegationCommander) delegationsList(cmd *cobra.Command, args []string) error { if len(args) != 1 { cmd.Usage() return fmt.Errorf( "Please provide a Global Unique Name as an argument to list") } config, err := d.configGetter() if err != nil { return err } gun := data.GUN(args[0]) rt, err := getTransport(config, gun, readOnly) if err != nil { return err } trustPin, err := getTrustPinning(config) if err != nil { return err } // initialize repo with transport to get latest state of the world before listing delegations nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), rt, d.retriever, trustPin) if err != nil { return err } delegationRoles, err := nRepo.GetDelegationRoles() if err != nil { return fmt.Errorf("Error retrieving delegation roles for repository %s: %v", gun, err) } cmd.Println("") prettyPrintRoles(delegationRoles, cmd.OutOrStdout(), "delegations") cmd.Println("") return nil }
[ "func", "(", "d", "*", "delegationCommander", ")", "delegationsList", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "if", "len", "(", "args", ")", "!=", "1", "{", "cmd", ".", "Usage", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "config", ",", "err", ":=", "d", ".", "configGetter", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "gun", ":=", "data", ".", "GUN", "(", "args", "[", "0", "]", ")", "\n\n", "rt", ",", "err", ":=", "getTransport", "(", "config", ",", "gun", ",", "readOnly", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "trustPin", ",", "err", ":=", "getTrustPinning", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// initialize repo with transport to get latest state of the world before listing delegations", "nRepo", ",", "err", ":=", "notaryclient", ".", "NewFileCachedRepository", "(", "config", ".", "GetString", "(", "\"", "\"", ")", ",", "gun", ",", "getRemoteTrustServer", "(", "config", ")", ",", "rt", ",", "d", ".", "retriever", ",", "trustPin", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "delegationRoles", ",", "err", ":=", "nRepo", ".", "GetDelegationRoles", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "gun", ",", "err", ")", "\n", "}", "\n\n", "cmd", ".", "Println", "(", "\"", "\"", ")", "\n", "prettyPrintRoles", "(", "delegationRoles", ",", "cmd", ".", "OutOrStdout", "(", ")", ",", "\"", "\"", ")", "\n", "cmd", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// delegationsList lists all the delegations for a particular GUN
[ "delegationsList", "lists", "all", "the", "delegations", "for", "a", "particular", "GUN" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/delegations.go#L131-L171
train
theupdateframework/notary
cmd/notary/delegations.go
delegationRemove
func (d *delegationCommander) delegationRemove(cmd *cobra.Command, args []string) error { config, gun, role, keyIDs, err := delegationAddInput(d, cmd, args) if err != nil { return err } trustPin, err := getTrustPinning(config) if err != nil { return err } // no online operations are performed by add so the transport argument // should be nil nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, d.retriever, trustPin) if err != nil { return err } if d.removeAll { cmd.Println("\nAre you sure you want to remove all data for this delegation? (yes/no)") // Ask for confirmation before force removing delegation if !d.forceYes { confirmed := askConfirm(os.Stdin) if !confirmed { fatalf("Aborting action.") } } else { cmd.Println("Confirmed `yes` from flag") } // Delete the entire delegation err = nRepo.RemoveDelegationRole(role) if err != nil { return fmt.Errorf("failed to remove delegation: %v", err) } } else { if d.allPaths { err = nRepo.ClearDelegationPaths(role) if err != nil { return fmt.Errorf("failed to remove delegation: %v", err) } } // Remove any keys or paths that we passed in err = nRepo.RemoveDelegationKeysAndPaths(role, keyIDs, d.paths) if err != nil { return fmt.Errorf("failed to remove delegation: %v", err) } } delegationRemoveOutput(cmd, d, gun, role, keyIDs) return maybeAutoPublish(cmd, d.autoPublish, gun, config, d.retriever) }
go
func (d *delegationCommander) delegationRemove(cmd *cobra.Command, args []string) error { config, gun, role, keyIDs, err := delegationAddInput(d, cmd, args) if err != nil { return err } trustPin, err := getTrustPinning(config) if err != nil { return err } // no online operations are performed by add so the transport argument // should be nil nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, d.retriever, trustPin) if err != nil { return err } if d.removeAll { cmd.Println("\nAre you sure you want to remove all data for this delegation? (yes/no)") // Ask for confirmation before force removing delegation if !d.forceYes { confirmed := askConfirm(os.Stdin) if !confirmed { fatalf("Aborting action.") } } else { cmd.Println("Confirmed `yes` from flag") } // Delete the entire delegation err = nRepo.RemoveDelegationRole(role) if err != nil { return fmt.Errorf("failed to remove delegation: %v", err) } } else { if d.allPaths { err = nRepo.ClearDelegationPaths(role) if err != nil { return fmt.Errorf("failed to remove delegation: %v", err) } } // Remove any keys or paths that we passed in err = nRepo.RemoveDelegationKeysAndPaths(role, keyIDs, d.paths) if err != nil { return fmt.Errorf("failed to remove delegation: %v", err) } } delegationRemoveOutput(cmd, d, gun, role, keyIDs) return maybeAutoPublish(cmd, d.autoPublish, gun, config, d.retriever) }
[ "func", "(", "d", "*", "delegationCommander", ")", "delegationRemove", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "config", ",", "gun", ",", "role", ",", "keyIDs", ",", "err", ":=", "delegationAddInput", "(", "d", ",", "cmd", ",", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "trustPin", ",", "err", ":=", "getTrustPinning", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// no online operations are performed by add so the transport argument", "// should be nil", "nRepo", ",", "err", ":=", "notaryclient", ".", "NewFileCachedRepository", "(", "config", ".", "GetString", "(", "\"", "\"", ")", ",", "gun", ",", "getRemoteTrustServer", "(", "config", ")", ",", "nil", ",", "d", ".", "retriever", ",", "trustPin", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "d", ".", "removeAll", "{", "cmd", ".", "Println", "(", "\"", "\\n", "\"", ")", "\n", "// Ask for confirmation before force removing delegation", "if", "!", "d", ".", "forceYes", "{", "confirmed", ":=", "askConfirm", "(", "os", ".", "Stdin", ")", "\n", "if", "!", "confirmed", "{", "fatalf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "cmd", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "// Delete the entire delegation", "err", "=", "nRepo", ".", "RemoveDelegationRole", "(", "role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "if", "d", ".", "allPaths", "{", "err", "=", "nRepo", ".", "ClearDelegationPaths", "(", "role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "// Remove any keys or paths that we passed in", "err", "=", "nRepo", ".", "RemoveDelegationKeysAndPaths", "(", "role", ",", "keyIDs", ",", "d", ".", "paths", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "delegationRemoveOutput", "(", "cmd", ",", "d", ",", "gun", ",", "role", ",", "keyIDs", ")", "\n\n", "return", "maybeAutoPublish", "(", "cmd", ",", "d", ".", "autoPublish", ",", "gun", ",", "config", ",", "d", ".", "retriever", ")", "\n", "}" ]
// delegationRemove removes a public key from a specific role in a GUN
[ "delegationRemove", "removes", "a", "public", "key", "from", "a", "specific", "role", "in", "a", "GUN" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/delegations.go#L174-L226
train
theupdateframework/notary
cmd/notary/delegations.go
delegationAdd
func (d *delegationCommander) delegationAdd(cmd *cobra.Command, args []string) error { // We must have at least the gun and role name, and at least one key or path (or the --all-paths flag) to add if len(args) < 2 || len(args) < 3 && d.paths == nil && !d.allPaths { cmd.Usage() return fmt.Errorf("must specify the Global Unique Name and the role of the delegation along with the public key certificate paths and/or a list of paths to add") } config, err := d.configGetter() if err != nil { return err } gun := data.GUN(args[0]) role := data.RoleName(args[1]) pubKeys, err := ingestPublicKeys(args) if err != nil { return err } checkAllPaths(d) trustPin, err := getTrustPinning(config) if err != nil { return err } // no online operations are performed by add so the transport argument // should be nil nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, d.retriever, trustPin) if err != nil { return err } // Add the delegation to the repository err = nRepo.AddDelegation(role, pubKeys, d.paths) if err != nil { return fmt.Errorf("failed to create delegation: %v", err) } // Make keyID slice for better CLI print pubKeyIDs := []string{} for _, pubKey := range pubKeys { pubKeyID, err := utils.CanonicalKeyID(pubKey) if err != nil { return err } pubKeyIDs = append(pubKeyIDs, pubKeyID) } cmd.Println("") addingItems := "" if len(pubKeyIDs) > 0 { addingItems = addingItems + fmt.Sprintf("with keys %s, ", pubKeyIDs) } if d.paths != nil || d.allPaths { addingItems = addingItems + fmt.Sprintf( "with paths [%s], ", strings.Join(prettyPaths(d.paths), "\n"), ) } cmd.Printf( "Addition of delegation role %s %sto repository \"%s\" staged for next publish.\n", role, addingItems, gun) cmd.Println("") return maybeAutoPublish(cmd, d.autoPublish, gun, config, d.retriever) }
go
func (d *delegationCommander) delegationAdd(cmd *cobra.Command, args []string) error { // We must have at least the gun and role name, and at least one key or path (or the --all-paths flag) to add if len(args) < 2 || len(args) < 3 && d.paths == nil && !d.allPaths { cmd.Usage() return fmt.Errorf("must specify the Global Unique Name and the role of the delegation along with the public key certificate paths and/or a list of paths to add") } config, err := d.configGetter() if err != nil { return err } gun := data.GUN(args[0]) role := data.RoleName(args[1]) pubKeys, err := ingestPublicKeys(args) if err != nil { return err } checkAllPaths(d) trustPin, err := getTrustPinning(config) if err != nil { return err } // no online operations are performed by add so the transport argument // should be nil nRepo, err := notaryclient.NewFileCachedRepository( config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, d.retriever, trustPin) if err != nil { return err } // Add the delegation to the repository err = nRepo.AddDelegation(role, pubKeys, d.paths) if err != nil { return fmt.Errorf("failed to create delegation: %v", err) } // Make keyID slice for better CLI print pubKeyIDs := []string{} for _, pubKey := range pubKeys { pubKeyID, err := utils.CanonicalKeyID(pubKey) if err != nil { return err } pubKeyIDs = append(pubKeyIDs, pubKeyID) } cmd.Println("") addingItems := "" if len(pubKeyIDs) > 0 { addingItems = addingItems + fmt.Sprintf("with keys %s, ", pubKeyIDs) } if d.paths != nil || d.allPaths { addingItems = addingItems + fmt.Sprintf( "with paths [%s], ", strings.Join(prettyPaths(d.paths), "\n"), ) } cmd.Printf( "Addition of delegation role %s %sto repository \"%s\" staged for next publish.\n", role, addingItems, gun) cmd.Println("") return maybeAutoPublish(cmd, d.autoPublish, gun, config, d.retriever) }
[ "func", "(", "d", "*", "delegationCommander", ")", "delegationAdd", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "// We must have at least the gun and role name, and at least one key or path (or the --all-paths flag) to add", "if", "len", "(", "args", ")", "<", "2", "||", "len", "(", "args", ")", "<", "3", "&&", "d", ".", "paths", "==", "nil", "&&", "!", "d", ".", "allPaths", "{", "cmd", ".", "Usage", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "config", ",", "err", ":=", "d", ".", "configGetter", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "gun", ":=", "data", ".", "GUN", "(", "args", "[", "0", "]", ")", "\n", "role", ":=", "data", ".", "RoleName", "(", "args", "[", "1", "]", ")", "\n\n", "pubKeys", ",", "err", ":=", "ingestPublicKeys", "(", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "checkAllPaths", "(", "d", ")", "\n\n", "trustPin", ",", "err", ":=", "getTrustPinning", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// no online operations are performed by add so the transport argument", "// should be nil", "nRepo", ",", "err", ":=", "notaryclient", ".", "NewFileCachedRepository", "(", "config", ".", "GetString", "(", "\"", "\"", ")", ",", "gun", ",", "getRemoteTrustServer", "(", "config", ")", ",", "nil", ",", "d", ".", "retriever", ",", "trustPin", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Add the delegation to the repository", "err", "=", "nRepo", ".", "AddDelegation", "(", "role", ",", "pubKeys", ",", "d", ".", "paths", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Make keyID slice for better CLI print", "pubKeyIDs", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "pubKey", ":=", "range", "pubKeys", "{", "pubKeyID", ",", "err", ":=", "utils", ".", "CanonicalKeyID", "(", "pubKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "pubKeyIDs", "=", "append", "(", "pubKeyIDs", ",", "pubKeyID", ")", "\n", "}", "\n\n", "cmd", ".", "Println", "(", "\"", "\"", ")", "\n", "addingItems", ":=", "\"", "\"", "\n", "if", "len", "(", "pubKeyIDs", ")", ">", "0", "{", "addingItems", "=", "addingItems", "+", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pubKeyIDs", ")", "\n", "}", "\n", "if", "d", ".", "paths", "!=", "nil", "||", "d", ".", "allPaths", "{", "addingItems", "=", "addingItems", "+", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "prettyPaths", "(", "d", ".", "paths", ")", ",", "\"", "\\n", "\"", ")", ",", ")", "\n", "}", "\n", "cmd", ".", "Printf", "(", "\"", "\\\"", "\\\"", "\\n", "\"", ",", "role", ",", "addingItems", ",", "gun", ")", "\n", "cmd", ".", "Println", "(", "\"", "\"", ")", "\n\n", "return", "maybeAutoPublish", "(", "cmd", ",", "d", ".", "autoPublish", ",", "gun", ",", "config", ",", "d", ".", "retriever", ")", "\n", "}" ]
// delegationAdd creates a new delegation by adding a public key from a certificate to a specific role in a GUN
[ "delegationAdd", "creates", "a", "new", "delegation", "by", "adding", "a", "public", "key", "from", "a", "certificate", "to", "a", "specific", "role", "in", "a", "GUN" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/delegations.go#L288-L356
train
theupdateframework/notary
tuf/signed/ed25519.go
AddKey
func (e *Ed25519) AddKey(role data.RoleName, gun data.GUN, k data.PrivateKey) error { e.addKey(role, k) return nil }
go
func (e *Ed25519) AddKey(role data.RoleName, gun data.GUN, k data.PrivateKey) error { e.addKey(role, k) return nil }
[ "func", "(", "e", "*", "Ed25519", ")", "AddKey", "(", "role", "data", ".", "RoleName", ",", "gun", "data", ".", "GUN", ",", "k", "data", ".", "PrivateKey", ")", "error", "{", "e", ".", "addKey", "(", "role", ",", "k", ")", "\n", "return", "nil", "\n", "}" ]
// AddKey allows you to add a private key
[ "AddKey", "allows", "you", "to", "add", "a", "private", "key" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L31-L34
train
theupdateframework/notary
tuf/signed/ed25519.go
addKey
func (e *Ed25519) addKey(role data.RoleName, k data.PrivateKey) { e.keys[k.ID()] = edCryptoKey{ role: role, privKey: k, } }
go
func (e *Ed25519) addKey(role data.RoleName, k data.PrivateKey) { e.keys[k.ID()] = edCryptoKey{ role: role, privKey: k, } }
[ "func", "(", "e", "*", "Ed25519", ")", "addKey", "(", "role", "data", ".", "RoleName", ",", "k", "data", ".", "PrivateKey", ")", "{", "e", ".", "keys", "[", "k", ".", "ID", "(", ")", "]", "=", "edCryptoKey", "{", "role", ":", "role", ",", "privKey", ":", "k", ",", "}", "\n", "}" ]
// addKey allows you to add a private key
[ "addKey", "allows", "you", "to", "add", "a", "private", "key" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L37-L42
train
theupdateframework/notary
tuf/signed/ed25519.go
RemoveKey
func (e *Ed25519) RemoveKey(keyID string) error { delete(e.keys, keyID) return nil }
go
func (e *Ed25519) RemoveKey(keyID string) error { delete(e.keys, keyID) return nil }
[ "func", "(", "e", "*", "Ed25519", ")", "RemoveKey", "(", "keyID", "string", ")", "error", "{", "delete", "(", "e", ".", "keys", ",", "keyID", ")", "\n", "return", "nil", "\n", "}" ]
// RemoveKey deletes a key from the signer
[ "RemoveKey", "deletes", "a", "key", "from", "the", "signer" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L45-L48
train
theupdateframework/notary
tuf/signed/ed25519.go
ListKeys
func (e *Ed25519) ListKeys(role data.RoleName) []string { keyIDs := make([]string, 0, len(e.keys)) for id, edCryptoKey := range e.keys { if edCryptoKey.role == role { keyIDs = append(keyIDs, id) } } return keyIDs }
go
func (e *Ed25519) ListKeys(role data.RoleName) []string { keyIDs := make([]string, 0, len(e.keys)) for id, edCryptoKey := range e.keys { if edCryptoKey.role == role { keyIDs = append(keyIDs, id) } } return keyIDs }
[ "func", "(", "e", "*", "Ed25519", ")", "ListKeys", "(", "role", "data", ".", "RoleName", ")", "[", "]", "string", "{", "keyIDs", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "e", ".", "keys", ")", ")", "\n", "for", "id", ",", "edCryptoKey", ":=", "range", "e", ".", "keys", "{", "if", "edCryptoKey", ".", "role", "==", "role", "{", "keyIDs", "=", "append", "(", "keyIDs", ",", "id", ")", "\n", "}", "\n", "}", "\n", "return", "keyIDs", "\n", "}" ]
// ListKeys returns the list of keys IDs for the role
[ "ListKeys", "returns", "the", "list", "of", "keys", "IDs", "for", "the", "role" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L51-L59
train
theupdateframework/notary
tuf/signed/ed25519.go
ListAllKeys
func (e *Ed25519) ListAllKeys() map[string]data.RoleName { keys := make(map[string]data.RoleName) for id, edKey := range e.keys { keys[id] = edKey.role } return keys }
go
func (e *Ed25519) ListAllKeys() map[string]data.RoleName { keys := make(map[string]data.RoleName) for id, edKey := range e.keys { keys[id] = edKey.role } return keys }
[ "func", "(", "e", "*", "Ed25519", ")", "ListAllKeys", "(", ")", "map", "[", "string", "]", "data", ".", "RoleName", "{", "keys", ":=", "make", "(", "map", "[", "string", "]", "data", ".", "RoleName", ")", "\n", "for", "id", ",", "edKey", ":=", "range", "e", ".", "keys", "{", "keys", "[", "id", "]", "=", "edKey", ".", "role", "\n", "}", "\n", "return", "keys", "\n", "}" ]
// ListAllKeys returns the map of keys IDs to role
[ "ListAllKeys", "returns", "the", "map", "of", "keys", "IDs", "to", "role" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L62-L68
train
theupdateframework/notary
tuf/signed/ed25519.go
Create
func (e *Ed25519) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) { if algorithm != data.ED25519Key { return nil, errors.New("only ED25519 supported by this cryptoservice") } private, err := utils.GenerateED25519Key(rand.Reader) if err != nil { return nil, err } e.addKey(role, private) return data.PublicKeyFromPrivate(private), nil }
go
func (e *Ed25519) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) { if algorithm != data.ED25519Key { return nil, errors.New("only ED25519 supported by this cryptoservice") } private, err := utils.GenerateED25519Key(rand.Reader) if err != nil { return nil, err } e.addKey(role, private) return data.PublicKeyFromPrivate(private), nil }
[ "func", "(", "e", "*", "Ed25519", ")", "Create", "(", "role", "data", ".", "RoleName", ",", "gun", "data", ".", "GUN", ",", "algorithm", "string", ")", "(", "data", ".", "PublicKey", ",", "error", ")", "{", "if", "algorithm", "!=", "data", ".", "ED25519Key", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "private", ",", "err", ":=", "utils", ".", "GenerateED25519Key", "(", "rand", ".", "Reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "e", ".", "addKey", "(", "role", ",", "private", ")", "\n", "return", "data", ".", "PublicKeyFromPrivate", "(", "private", ")", ",", "nil", "\n", "}" ]
// Create generates a new key and returns the public part
[ "Create", "generates", "a", "new", "key", "and", "returns", "the", "public", "part" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L71-L83
train
theupdateframework/notary
tuf/signed/ed25519.go
PublicKeys
func (e *Ed25519) PublicKeys(keyIDs ...string) (map[string]data.PublicKey, error) { k := make(map[string]data.PublicKey) for _, keyID := range keyIDs { if edKey, ok := e.keys[keyID]; ok { k[keyID] = data.PublicKeyFromPrivate(edKey.privKey) } } return k, nil }
go
func (e *Ed25519) PublicKeys(keyIDs ...string) (map[string]data.PublicKey, error) { k := make(map[string]data.PublicKey) for _, keyID := range keyIDs { if edKey, ok := e.keys[keyID]; ok { k[keyID] = data.PublicKeyFromPrivate(edKey.privKey) } } return k, nil }
[ "func", "(", "e", "*", "Ed25519", ")", "PublicKeys", "(", "keyIDs", "...", "string", ")", "(", "map", "[", "string", "]", "data", ".", "PublicKey", ",", "error", ")", "{", "k", ":=", "make", "(", "map", "[", "string", "]", "data", ".", "PublicKey", ")", "\n", "for", "_", ",", "keyID", ":=", "range", "keyIDs", "{", "if", "edKey", ",", "ok", ":=", "e", ".", "keys", "[", "keyID", "]", ";", "ok", "{", "k", "[", "keyID", "]", "=", "data", ".", "PublicKeyFromPrivate", "(", "edKey", ".", "privKey", ")", "\n", "}", "\n", "}", "\n", "return", "k", ",", "nil", "\n", "}" ]
// PublicKeys returns a map of public keys for the ids provided, when those IDs are found // in the store.
[ "PublicKeys", "returns", "a", "map", "of", "public", "keys", "for", "the", "ids", "provided", "when", "those", "IDs", "are", "found", "in", "the", "store", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L87-L95
train
theupdateframework/notary
tuf/signed/ed25519.go
GetKey
func (e *Ed25519) GetKey(keyID string) data.PublicKey { if privKey, _, err := e.GetPrivateKey(keyID); err == nil { return data.PublicKeyFromPrivate(privKey) } return nil }
go
func (e *Ed25519) GetKey(keyID string) data.PublicKey { if privKey, _, err := e.GetPrivateKey(keyID); err == nil { return data.PublicKeyFromPrivate(privKey) } return nil }
[ "func", "(", "e", "*", "Ed25519", ")", "GetKey", "(", "keyID", "string", ")", "data", ".", "PublicKey", "{", "if", "privKey", ",", "_", ",", "err", ":=", "e", ".", "GetPrivateKey", "(", "keyID", ")", ";", "err", "==", "nil", "{", "return", "data", ".", "PublicKeyFromPrivate", "(", "privKey", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetKey returns a single public key based on the ID
[ "GetKey", "returns", "a", "single", "public", "key", "based", "on", "the", "ID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L98-L103
train
theupdateframework/notary
tuf/signed/ed25519.go
GetPrivateKey
func (e *Ed25519) GetPrivateKey(keyID string) (data.PrivateKey, data.RoleName, error) { if k, ok := e.keys[keyID]; ok { return k.privKey, k.role, nil } return nil, "", trustmanager.ErrKeyNotFound{KeyID: keyID} }
go
func (e *Ed25519) GetPrivateKey(keyID string) (data.PrivateKey, data.RoleName, error) { if k, ok := e.keys[keyID]; ok { return k.privKey, k.role, nil } return nil, "", trustmanager.ErrKeyNotFound{KeyID: keyID} }
[ "func", "(", "e", "*", "Ed25519", ")", "GetPrivateKey", "(", "keyID", "string", ")", "(", "data", ".", "PrivateKey", ",", "data", ".", "RoleName", ",", "error", ")", "{", "if", "k", ",", "ok", ":=", "e", ".", "keys", "[", "keyID", "]", ";", "ok", "{", "return", "k", ".", "privKey", ",", "k", ".", "role", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "\"", "\"", ",", "trustmanager", ".", "ErrKeyNotFound", "{", "KeyID", ":", "keyID", "}", "\n", "}" ]
// GetPrivateKey returns a single private key and role if present, based on the ID
[ "GetPrivateKey", "returns", "a", "single", "private", "key", "and", "role", "if", "present", "based", "on", "the", "ID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L106-L111
train
theupdateframework/notary
tuf/utils/stack.go
Push
func (s *Stack) Push(item interface{}) { s.l.Lock() defer s.l.Unlock() s.s = append(s.s, item) }
go
func (s *Stack) Push(item interface{}) { s.l.Lock() defer s.l.Unlock() s.s = append(s.s, item) }
[ "func", "(", "s", "*", "Stack", ")", "Push", "(", "item", "interface", "{", "}", ")", "{", "s", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "l", ".", "Unlock", "(", ")", "\n", "s", ".", "s", "=", "append", "(", "s", ".", "s", ",", "item", ")", "\n", "}" ]
// Push adds an item to the top of the stack.
[ "Push", "adds", "an", "item", "to", "the", "top", "of", "the", "stack", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/stack.go#L41-L45
train
theupdateframework/notary
tuf/utils/stack.go
Pop
func (s *Stack) Pop() (interface{}, error) { s.l.Lock() defer s.l.Unlock() l := len(s.s) if l > 0 { item := s.s[l-1] s.s = s.s[:l-1] return item, nil } return nil, ErrEmptyStack{action: "Pop"} }
go
func (s *Stack) Pop() (interface{}, error) { s.l.Lock() defer s.l.Unlock() l := len(s.s) if l > 0 { item := s.s[l-1] s.s = s.s[:l-1] return item, nil } return nil, ErrEmptyStack{action: "Pop"} }
[ "func", "(", "s", "*", "Stack", ")", "Pop", "(", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "s", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "l", ".", "Unlock", "(", ")", "\n", "l", ":=", "len", "(", "s", ".", "s", ")", "\n", "if", "l", ">", "0", "{", "item", ":=", "s", ".", "s", "[", "l", "-", "1", "]", "\n", "s", ".", "s", "=", "s", ".", "s", "[", ":", "l", "-", "1", "]", "\n", "return", "item", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "ErrEmptyStack", "{", "action", ":", "\"", "\"", "}", "\n", "}" ]
// Pop removes and returns the top item on the stack, or returns // ErrEmptyStack if the stack has no content
[ "Pop", "removes", "and", "returns", "the", "top", "item", "on", "the", "stack", "or", "returns", "ErrEmptyStack", "if", "the", "stack", "has", "no", "content" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/stack.go#L49-L59
train
theupdateframework/notary
tuf/utils/stack.go
PopString
func (s *Stack) PopString() (string, error) { s.l.Lock() defer s.l.Unlock() l := len(s.s) if l > 0 { item := s.s[l-1] if item, ok := item.(string); ok { s.s = s.s[:l-1] return item, nil } return "", ErrBadTypeCast{} } return "", ErrEmptyStack{action: "PopString"} }
go
func (s *Stack) PopString() (string, error) { s.l.Lock() defer s.l.Unlock() l := len(s.s) if l > 0 { item := s.s[l-1] if item, ok := item.(string); ok { s.s = s.s[:l-1] return item, nil } return "", ErrBadTypeCast{} } return "", ErrEmptyStack{action: "PopString"} }
[ "func", "(", "s", "*", "Stack", ")", "PopString", "(", ")", "(", "string", ",", "error", ")", "{", "s", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "l", ".", "Unlock", "(", ")", "\n", "l", ":=", "len", "(", "s", ".", "s", ")", "\n", "if", "l", ">", "0", "{", "item", ":=", "s", ".", "s", "[", "l", "-", "1", "]", "\n", "if", "item", ",", "ok", ":=", "item", ".", "(", "string", ")", ";", "ok", "{", "s", ".", "s", "=", "s", ".", "s", "[", ":", "l", "-", "1", "]", "\n", "return", "item", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "ErrBadTypeCast", "{", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "ErrEmptyStack", "{", "action", ":", "\"", "\"", "}", "\n", "}" ]
// PopString attempts to cast the top item on the stack to the string type. // If this succeeds, it removes and returns the top item. If the item // is not of the string type, ErrBadTypeCast is returned. If the stack // is empty, ErrEmptyStack is returned
[ "PopString", "attempts", "to", "cast", "the", "top", "item", "on", "the", "stack", "to", "the", "string", "type", ".", "If", "this", "succeeds", "it", "removes", "and", "returns", "the", "top", "item", ".", "If", "the", "item", "is", "not", "of", "the", "string", "type", "ErrBadTypeCast", "is", "returned", ".", "If", "the", "stack", "is", "empty", "ErrEmptyStack", "is", "returned" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/stack.go#L65-L78
train
theupdateframework/notary
tuf/utils/stack.go
Empty
func (s *Stack) Empty() bool { s.l.Lock() defer s.l.Unlock() return len(s.s) == 0 }
go
func (s *Stack) Empty() bool { s.l.Lock() defer s.l.Unlock() return len(s.s) == 0 }
[ "func", "(", "s", "*", "Stack", ")", "Empty", "(", ")", "bool", "{", "s", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "l", ".", "Unlock", "(", ")", "\n", "return", "len", "(", "s", ".", "s", ")", "==", "0", "\n", "}" ]
// Empty returns true if the stack is empty
[ "Empty", "returns", "true", "if", "the", "stack", "is", "empty" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/stack.go#L81-L85
train
theupdateframework/notary
trustmanager/keys.go
ExportKeysByGUN
func ExportKeysByGUN(to io.Writer, s Exporter, gun string) error { keys := s.ListFiles() sort.Strings(keys) // ensure consistency. ListFiles has no order guarantee for _, loc := range keys { keyFile, err := s.Get(loc) if err != nil { logrus.Warn("Could not parse key file at ", loc) continue } block, _ := pem.Decode(keyFile) keyGun := block.Headers["gun"] if keyGun == gun { // must be full GUN match if err := ExportKeys(to, s, loc); err != nil { return err } } } return nil }
go
func ExportKeysByGUN(to io.Writer, s Exporter, gun string) error { keys := s.ListFiles() sort.Strings(keys) // ensure consistency. ListFiles has no order guarantee for _, loc := range keys { keyFile, err := s.Get(loc) if err != nil { logrus.Warn("Could not parse key file at ", loc) continue } block, _ := pem.Decode(keyFile) keyGun := block.Headers["gun"] if keyGun == gun { // must be full GUN match if err := ExportKeys(to, s, loc); err != nil { return err } } } return nil }
[ "func", "ExportKeysByGUN", "(", "to", "io", ".", "Writer", ",", "s", "Exporter", ",", "gun", "string", ")", "error", "{", "keys", ":=", "s", ".", "ListFiles", "(", ")", "\n", "sort", ".", "Strings", "(", "keys", ")", "// ensure consistency. ListFiles has no order guarantee", "\n", "for", "_", ",", "loc", ":=", "range", "keys", "{", "keyFile", ",", "err", ":=", "s", ".", "Get", "(", "loc", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warn", "(", "\"", "\"", ",", "loc", ")", "\n", "continue", "\n", "}", "\n", "block", ",", "_", ":=", "pem", ".", "Decode", "(", "keyFile", ")", "\n", "keyGun", ":=", "block", ".", "Headers", "[", "\"", "\"", "]", "\n", "if", "keyGun", "==", "gun", "{", "// must be full GUN match", "if", "err", ":=", "ExportKeys", "(", "to", ",", "s", ",", "loc", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ExportKeysByGUN exports all keys filtered to a GUN
[ "ExportKeysByGUN", "exports", "all", "keys", "filtered", "to", "a", "GUN" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keys.go#L31-L49
train
theupdateframework/notary
trustmanager/keys.go
ExportKeysByID
func ExportKeysByID(to io.Writer, s Exporter, ids []string) error { want := make(map[string]struct{}) for _, id := range ids { want[id] = struct{}{} } keys := s.ListFiles() for _, k := range keys { id := filepath.Base(k) if _, ok := want[id]; ok { if err := ExportKeys(to, s, k); err != nil { return err } } } return nil }
go
func ExportKeysByID(to io.Writer, s Exporter, ids []string) error { want := make(map[string]struct{}) for _, id := range ids { want[id] = struct{}{} } keys := s.ListFiles() for _, k := range keys { id := filepath.Base(k) if _, ok := want[id]; ok { if err := ExportKeys(to, s, k); err != nil { return err } } } return nil }
[ "func", "ExportKeysByID", "(", "to", "io", ".", "Writer", ",", "s", "Exporter", ",", "ids", "[", "]", "string", ")", "error", "{", "want", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "id", ":=", "range", "ids", "{", "want", "[", "id", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "keys", ":=", "s", ".", "ListFiles", "(", ")", "\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "id", ":=", "filepath", ".", "Base", "(", "k", ")", "\n", "if", "_", ",", "ok", ":=", "want", "[", "id", "]", ";", "ok", "{", "if", "err", ":=", "ExportKeys", "(", "to", ",", "s", ",", "k", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ExportKeysByID exports all keys matching the given ID
[ "ExportKeysByID", "exports", "all", "keys", "matching", "the", "given", "ID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keys.go#L52-L67
train
theupdateframework/notary
trustmanager/keys.go
ExportKeys
func ExportKeys(to io.Writer, s Exporter, from string) error { // get PEM block k, err := s.Get(from) if err != nil { return err } // parse PEM blocks if there are more than one for block, rest := pem.Decode(k); block != nil; block, rest = pem.Decode(rest) { // add from path in a header for later import block.Headers["path"] = from // write serialized PEM err = pem.Encode(to, block) if err != nil { return err } } return nil }
go
func ExportKeys(to io.Writer, s Exporter, from string) error { // get PEM block k, err := s.Get(from) if err != nil { return err } // parse PEM blocks if there are more than one for block, rest := pem.Decode(k); block != nil; block, rest = pem.Decode(rest) { // add from path in a header for later import block.Headers["path"] = from // write serialized PEM err = pem.Encode(to, block) if err != nil { return err } } return nil }
[ "func", "ExportKeys", "(", "to", "io", ".", "Writer", ",", "s", "Exporter", ",", "from", "string", ")", "error", "{", "// get PEM block", "k", ",", "err", ":=", "s", ".", "Get", "(", "from", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// parse PEM blocks if there are more than one", "for", "block", ",", "rest", ":=", "pem", ".", "Decode", "(", "k", ")", ";", "block", "!=", "nil", ";", "block", ",", "rest", "=", "pem", ".", "Decode", "(", "rest", ")", "{", "// add from path in a header for later import", "block", ".", "Headers", "[", "\"", "\"", "]", "=", "from", "\n", "// write serialized PEM", "err", "=", "pem", ".", "Encode", "(", "to", ",", "block", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ExportKeys copies a key from the store to the io.Writer
[ "ExportKeys", "copies", "a", "key", "from", "the", "store", "to", "the", "io", ".", "Writer" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keys.go#L70-L88
train
theupdateframework/notary
trustmanager/keys.go
ImportKeys
func ImportKeys(from io.Reader, to []Importer, fallbackRole string, fallbackGUN string, passRet notary.PassRetriever) error { // importLogic.md contains a small flowchart I made to clear up my understand while writing the cases in this function // it is very rough, but it may help while reading this piece of code data, err := ioutil.ReadAll(from) if err != nil { return err } var ( writeTo string toWrite []byte errBlocks []string ) for block, rest := pem.Decode(data); block != nil; block, rest = pem.Decode(rest) { handleLegacyPath(block) setFallbacks(block, fallbackGUN, fallbackRole) loc, err := checkValidity(block) if err != nil { // already logged in checkValidity errBlocks = append(errBlocks, err.Error()) continue } // the path header is not of any use once we've imported the key so strip it away delete(block.Headers, "path") // we are now all set for import but let's first encrypt the key blockBytes := pem.EncodeToMemory(block) // check if key is encrypted, note: if it is encrypted at this point, it will have had a path header if privKey, err := utils.ParsePEMPrivateKey(blockBytes, ""); err == nil { // Key is not encrypted- ask for a passphrase and encrypt this key var chosenPassphrase string for attempts := 0; ; attempts++ { var giveup bool chosenPassphrase, giveup, err = passRet(loc, block.Headers["role"], true, attempts) if err == nil { break } if giveup || attempts > 10 { return errors.New("maximum number of passphrase attempts exceeded") } } blockBytes, err = utils.ConvertPrivateKeyToPKCS8(privKey, tufdata.RoleName(block.Headers["role"]), tufdata.GUN(block.Headers["gun"]), chosenPassphrase) if err != nil { return errors.New("failed to encrypt key with given passphrase") } } if loc != writeTo { // next location is different from previous one. We've finished aggregating // data for the previous file. If we have data, write the previous file, // clear toWrite and set writeTo to the next path we're going to write if toWrite != nil { if err = importToStores(to, writeTo, toWrite); err != nil { return err } } // set up for aggregating next file's data toWrite = nil writeTo = loc } toWrite = append(toWrite, blockBytes...) } if toWrite != nil { // close out final iteration if there's data left return importToStores(to, writeTo, toWrite) } if len(errBlocks) > 0 { return fmt.Errorf("failed to import all keys: %s", strings.Join(errBlocks, ", ")) } return nil }
go
func ImportKeys(from io.Reader, to []Importer, fallbackRole string, fallbackGUN string, passRet notary.PassRetriever) error { // importLogic.md contains a small flowchart I made to clear up my understand while writing the cases in this function // it is very rough, but it may help while reading this piece of code data, err := ioutil.ReadAll(from) if err != nil { return err } var ( writeTo string toWrite []byte errBlocks []string ) for block, rest := pem.Decode(data); block != nil; block, rest = pem.Decode(rest) { handleLegacyPath(block) setFallbacks(block, fallbackGUN, fallbackRole) loc, err := checkValidity(block) if err != nil { // already logged in checkValidity errBlocks = append(errBlocks, err.Error()) continue } // the path header is not of any use once we've imported the key so strip it away delete(block.Headers, "path") // we are now all set for import but let's first encrypt the key blockBytes := pem.EncodeToMemory(block) // check if key is encrypted, note: if it is encrypted at this point, it will have had a path header if privKey, err := utils.ParsePEMPrivateKey(blockBytes, ""); err == nil { // Key is not encrypted- ask for a passphrase and encrypt this key var chosenPassphrase string for attempts := 0; ; attempts++ { var giveup bool chosenPassphrase, giveup, err = passRet(loc, block.Headers["role"], true, attempts) if err == nil { break } if giveup || attempts > 10 { return errors.New("maximum number of passphrase attempts exceeded") } } blockBytes, err = utils.ConvertPrivateKeyToPKCS8(privKey, tufdata.RoleName(block.Headers["role"]), tufdata.GUN(block.Headers["gun"]), chosenPassphrase) if err != nil { return errors.New("failed to encrypt key with given passphrase") } } if loc != writeTo { // next location is different from previous one. We've finished aggregating // data for the previous file. If we have data, write the previous file, // clear toWrite and set writeTo to the next path we're going to write if toWrite != nil { if err = importToStores(to, writeTo, toWrite); err != nil { return err } } // set up for aggregating next file's data toWrite = nil writeTo = loc } toWrite = append(toWrite, blockBytes...) } if toWrite != nil { // close out final iteration if there's data left return importToStores(to, writeTo, toWrite) } if len(errBlocks) > 0 { return fmt.Errorf("failed to import all keys: %s", strings.Join(errBlocks, ", ")) } return nil }
[ "func", "ImportKeys", "(", "from", "io", ".", "Reader", ",", "to", "[", "]", "Importer", ",", "fallbackRole", "string", ",", "fallbackGUN", "string", ",", "passRet", "notary", ".", "PassRetriever", ")", "error", "{", "// importLogic.md contains a small flowchart I made to clear up my understand while writing the cases in this function", "// it is very rough, but it may help while reading this piece of code", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "from", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "(", "writeTo", "string", "\n", "toWrite", "[", "]", "byte", "\n", "errBlocks", "[", "]", "string", "\n", ")", "\n", "for", "block", ",", "rest", ":=", "pem", ".", "Decode", "(", "data", ")", ";", "block", "!=", "nil", ";", "block", ",", "rest", "=", "pem", ".", "Decode", "(", "rest", ")", "{", "handleLegacyPath", "(", "block", ")", "\n", "setFallbacks", "(", "block", ",", "fallbackGUN", ",", "fallbackRole", ")", "\n\n", "loc", ",", "err", ":=", "checkValidity", "(", "block", ")", "\n", "if", "err", "!=", "nil", "{", "// already logged in checkValidity", "errBlocks", "=", "append", "(", "errBlocks", ",", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "// the path header is not of any use once we've imported the key so strip it away", "delete", "(", "block", ".", "Headers", ",", "\"", "\"", ")", "\n\n", "// we are now all set for import but let's first encrypt the key", "blockBytes", ":=", "pem", ".", "EncodeToMemory", "(", "block", ")", "\n", "// check if key is encrypted, note: if it is encrypted at this point, it will have had a path header", "if", "privKey", ",", "err", ":=", "utils", ".", "ParsePEMPrivateKey", "(", "blockBytes", ",", "\"", "\"", ")", ";", "err", "==", "nil", "{", "// Key is not encrypted- ask for a passphrase and encrypt this key", "var", "chosenPassphrase", "string", "\n", "for", "attempts", ":=", "0", ";", ";", "attempts", "++", "{", "var", "giveup", "bool", "\n", "chosenPassphrase", ",", "giveup", ",", "err", "=", "passRet", "(", "loc", ",", "block", ".", "Headers", "[", "\"", "\"", "]", ",", "true", ",", "attempts", ")", "\n", "if", "err", "==", "nil", "{", "break", "\n", "}", "\n", "if", "giveup", "||", "attempts", ">", "10", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "blockBytes", ",", "err", "=", "utils", ".", "ConvertPrivateKeyToPKCS8", "(", "privKey", ",", "tufdata", ".", "RoleName", "(", "block", ".", "Headers", "[", "\"", "\"", "]", ")", ",", "tufdata", ".", "GUN", "(", "block", ".", "Headers", "[", "\"", "\"", "]", ")", ",", "chosenPassphrase", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "loc", "!=", "writeTo", "{", "// next location is different from previous one. We've finished aggregating", "// data for the previous file. If we have data, write the previous file,", "// clear toWrite and set writeTo to the next path we're going to write", "if", "toWrite", "!=", "nil", "{", "if", "err", "=", "importToStores", "(", "to", ",", "writeTo", ",", "toWrite", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "// set up for aggregating next file's data", "toWrite", "=", "nil", "\n", "writeTo", "=", "loc", "\n", "}", "\n\n", "toWrite", "=", "append", "(", "toWrite", ",", "blockBytes", "...", ")", "\n", "}", "\n", "if", "toWrite", "!=", "nil", "{", "// close out final iteration if there's data left", "return", "importToStores", "(", "to", ",", "writeTo", ",", "toWrite", ")", "\n", "}", "\n", "if", "len", "(", "errBlocks", ")", ">", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "errBlocks", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ImportKeys expects an io.Reader containing one or more PEM blocks. // It reads PEM blocks one at a time until pem.Decode returns a nil // block. // Each block is written to the subpath indicated in the "path" PEM // header. If the file already exists, the file is truncated. Multiple // adjacent PEMs with the same "path" header are appended together.
[ "ImportKeys", "expects", "an", "io", ".", "Reader", "containing", "one", "or", "more", "PEM", "blocks", ".", "It", "reads", "PEM", "blocks", "one", "at", "a", "time", "until", "pem", ".", "Decode", "returns", "a", "nil", "block", ".", "Each", "block", "is", "written", "to", "the", "subpath", "indicated", "in", "the", "path", "PEM", "header", ".", "If", "the", "file", "already", "exists", "the", "file", "is", "truncated", ".", "Multiple", "adjacent", "PEMs", "with", "the", "same", "path", "header", "are", "appended", "together", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keys.go#L96-L167
train
theupdateframework/notary
trustmanager/keys.go
checkValidity
func checkValidity(block *pem.Block) (string, error) { // A root key or a delegations key should not have a gun // Note that a key that is not any of the canonical roles (except root) is a delegations key and should not have a gun switch block.Headers["role"] { case tufdata.CanonicalSnapshotRole.String(), tufdata.CanonicalTargetsRole.String(), tufdata.CanonicalTimestampRole.String(): // check if the key is missing a gun header or has an empty gun and error out since we don't know what gun it belongs to if block.Headers["gun"] == "" { logrus.Warnf("failed to import key (%s) to store: Cannot have canonical role key without a gun, don't know what gun it belongs to", block.Headers["path"]) return "", errors.New("invalid key pem block") } default: delete(block.Headers, "gun") } loc, ok := block.Headers["path"] // only if the path isn't specified do we get into this parsing path logic if !ok || loc == "" { // if the path isn't specified, we will try to infer the path rel to trust dir from the role (and then gun) // parse key for the keyID which we will save it by. // if the key is encrypted at this point, we will generate an error and continue since we don't know the ID to save it by decodedKey, err := utils.ParsePEMPrivateKey(pem.EncodeToMemory(block), "") if err != nil { logrus.Warn("failed to import key to store: Invalid key generated, key may be encrypted and does not contain path header") return "", errors.New("invalid key pem block") } loc = decodedKey.ID() } return loc, nil }
go
func checkValidity(block *pem.Block) (string, error) { // A root key or a delegations key should not have a gun // Note that a key that is not any of the canonical roles (except root) is a delegations key and should not have a gun switch block.Headers["role"] { case tufdata.CanonicalSnapshotRole.String(), tufdata.CanonicalTargetsRole.String(), tufdata.CanonicalTimestampRole.String(): // check if the key is missing a gun header or has an empty gun and error out since we don't know what gun it belongs to if block.Headers["gun"] == "" { logrus.Warnf("failed to import key (%s) to store: Cannot have canonical role key without a gun, don't know what gun it belongs to", block.Headers["path"]) return "", errors.New("invalid key pem block") } default: delete(block.Headers, "gun") } loc, ok := block.Headers["path"] // only if the path isn't specified do we get into this parsing path logic if !ok || loc == "" { // if the path isn't specified, we will try to infer the path rel to trust dir from the role (and then gun) // parse key for the keyID which we will save it by. // if the key is encrypted at this point, we will generate an error and continue since we don't know the ID to save it by decodedKey, err := utils.ParsePEMPrivateKey(pem.EncodeToMemory(block), "") if err != nil { logrus.Warn("failed to import key to store: Invalid key generated, key may be encrypted and does not contain path header") return "", errors.New("invalid key pem block") } loc = decodedKey.ID() } return loc, nil }
[ "func", "checkValidity", "(", "block", "*", "pem", ".", "Block", ")", "(", "string", ",", "error", ")", "{", "// A root key or a delegations key should not have a gun", "// Note that a key that is not any of the canonical roles (except root) is a delegations key and should not have a gun", "switch", "block", ".", "Headers", "[", "\"", "\"", "]", "{", "case", "tufdata", ".", "CanonicalSnapshotRole", ".", "String", "(", ")", ",", "tufdata", ".", "CanonicalTargetsRole", ".", "String", "(", ")", ",", "tufdata", ".", "CanonicalTimestampRole", ".", "String", "(", ")", ":", "// check if the key is missing a gun header or has an empty gun and error out since we don't know what gun it belongs to", "if", "block", ".", "Headers", "[", "\"", "\"", "]", "==", "\"", "\"", "{", "logrus", ".", "Warnf", "(", "\"", "\"", ",", "block", ".", "Headers", "[", "\"", "\"", "]", ")", "\n", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "delete", "(", "block", ".", "Headers", ",", "\"", "\"", ")", "\n", "}", "\n\n", "loc", ",", "ok", ":=", "block", ".", "Headers", "[", "\"", "\"", "]", "\n", "// only if the path isn't specified do we get into this parsing path logic", "if", "!", "ok", "||", "loc", "==", "\"", "\"", "{", "// if the path isn't specified, we will try to infer the path rel to trust dir from the role (and then gun)", "// parse key for the keyID which we will save it by.", "// if the key is encrypted at this point, we will generate an error and continue since we don't know the ID to save it by", "decodedKey", ",", "err", ":=", "utils", ".", "ParsePEMPrivateKey", "(", "pem", ".", "EncodeToMemory", "(", "block", ")", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "loc", "=", "decodedKey", ".", "ID", "(", ")", "\n", "}", "\n", "return", "loc", ",", "nil", "\n", "}" ]
// checkValidity ensures the fields in the pem headers are valid and parses out the location. // While importing a collection of keys, errors from this function should result in only the // current pem block being skipped.
[ "checkValidity", "ensures", "the", "fields", "in", "the", "pem", "headers", "are", "valid", "and", "parses", "out", "the", "location", ".", "While", "importing", "a", "collection", "of", "keys", "errors", "from", "this", "function", "should", "result", "in", "only", "the", "current", "pem", "block", "being", "skipped", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keys.go#L205-L234
train
theupdateframework/notary
server/timestamp/timestamp.go
GetOrCreateTimestamp
func GetOrCreateTimestamp(gun data.GUN, store storage.MetaStore, cryptoService signed.CryptoService) ( *time.Time, []byte, error) { updates := []storage.MetaUpdate{} lastModified, timestampJSON, err := store.GetCurrent(gun, data.CanonicalTimestampRole) if err != nil { logrus.Debug("error retrieving timestamp: ", err.Error()) return nil, nil, err } prev := &data.SignedTimestamp{} if err := json.Unmarshal(timestampJSON, prev); err != nil { logrus.Error("Failed to unmarshal existing timestamp") return nil, nil, err } snapChecksums, err := prev.GetSnapshot() if err != nil || snapChecksums == nil { return nil, nil, err } snapshotSHA256Bytes, ok := snapChecksums.Hashes[notary.SHA256] if !ok { return nil, nil, data.ErrMissingMeta{Role: data.CanonicalSnapshotRole.String()} } snapshotSHA256Hex := hex.EncodeToString(snapshotSHA256Bytes[:]) snapshotTime, snapshot, err := snapshot.GetOrCreateSnapshot(gun, snapshotSHA256Hex, store, cryptoService) if err != nil { logrus.Debug("Previous timestamp, but no valid snapshot for GUN ", gun) return nil, nil, err } snapshotRole := &data.SignedSnapshot{} if err := json.Unmarshal(snapshot, snapshotRole); err != nil { logrus.Error("Failed to unmarshal retrieved snapshot") return nil, nil, err } // If the snapshot was generated, we should write it with the timestamp if snapshotTime == nil { updates = append(updates, storage.MetaUpdate{Role: data.CanonicalSnapshotRole, Version: snapshotRole.Signed.Version, Data: snapshot}) } if !timestampExpired(prev) && !snapshotExpired(prev, snapshot) { return lastModified, timestampJSON, nil } tsUpdate, err := createTimestamp(gun, prev, snapshot, store, cryptoService) if err != nil { logrus.Error("Failed to create a new timestamp") return nil, nil, err } updates = append(updates, *tsUpdate) c := time.Now() // Write the timestamp, and potentially snapshot if err = store.UpdateMany(gun, updates); err != nil { return nil, nil, err } return &c, tsUpdate.Data, nil }
go
func GetOrCreateTimestamp(gun data.GUN, store storage.MetaStore, cryptoService signed.CryptoService) ( *time.Time, []byte, error) { updates := []storage.MetaUpdate{} lastModified, timestampJSON, err := store.GetCurrent(gun, data.CanonicalTimestampRole) if err != nil { logrus.Debug("error retrieving timestamp: ", err.Error()) return nil, nil, err } prev := &data.SignedTimestamp{} if err := json.Unmarshal(timestampJSON, prev); err != nil { logrus.Error("Failed to unmarshal existing timestamp") return nil, nil, err } snapChecksums, err := prev.GetSnapshot() if err != nil || snapChecksums == nil { return nil, nil, err } snapshotSHA256Bytes, ok := snapChecksums.Hashes[notary.SHA256] if !ok { return nil, nil, data.ErrMissingMeta{Role: data.CanonicalSnapshotRole.String()} } snapshotSHA256Hex := hex.EncodeToString(snapshotSHA256Bytes[:]) snapshotTime, snapshot, err := snapshot.GetOrCreateSnapshot(gun, snapshotSHA256Hex, store, cryptoService) if err != nil { logrus.Debug("Previous timestamp, but no valid snapshot for GUN ", gun) return nil, nil, err } snapshotRole := &data.SignedSnapshot{} if err := json.Unmarshal(snapshot, snapshotRole); err != nil { logrus.Error("Failed to unmarshal retrieved snapshot") return nil, nil, err } // If the snapshot was generated, we should write it with the timestamp if snapshotTime == nil { updates = append(updates, storage.MetaUpdate{Role: data.CanonicalSnapshotRole, Version: snapshotRole.Signed.Version, Data: snapshot}) } if !timestampExpired(prev) && !snapshotExpired(prev, snapshot) { return lastModified, timestampJSON, nil } tsUpdate, err := createTimestamp(gun, prev, snapshot, store, cryptoService) if err != nil { logrus.Error("Failed to create a new timestamp") return nil, nil, err } updates = append(updates, *tsUpdate) c := time.Now() // Write the timestamp, and potentially snapshot if err = store.UpdateMany(gun, updates); err != nil { return nil, nil, err } return &c, tsUpdate.Data, nil }
[ "func", "GetOrCreateTimestamp", "(", "gun", "data", ".", "GUN", ",", "store", "storage", ".", "MetaStore", ",", "cryptoService", "signed", ".", "CryptoService", ")", "(", "*", "time", ".", "Time", ",", "[", "]", "byte", ",", "error", ")", "{", "updates", ":=", "[", "]", "storage", ".", "MetaUpdate", "{", "}", "\n\n", "lastModified", ",", "timestampJSON", ",", "err", ":=", "store", ".", "GetCurrent", "(", "gun", ",", "data", ".", "CanonicalTimestampRole", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "prev", ":=", "&", "data", ".", "SignedTimestamp", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "timestampJSON", ",", "prev", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "snapChecksums", ",", "err", ":=", "prev", ".", "GetSnapshot", "(", ")", "\n", "if", "err", "!=", "nil", "||", "snapChecksums", "==", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "snapshotSHA256Bytes", ",", "ok", ":=", "snapChecksums", ".", "Hashes", "[", "notary", ".", "SHA256", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "nil", ",", "data", ".", "ErrMissingMeta", "{", "Role", ":", "data", ".", "CanonicalSnapshotRole", ".", "String", "(", ")", "}", "\n", "}", "\n", "snapshotSHA256Hex", ":=", "hex", ".", "EncodeToString", "(", "snapshotSHA256Bytes", "[", ":", "]", ")", "\n", "snapshotTime", ",", "snapshot", ",", "err", ":=", "snapshot", ".", "GetOrCreateSnapshot", "(", "gun", ",", "snapshotSHA256Hex", ",", "store", ",", "cryptoService", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "gun", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "snapshotRole", ":=", "&", "data", ".", "SignedSnapshot", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "snapshot", ",", "snapshotRole", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// If the snapshot was generated, we should write it with the timestamp", "if", "snapshotTime", "==", "nil", "{", "updates", "=", "append", "(", "updates", ",", "storage", ".", "MetaUpdate", "{", "Role", ":", "data", ".", "CanonicalSnapshotRole", ",", "Version", ":", "snapshotRole", ".", "Signed", ".", "Version", ",", "Data", ":", "snapshot", "}", ")", "\n", "}", "\n\n", "if", "!", "timestampExpired", "(", "prev", ")", "&&", "!", "snapshotExpired", "(", "prev", ",", "snapshot", ")", "{", "return", "lastModified", ",", "timestampJSON", ",", "nil", "\n", "}", "\n\n", "tsUpdate", ",", "err", ":=", "createTimestamp", "(", "gun", ",", "prev", ",", "snapshot", ",", "store", ",", "cryptoService", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "updates", "=", "append", "(", "updates", ",", "*", "tsUpdate", ")", "\n\n", "c", ":=", "time", ".", "Now", "(", ")", "\n\n", "// Write the timestamp, and potentially snapshot", "if", "err", "=", "store", ".", "UpdateMany", "(", "gun", ",", "updates", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "&", "c", ",", "tsUpdate", ".", "Data", ",", "nil", "\n", "}" ]
// GetOrCreateTimestamp returns the current timestamp for the gun. This may mean // a new timestamp is generated either because none exists, or because the current // one has expired. Once generated, the timestamp is saved in the store. // Additionally, if we had to generate a new snapshot for this timestamp, // it is also saved in the store
[ "GetOrCreateTimestamp", "returns", "the", "current", "timestamp", "for", "the", "gun", ".", "This", "may", "mean", "a", "new", "timestamp", "is", "generated", "either", "because", "none", "exists", "or", "because", "the", "current", "one", "has", "expired", ".", "Once", "generated", "the", "timestamp", "is", "saved", "in", "the", "store", ".", "Additionally", "if", "we", "had", "to", "generate", "a", "new", "snapshot", "for", "this", "timestamp", "it", "is", "also", "saved", "in", "the", "store" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/timestamp/timestamp.go#L74-L133
train
theupdateframework/notary
server/timestamp/timestamp.go
timestampExpired
func timestampExpired(ts *data.SignedTimestamp) bool { return signed.IsExpired(ts.Signed.Expires) }
go
func timestampExpired(ts *data.SignedTimestamp) bool { return signed.IsExpired(ts.Signed.Expires) }
[ "func", "timestampExpired", "(", "ts", "*", "data", ".", "SignedTimestamp", ")", "bool", "{", "return", "signed", ".", "IsExpired", "(", "ts", ".", "Signed", ".", "Expires", ")", "\n", "}" ]
// timestampExpired compares the current time to the expiry time of the timestamp
[ "timestampExpired", "compares", "the", "current", "time", "to", "the", "expiry", "time", "of", "the", "timestamp" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/timestamp/timestamp.go#L136-L138
train
theupdateframework/notary
server/timestamp/timestamp.go
createTimestamp
func createTimestamp(gun data.GUN, prev *data.SignedTimestamp, snapshot []byte, store storage.MetaStore, cryptoService signed.CryptoService) (*storage.MetaUpdate, error) { builder := tuf.NewRepoBuilder(gun, cryptoService, trustpinning.TrustPinConfig{}) // load the current root to ensure we use the correct timestamp key. _, root, err := store.GetCurrent(gun, data.CanonicalRootRole) if err != nil { logrus.Debug("Previous timestamp, but no root for GUN ", gun) return nil, err } if err := builder.Load(data.CanonicalRootRole, root, 1, false); err != nil { logrus.Debug("Could not load valid previous root for GUN ", gun) return nil, err } // load snapshot so we can include it in timestamp if err := builder.Load(data.CanonicalSnapshotRole, snapshot, 1, false); err != nil { logrus.Debug("Could not load valid previous snapshot for GUN ", gun) return nil, err } meta, ver, err := builder.GenerateTimestamp(prev) if err != nil { return nil, err } return &storage.MetaUpdate{ Role: data.CanonicalTimestampRole, Version: ver, Data: meta, }, nil }
go
func createTimestamp(gun data.GUN, prev *data.SignedTimestamp, snapshot []byte, store storage.MetaStore, cryptoService signed.CryptoService) (*storage.MetaUpdate, error) { builder := tuf.NewRepoBuilder(gun, cryptoService, trustpinning.TrustPinConfig{}) // load the current root to ensure we use the correct timestamp key. _, root, err := store.GetCurrent(gun, data.CanonicalRootRole) if err != nil { logrus.Debug("Previous timestamp, but no root for GUN ", gun) return nil, err } if err := builder.Load(data.CanonicalRootRole, root, 1, false); err != nil { logrus.Debug("Could not load valid previous root for GUN ", gun) return nil, err } // load snapshot so we can include it in timestamp if err := builder.Load(data.CanonicalSnapshotRole, snapshot, 1, false); err != nil { logrus.Debug("Could not load valid previous snapshot for GUN ", gun) return nil, err } meta, ver, err := builder.GenerateTimestamp(prev) if err != nil { return nil, err } return &storage.MetaUpdate{ Role: data.CanonicalTimestampRole, Version: ver, Data: meta, }, nil }
[ "func", "createTimestamp", "(", "gun", "data", ".", "GUN", ",", "prev", "*", "data", ".", "SignedTimestamp", ",", "snapshot", "[", "]", "byte", ",", "store", "storage", ".", "MetaStore", ",", "cryptoService", "signed", ".", "CryptoService", ")", "(", "*", "storage", ".", "MetaUpdate", ",", "error", ")", "{", "builder", ":=", "tuf", ".", "NewRepoBuilder", "(", "gun", ",", "cryptoService", ",", "trustpinning", ".", "TrustPinConfig", "{", "}", ")", "\n\n", "// load the current root to ensure we use the correct timestamp key.", "_", ",", "root", ",", "err", ":=", "store", ".", "GetCurrent", "(", "gun", ",", "data", ".", "CanonicalRootRole", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "gun", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "builder", ".", "Load", "(", "data", ".", "CanonicalRootRole", ",", "root", ",", "1", ",", "false", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "gun", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// load snapshot so we can include it in timestamp", "if", "err", ":=", "builder", ".", "Load", "(", "data", ".", "CanonicalSnapshotRole", ",", "snapshot", ",", "1", ",", "false", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "gun", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "meta", ",", "ver", ",", "err", ":=", "builder", ".", "GenerateTimestamp", "(", "prev", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "storage", ".", "MetaUpdate", "{", "Role", ":", "data", ".", "CanonicalTimestampRole", ",", "Version", ":", "ver", ",", "Data", ":", "meta", ",", "}", ",", "nil", "\n", "}" ]
// CreateTimestamp creates a new timestamp. If a prev timestamp is provided, it // is assumed this is the immediately previous one, and the new one will have a // version number one higher than prev. The store is used to lookup the current // snapshot, this function does not save the newly generated timestamp.
[ "CreateTimestamp", "creates", "a", "new", "timestamp", ".", "If", "a", "prev", "timestamp", "is", "provided", "it", "is", "assumed", "this", "is", "the", "immediately", "previous", "one", "and", "the", "new", "one", "will", "have", "a", "version", "number", "one", "higher", "than", "prev", ".", "The", "store", "is", "used", "to", "lookup", "the", "current", "snapshot", "this", "function", "does", "not", "save", "the", "newly", "generated", "timestamp", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/timestamp/timestamp.go#L152-L183
train
theupdateframework/notary
tuf/utils/utils.go
StrSliceContains
func StrSliceContains(ss []string, s string) bool { for _, v := range ss { if v == s { return true } } return false }
go
func StrSliceContains(ss []string, s string) bool { for _, v := range ss { if v == s { return true } } return false }
[ "func", "StrSliceContains", "(", "ss", "[", "]", "string", ",", "s", "string", ")", "bool", "{", "for", "_", ",", "v", ":=", "range", "ss", "{", "if", "v", "==", "s", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// StrSliceContains checks if the given string appears in the slice
[ "StrSliceContains", "checks", "if", "the", "given", "string", "appears", "in", "the", "slice" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L14-L21
train
theupdateframework/notary
tuf/utils/utils.go
RoleNameSliceContains
func RoleNameSliceContains(ss []data.RoleName, s data.RoleName) bool { for _, v := range ss { if v == s { return true } } return false }
go
func RoleNameSliceContains(ss []data.RoleName, s data.RoleName) bool { for _, v := range ss { if v == s { return true } } return false }
[ "func", "RoleNameSliceContains", "(", "ss", "[", "]", "data", ".", "RoleName", ",", "s", "data", ".", "RoleName", ")", "bool", "{", "for", "_", ",", "v", ":=", "range", "ss", "{", "if", "v", "==", "s", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// RoleNameSliceContains checks if the given string appears in the slice
[ "RoleNameSliceContains", "checks", "if", "the", "given", "string", "appears", "in", "the", "slice" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L24-L31
train
theupdateframework/notary
tuf/utils/utils.go
RoleNameSliceRemove
func RoleNameSliceRemove(ss []data.RoleName, s data.RoleName) []data.RoleName { res := []data.RoleName{} for _, v := range ss { if v != s { res = append(res, v) } } return res }
go
func RoleNameSliceRemove(ss []data.RoleName, s data.RoleName) []data.RoleName { res := []data.RoleName{} for _, v := range ss { if v != s { res = append(res, v) } } return res }
[ "func", "RoleNameSliceRemove", "(", "ss", "[", "]", "data", ".", "RoleName", ",", "s", "data", ".", "RoleName", ")", "[", "]", "data", ".", "RoleName", "{", "res", ":=", "[", "]", "data", ".", "RoleName", "{", "}", "\n", "for", "_", ",", "v", ":=", "range", "ss", "{", "if", "v", "!=", "s", "{", "res", "=", "append", "(", "res", ",", "v", ")", "\n", "}", "\n", "}", "\n", "return", "res", "\n", "}" ]
// RoleNameSliceRemove removes the the given RoleName from the slice, returning a new slice
[ "RoleNameSliceRemove", "removes", "the", "the", "given", "RoleName", "from", "the", "slice", "returning", "a", "new", "slice" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L34-L42
train
theupdateframework/notary
tuf/utils/utils.go
DoHash
func DoHash(alg string, d []byte) []byte { switch alg { case "sha256": digest := sha256.Sum256(d) return digest[:] case "sha512": digest := sha512.Sum512(d) return digest[:] } return nil }
go
func DoHash(alg string, d []byte) []byte { switch alg { case "sha256": digest := sha256.Sum256(d) return digest[:] case "sha512": digest := sha512.Sum512(d) return digest[:] } return nil }
[ "func", "DoHash", "(", "alg", "string", ",", "d", "[", "]", "byte", ")", "[", "]", "byte", "{", "switch", "alg", "{", "case", "\"", "\"", ":", "digest", ":=", "sha256", ".", "Sum256", "(", "d", ")", "\n", "return", "digest", "[", ":", "]", "\n", "case", "\"", "\"", ":", "digest", ":=", "sha512", ".", "Sum512", "(", "d", ")", "\n", "return", "digest", "[", ":", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DoHash returns the digest of d using the hashing algorithm named // in alg
[ "DoHash", "returns", "the", "digest", "of", "d", "using", "the", "hashing", "algorithm", "named", "in", "alg" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L57-L67
train
theupdateframework/notary
tuf/utils/utils.go
UnusedDelegationKeys
func UnusedDelegationKeys(t data.SignedTargets) []string { // compare ids to all still active key ids in all active roles // with the targets file found := make(map[string]bool) for _, r := range t.Signed.Delegations.Roles { for _, id := range r.KeyIDs { found[id] = true } } var discard []string for id := range t.Signed.Delegations.Keys { if !found[id] { discard = append(discard, id) } } return discard }
go
func UnusedDelegationKeys(t data.SignedTargets) []string { // compare ids to all still active key ids in all active roles // with the targets file found := make(map[string]bool) for _, r := range t.Signed.Delegations.Roles { for _, id := range r.KeyIDs { found[id] = true } } var discard []string for id := range t.Signed.Delegations.Keys { if !found[id] { discard = append(discard, id) } } return discard }
[ "func", "UnusedDelegationKeys", "(", "t", "data", ".", "SignedTargets", ")", "[", "]", "string", "{", "// compare ids to all still active key ids in all active roles", "// with the targets file", "found", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "r", ":=", "range", "t", ".", "Signed", ".", "Delegations", ".", "Roles", "{", "for", "_", ",", "id", ":=", "range", "r", ".", "KeyIDs", "{", "found", "[", "id", "]", "=", "true", "\n", "}", "\n", "}", "\n", "var", "discard", "[", "]", "string", "\n", "for", "id", ":=", "range", "t", ".", "Signed", ".", "Delegations", ".", "Keys", "{", "if", "!", "found", "[", "id", "]", "{", "discard", "=", "append", "(", "discard", ",", "id", ")", "\n", "}", "\n", "}", "\n", "return", "discard", "\n", "}" ]
// UnusedDelegationKeys prunes a list of keys, returning those that are no // longer in use for a given targets file
[ "UnusedDelegationKeys", "prunes", "a", "list", "of", "keys", "returning", "those", "that", "are", "no", "longer", "in", "use", "for", "a", "given", "targets", "file" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L71-L87
train
theupdateframework/notary
tuf/utils/utils.go
RemoveUnusedKeys
func RemoveUnusedKeys(t *data.SignedTargets) { unusedIDs := UnusedDelegationKeys(*t) for _, id := range unusedIDs { delete(t.Signed.Delegations.Keys, id) } }
go
func RemoveUnusedKeys(t *data.SignedTargets) { unusedIDs := UnusedDelegationKeys(*t) for _, id := range unusedIDs { delete(t.Signed.Delegations.Keys, id) } }
[ "func", "RemoveUnusedKeys", "(", "t", "*", "data", ".", "SignedTargets", ")", "{", "unusedIDs", ":=", "UnusedDelegationKeys", "(", "*", "t", ")", "\n", "for", "_", ",", "id", ":=", "range", "unusedIDs", "{", "delete", "(", "t", ".", "Signed", ".", "Delegations", ".", "Keys", ",", "id", ")", "\n", "}", "\n", "}" ]
// RemoveUnusedKeys determines which keys in the slice of IDs are no longer // used in the given targets file and removes them from the delegated keys // map
[ "RemoveUnusedKeys", "determines", "which", "keys", "in", "the", "slice", "of", "IDs", "are", "no", "longer", "used", "in", "the", "given", "targets", "file", "and", "removes", "them", "from", "the", "delegated", "keys", "map" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L92-L97
train
theupdateframework/notary
tuf/utils/utils.go
ConsistentName
func ConsistentName(role string, hashSHA256 []byte) string { if len(hashSHA256) > 0 { hash := hex.EncodeToString(hashSHA256) return fmt.Sprintf("%s.%s", role, hash) } return role }
go
func ConsistentName(role string, hashSHA256 []byte) string { if len(hashSHA256) > 0 { hash := hex.EncodeToString(hashSHA256) return fmt.Sprintf("%s.%s", role, hash) } return role }
[ "func", "ConsistentName", "(", "role", "string", ",", "hashSHA256", "[", "]", "byte", ")", "string", "{", "if", "len", "(", "hashSHA256", ")", ">", "0", "{", "hash", ":=", "hex", ".", "EncodeToString", "(", "hashSHA256", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "role", ",", "hash", ")", "\n", "}", "\n", "return", "role", "\n", "}" ]
// ConsistentName generates the appropriate HTTP URL path for the role, // based on whether the repo is marked as consistent. The RemoteStore // is responsible for adding file extensions.
[ "ConsistentName", "generates", "the", "appropriate", "HTTP", "URL", "path", "for", "the", "role", "based", "on", "whether", "the", "repo", "is", "marked", "as", "consistent", ".", "The", "RemoteStore", "is", "responsible", "for", "adding", "file", "extensions", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L113-L119
train
theupdateframework/notary
trustpinning/trustpin.go
NewTrustPinChecker
func NewTrustPinChecker(trustPinConfig TrustPinConfig, gun data.GUN, firstBootstrap bool) (CertChecker, error) { t := trustPinChecker{gun: gun, config: trustPinConfig} // Determine the mode, and if it's even valid if pinnedCerts, ok := trustPinConfig.Certs[gun.String()]; ok { logrus.Debugf("trust-pinning using Cert IDs") t.pinnedCertIDs = pinnedCerts return t.certsCheck, nil } var ok bool t.pinnedCertIDs, ok = wildcardMatch(gun, trustPinConfig.Certs) if ok { return t.certsCheck, nil } if caFilepath, err := getPinnedCAFilepathByPrefix(gun, trustPinConfig); err == nil { logrus.Debugf("trust-pinning using root CA bundle at: %s", caFilepath) // Try to add the CA certs from its bundle file to our certificate store, // and use it to validate certs in the root.json later caCerts, err := utils.LoadCertBundleFromFile(caFilepath) if err != nil { return nil, fmt.Errorf("could not load root cert from CA path") } // Now only consider certificates that are direct children from this CA cert chain caRootPool := x509.NewCertPool() for _, caCert := range caCerts { if err = utils.ValidateCertificate(caCert, true); err != nil { logrus.Debugf("ignoring root CA certificate with CN %s in bundle: %s", caCert.Subject.CommonName, err) continue } caRootPool.AddCert(caCert) } // If we didn't have any valid CA certs, error out if len(caRootPool.Subjects()) == 0 { return nil, fmt.Errorf("invalid CA certs provided") } t.pinnedCAPool = caRootPool return t.caCheck, nil } // If TOFUs is disabled and we don't have any previous trusted root data for this GUN, we error out if trustPinConfig.DisableTOFU && firstBootstrap { return nil, fmt.Errorf("invalid trust pinning specified") } return t.tofusCheck, nil }
go
func NewTrustPinChecker(trustPinConfig TrustPinConfig, gun data.GUN, firstBootstrap bool) (CertChecker, error) { t := trustPinChecker{gun: gun, config: trustPinConfig} // Determine the mode, and if it's even valid if pinnedCerts, ok := trustPinConfig.Certs[gun.String()]; ok { logrus.Debugf("trust-pinning using Cert IDs") t.pinnedCertIDs = pinnedCerts return t.certsCheck, nil } var ok bool t.pinnedCertIDs, ok = wildcardMatch(gun, trustPinConfig.Certs) if ok { return t.certsCheck, nil } if caFilepath, err := getPinnedCAFilepathByPrefix(gun, trustPinConfig); err == nil { logrus.Debugf("trust-pinning using root CA bundle at: %s", caFilepath) // Try to add the CA certs from its bundle file to our certificate store, // and use it to validate certs in the root.json later caCerts, err := utils.LoadCertBundleFromFile(caFilepath) if err != nil { return nil, fmt.Errorf("could not load root cert from CA path") } // Now only consider certificates that are direct children from this CA cert chain caRootPool := x509.NewCertPool() for _, caCert := range caCerts { if err = utils.ValidateCertificate(caCert, true); err != nil { logrus.Debugf("ignoring root CA certificate with CN %s in bundle: %s", caCert.Subject.CommonName, err) continue } caRootPool.AddCert(caCert) } // If we didn't have any valid CA certs, error out if len(caRootPool.Subjects()) == 0 { return nil, fmt.Errorf("invalid CA certs provided") } t.pinnedCAPool = caRootPool return t.caCheck, nil } // If TOFUs is disabled and we don't have any previous trusted root data for this GUN, we error out if trustPinConfig.DisableTOFU && firstBootstrap { return nil, fmt.Errorf("invalid trust pinning specified") } return t.tofusCheck, nil }
[ "func", "NewTrustPinChecker", "(", "trustPinConfig", "TrustPinConfig", ",", "gun", "data", ".", "GUN", ",", "firstBootstrap", "bool", ")", "(", "CertChecker", ",", "error", ")", "{", "t", ":=", "trustPinChecker", "{", "gun", ":", "gun", ",", "config", ":", "trustPinConfig", "}", "\n", "// Determine the mode, and if it's even valid", "if", "pinnedCerts", ",", "ok", ":=", "trustPinConfig", ".", "Certs", "[", "gun", ".", "String", "(", ")", "]", ";", "ok", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ")", "\n", "t", ".", "pinnedCertIDs", "=", "pinnedCerts", "\n", "return", "t", ".", "certsCheck", ",", "nil", "\n", "}", "\n", "var", "ok", "bool", "\n", "t", ".", "pinnedCertIDs", ",", "ok", "=", "wildcardMatch", "(", "gun", ",", "trustPinConfig", ".", "Certs", ")", "\n", "if", "ok", "{", "return", "t", ".", "certsCheck", ",", "nil", "\n", "}", "\n\n", "if", "caFilepath", ",", "err", ":=", "getPinnedCAFilepathByPrefix", "(", "gun", ",", "trustPinConfig", ")", ";", "err", "==", "nil", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "caFilepath", ")", "\n\n", "// Try to add the CA certs from its bundle file to our certificate store,", "// and use it to validate certs in the root.json later", "caCerts", ",", "err", ":=", "utils", ".", "LoadCertBundleFromFile", "(", "caFilepath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "// Now only consider certificates that are direct children from this CA cert chain", "caRootPool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "for", "_", ",", "caCert", ":=", "range", "caCerts", "{", "if", "err", "=", "utils", ".", "ValidateCertificate", "(", "caCert", ",", "true", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "caCert", ".", "Subject", ".", "CommonName", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "caRootPool", ".", "AddCert", "(", "caCert", ")", "\n", "}", "\n", "// If we didn't have any valid CA certs, error out", "if", "len", "(", "caRootPool", ".", "Subjects", "(", ")", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "t", ".", "pinnedCAPool", "=", "caRootPool", "\n", "return", "t", ".", "caCheck", ",", "nil", "\n", "}", "\n\n", "// If TOFUs is disabled and we don't have any previous trusted root data for this GUN, we error out", "if", "trustPinConfig", ".", "DisableTOFU", "&&", "firstBootstrap", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n\n", "}", "\n", "return", "t", ".", "tofusCheck", ",", "nil", "\n", "}" ]
// NewTrustPinChecker returns a new certChecker function from a TrustPinConfig for a GUN
[ "NewTrustPinChecker", "returns", "a", "new", "certChecker", "function", "from", "a", "TrustPinConfig", "for", "a", "GUN" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustpinning/trustpin.go#L47-L93
train
theupdateframework/notary
server/snapshot/snapshot.go
GetOrCreateSnapshotKey
func GetOrCreateSnapshotKey(gun data.GUN, store storage.MetaStore, crypto signed.CryptoService, createAlgorithm string) (data.PublicKey, error) { _, rootJSON, err := store.GetCurrent(gun, data.CanonicalRootRole) if err != nil { // If the error indicates we couldn't find the root, create a new key if _, ok := err.(storage.ErrNotFound); !ok { logrus.Errorf("Error when retrieving root role for GUN %s: %v", gun.String(), err) return nil, err } return crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm) } // If we have a current root, parse out the public key for the snapshot role, and return it repoSignedRoot := new(data.SignedRoot) if err := json.Unmarshal(rootJSON, repoSignedRoot); err != nil { logrus.Errorf("Failed to unmarshal existing root for GUN %s to retrieve snapshot key ID", gun) return nil, err } snapshotRole, err := repoSignedRoot.BuildBaseRole(data.CanonicalSnapshotRole) if err != nil { logrus.Errorf("Failed to extract snapshot role from root for GUN %s", gun) return nil, err } // We currently only support single keys for snapshot and timestamp, so we can return the first and only key in the map if the signer has it for keyID := range snapshotRole.Keys { if pubKey := crypto.GetKey(keyID); pubKey != nil { return pubKey, nil } } logrus.Debugf("Failed to find any snapshot keys in cryptosigner from root for GUN %s, generating new key", gun) return crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm) }
go
func GetOrCreateSnapshotKey(gun data.GUN, store storage.MetaStore, crypto signed.CryptoService, createAlgorithm string) (data.PublicKey, error) { _, rootJSON, err := store.GetCurrent(gun, data.CanonicalRootRole) if err != nil { // If the error indicates we couldn't find the root, create a new key if _, ok := err.(storage.ErrNotFound); !ok { logrus.Errorf("Error when retrieving root role for GUN %s: %v", gun.String(), err) return nil, err } return crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm) } // If we have a current root, parse out the public key for the snapshot role, and return it repoSignedRoot := new(data.SignedRoot) if err := json.Unmarshal(rootJSON, repoSignedRoot); err != nil { logrus.Errorf("Failed to unmarshal existing root for GUN %s to retrieve snapshot key ID", gun) return nil, err } snapshotRole, err := repoSignedRoot.BuildBaseRole(data.CanonicalSnapshotRole) if err != nil { logrus.Errorf("Failed to extract snapshot role from root for GUN %s", gun) return nil, err } // We currently only support single keys for snapshot and timestamp, so we can return the first and only key in the map if the signer has it for keyID := range snapshotRole.Keys { if pubKey := crypto.GetKey(keyID); pubKey != nil { return pubKey, nil } } logrus.Debugf("Failed to find any snapshot keys in cryptosigner from root for GUN %s, generating new key", gun) return crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm) }
[ "func", "GetOrCreateSnapshotKey", "(", "gun", "data", ".", "GUN", ",", "store", "storage", ".", "MetaStore", ",", "crypto", "signed", ".", "CryptoService", ",", "createAlgorithm", "string", ")", "(", "data", ".", "PublicKey", ",", "error", ")", "{", "_", ",", "rootJSON", ",", "err", ":=", "store", ".", "GetCurrent", "(", "gun", ",", "data", ".", "CanonicalRootRole", ")", "\n", "if", "err", "!=", "nil", "{", "// If the error indicates we couldn't find the root, create a new key", "if", "_", ",", "ok", ":=", "err", ".", "(", "storage", ".", "ErrNotFound", ")", ";", "!", "ok", "{", "logrus", ".", "Errorf", "(", "\"", "\"", ",", "gun", ".", "String", "(", ")", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "crypto", ".", "Create", "(", "data", ".", "CanonicalSnapshotRole", ",", "gun", ",", "createAlgorithm", ")", "\n", "}", "\n\n", "// If we have a current root, parse out the public key for the snapshot role, and return it", "repoSignedRoot", ":=", "new", "(", "data", ".", "SignedRoot", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "rootJSON", ",", "repoSignedRoot", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Errorf", "(", "\"", "\"", ",", "gun", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "snapshotRole", ",", "err", ":=", "repoSignedRoot", ".", "BuildBaseRole", "(", "data", ".", "CanonicalSnapshotRole", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Errorf", "(", "\"", "\"", ",", "gun", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// We currently only support single keys for snapshot and timestamp, so we can return the first and only key in the map if the signer has it", "for", "keyID", ":=", "range", "snapshotRole", ".", "Keys", "{", "if", "pubKey", ":=", "crypto", ".", "GetKey", "(", "keyID", ")", ";", "pubKey", "!=", "nil", "{", "return", "pubKey", ",", "nil", "\n", "}", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "gun", ")", "\n", "return", "crypto", ".", "Create", "(", "data", ".", "CanonicalSnapshotRole", ",", "gun", ",", "createAlgorithm", ")", "\n", "}" ]
// GetOrCreateSnapshotKey either creates a new snapshot key, or returns // the existing one. Only the PublicKey is returned. The private part // is held by the CryptoService.
[ "GetOrCreateSnapshotKey", "either", "creates", "a", "new", "snapshot", "key", "or", "returns", "the", "existing", "one", ".", "Only", "the", "PublicKey", "is", "returned", ".", "The", "private", "part", "is", "held", "by", "the", "CryptoService", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/snapshot/snapshot.go#L19-L51
train
theupdateframework/notary
server/snapshot/snapshot.go
RotateSnapshotKey
func RotateSnapshotKey(gun data.GUN, store storage.MetaStore, crypto signed.CryptoService, createAlgorithm string) (data.PublicKey, error) { // Always attempt to create a new key, but this might be rate-limited key, err := crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm) if err != nil { return nil, err } logrus.Debug("Created new pending snapshot key ", key.ID(), "to rotate to for ", gun, ". With algo: ", key.Algorithm()) return key, nil }
go
func RotateSnapshotKey(gun data.GUN, store storage.MetaStore, crypto signed.CryptoService, createAlgorithm string) (data.PublicKey, error) { // Always attempt to create a new key, but this might be rate-limited key, err := crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm) if err != nil { return nil, err } logrus.Debug("Created new pending snapshot key ", key.ID(), "to rotate to for ", gun, ". With algo: ", key.Algorithm()) return key, nil }
[ "func", "RotateSnapshotKey", "(", "gun", "data", ".", "GUN", ",", "store", "storage", ".", "MetaStore", ",", "crypto", "signed", ".", "CryptoService", ",", "createAlgorithm", "string", ")", "(", "data", ".", "PublicKey", ",", "error", ")", "{", "// Always attempt to create a new key, but this might be rate-limited", "key", ",", "err", ":=", "crypto", ".", "Create", "(", "data", ".", "CanonicalSnapshotRole", ",", "gun", ",", "createAlgorithm", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logrus", ".", "Debug", "(", "\"", "\"", ",", "key", ".", "ID", "(", ")", ",", "\"", "\"", ",", "gun", ",", "\"", "\"", ",", "key", ".", "Algorithm", "(", ")", ")", "\n", "return", "key", ",", "nil", "\n", "}" ]
// RotateSnapshotKey attempts to rotate a snapshot key in the signer, but might be rate-limited by the signer
[ "RotateSnapshotKey", "attempts", "to", "rotate", "a", "snapshot", "key", "in", "the", "signer", "but", "might", "be", "rate", "-", "limited", "by", "the", "signer" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/snapshot/snapshot.go#L54-L62
train
theupdateframework/notary
server/snapshot/snapshot.go
GetOrCreateSnapshot
func GetOrCreateSnapshot(gun data.GUN, checksum string, store storage.MetaStore, cryptoService signed.CryptoService) ( *time.Time, []byte, error) { lastModified, currentJSON, err := store.GetChecksum(gun, data.CanonicalSnapshotRole, checksum) if err != nil { return nil, nil, err } prev := new(data.SignedSnapshot) if err := json.Unmarshal(currentJSON, prev); err != nil { logrus.Error("Failed to unmarshal existing snapshot for GUN ", gun) return nil, nil, err } if !snapshotExpired(prev) { return lastModified, currentJSON, nil } builder := tuf.NewRepoBuilder(gun, cryptoService, trustpinning.TrustPinConfig{}) // load the current root to ensure we use the correct snapshot key. _, rootJSON, err := store.GetCurrent(gun, data.CanonicalRootRole) if err != nil { logrus.Debug("Previous snapshot, but no root for GUN ", gun) return nil, nil, err } if err := builder.Load(data.CanonicalRootRole, rootJSON, 1, false); err != nil { logrus.Debug("Could not load valid previous root for GUN ", gun) return nil, nil, err } meta, _, err := builder.GenerateSnapshot(prev) if err != nil { return nil, nil, err } return nil, meta, nil }
go
func GetOrCreateSnapshot(gun data.GUN, checksum string, store storage.MetaStore, cryptoService signed.CryptoService) ( *time.Time, []byte, error) { lastModified, currentJSON, err := store.GetChecksum(gun, data.CanonicalSnapshotRole, checksum) if err != nil { return nil, nil, err } prev := new(data.SignedSnapshot) if err := json.Unmarshal(currentJSON, prev); err != nil { logrus.Error("Failed to unmarshal existing snapshot for GUN ", gun) return nil, nil, err } if !snapshotExpired(prev) { return lastModified, currentJSON, nil } builder := tuf.NewRepoBuilder(gun, cryptoService, trustpinning.TrustPinConfig{}) // load the current root to ensure we use the correct snapshot key. _, rootJSON, err := store.GetCurrent(gun, data.CanonicalRootRole) if err != nil { logrus.Debug("Previous snapshot, but no root for GUN ", gun) return nil, nil, err } if err := builder.Load(data.CanonicalRootRole, rootJSON, 1, false); err != nil { logrus.Debug("Could not load valid previous root for GUN ", gun) return nil, nil, err } meta, _, err := builder.GenerateSnapshot(prev) if err != nil { return nil, nil, err } return nil, meta, nil }
[ "func", "GetOrCreateSnapshot", "(", "gun", "data", ".", "GUN", ",", "checksum", "string", ",", "store", "storage", ".", "MetaStore", ",", "cryptoService", "signed", ".", "CryptoService", ")", "(", "*", "time", ".", "Time", ",", "[", "]", "byte", ",", "error", ")", "{", "lastModified", ",", "currentJSON", ",", "err", ":=", "store", ".", "GetChecksum", "(", "gun", ",", "data", ".", "CanonicalSnapshotRole", ",", "checksum", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "prev", ":=", "new", "(", "data", ".", "SignedSnapshot", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "currentJSON", ",", "prev", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Error", "(", "\"", "\"", ",", "gun", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "if", "!", "snapshotExpired", "(", "prev", ")", "{", "return", "lastModified", ",", "currentJSON", ",", "nil", "\n", "}", "\n\n", "builder", ":=", "tuf", ".", "NewRepoBuilder", "(", "gun", ",", "cryptoService", ",", "trustpinning", ".", "TrustPinConfig", "{", "}", ")", "\n\n", "// load the current root to ensure we use the correct snapshot key.", "_", ",", "rootJSON", ",", "err", ":=", "store", ".", "GetCurrent", "(", "gun", ",", "data", ".", "CanonicalRootRole", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "gun", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "builder", ".", "Load", "(", "data", ".", "CanonicalRootRole", ",", "rootJSON", ",", "1", ",", "false", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Debug", "(", "\"", "\"", ",", "gun", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "meta", ",", "_", ",", "err", ":=", "builder", ".", "GenerateSnapshot", "(", "prev", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "return", "nil", ",", "meta", ",", "nil", "\n", "}" ]
// GetOrCreateSnapshot either returns the existing latest snapshot, or uses // whatever the most recent snapshot is to generate the next one, only updating // the expiry time and version. Note that this function does not write generated // snapshots to the underlying data store, and will either return the latest snapshot time // or nil as the time modified
[ "GetOrCreateSnapshot", "either", "returns", "the", "existing", "latest", "snapshot", "or", "uses", "whatever", "the", "most", "recent", "snapshot", "is", "to", "generate", "the", "next", "one", "only", "updating", "the", "expiry", "time", "and", "version", ".", "Note", "that", "this", "function", "does", "not", "write", "generated", "snapshots", "to", "the", "underlying", "data", "store", "and", "will", "either", "return", "the", "latest", "snapshot", "time", "or", "nil", "as", "the", "time", "modified" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/snapshot/snapshot.go#L69-L106
train
theupdateframework/notary
server/snapshot/snapshot.go
snapshotExpired
func snapshotExpired(sn *data.SignedSnapshot) bool { return signed.IsExpired(sn.Signed.Expires) }
go
func snapshotExpired(sn *data.SignedSnapshot) bool { return signed.IsExpired(sn.Signed.Expires) }
[ "func", "snapshotExpired", "(", "sn", "*", "data", ".", "SignedSnapshot", ")", "bool", "{", "return", "signed", ".", "IsExpired", "(", "sn", ".", "Signed", ".", "Expires", ")", "\n", "}" ]
// snapshotExpired simply checks if the snapshot is past its expiry time
[ "snapshotExpired", "simply", "checks", "if", "the", "snapshot", "is", "past", "its", "expiry", "time" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/snapshot/snapshot.go#L109-L111
train
theupdateframework/notary
storage/offlinestore.go
GetSized
func (es OfflineStore) GetSized(name string, size int64) ([]byte, error) { return nil, err }
go
func (es OfflineStore) GetSized(name string, size int64) ([]byte, error) { return nil, err }
[ "func", "(", "es", "OfflineStore", ")", "GetSized", "(", "name", "string", ",", "size", "int64", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "nil", ",", "err", "\n", "}" ]
// GetSized returns ErrOffline
[ "GetSized", "returns", "ErrOffline" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/offlinestore.go#L21-L23
train
theupdateframework/notary
storage/offlinestore.go
GetKey
func (es OfflineStore) GetKey(role data.RoleName) ([]byte, error) { return nil, err }
go
func (es OfflineStore) GetKey(role data.RoleName) ([]byte, error) { return nil, err }
[ "func", "(", "es", "OfflineStore", ")", "GetKey", "(", "role", "data", ".", "RoleName", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "nil", ",", "err", "\n", "}" ]
// GetKey returns ErrOffline
[ "GetKey", "returns", "ErrOffline" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/offlinestore.go#L41-L43
train
theupdateframework/notary
client/delegations.go
AddDelegationRoleAndKeys
func (r *repository) AddDelegationRoleAndKeys(name data.RoleName, delegationKeys []data.PublicKey) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Adding delegation "%s" with threshold %d, and %d keys\n`, name, notary.MinThreshold, len(delegationKeys)) // Defaulting to threshold of 1, since we don't allow for larger thresholds at the moment. tdJSON, err := json.Marshal(&changelist.TUFDelegation{ NewThreshold: notary.MinThreshold, AddKeys: data.KeyList(delegationKeys), }) if err != nil { return err } template := newCreateDelegationChange(name, tdJSON) return addChange(r.changelist, template, name) }
go
func (r *repository) AddDelegationRoleAndKeys(name data.RoleName, delegationKeys []data.PublicKey) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Adding delegation "%s" with threshold %d, and %d keys\n`, name, notary.MinThreshold, len(delegationKeys)) // Defaulting to threshold of 1, since we don't allow for larger thresholds at the moment. tdJSON, err := json.Marshal(&changelist.TUFDelegation{ NewThreshold: notary.MinThreshold, AddKeys: data.KeyList(delegationKeys), }) if err != nil { return err } template := newCreateDelegationChange(name, tdJSON) return addChange(r.changelist, template, name) }
[ "func", "(", "r", "*", "repository", ")", "AddDelegationRoleAndKeys", "(", "name", "data", ".", "RoleName", ",", "delegationKeys", "[", "]", "data", ".", "PublicKey", ")", "error", "{", "if", "!", "data", ".", "IsDelegation", "(", "name", ")", "{", "return", "data", ".", "ErrInvalidRole", "{", "Role", ":", "name", ",", "Reason", ":", "\"", "\"", "}", "\n", "}", "\n\n", "logrus", ".", "Debugf", "(", "`Adding delegation \"%s\" with threshold %d, and %d keys\\n`", ",", "name", ",", "notary", ".", "MinThreshold", ",", "len", "(", "delegationKeys", ")", ")", "\n\n", "// Defaulting to threshold of 1, since we don't allow for larger thresholds at the moment.", "tdJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "&", "changelist", ".", "TUFDelegation", "{", "NewThreshold", ":", "notary", ".", "MinThreshold", ",", "AddKeys", ":", "data", ".", "KeyList", "(", "delegationKeys", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "template", ":=", "newCreateDelegationChange", "(", "name", ",", "tdJSON", ")", "\n", "return", "addChange", "(", "r", ".", "changelist", ",", "template", ",", "name", ")", "\n", "}" ]
// AddDelegationRoleAndKeys creates a changelist entry to add provided delegation public keys. // This method is the simplest way to create a new delegation, because the delegation must have at least // one key upon creation to be valid since we will reject the changelist while validating the threshold.
[ "AddDelegationRoleAndKeys", "creates", "a", "changelist", "entry", "to", "add", "provided", "delegation", "public", "keys", ".", "This", "method", "is", "the", "simplest", "way", "to", "create", "a", "new", "delegation", "because", "the", "delegation", "must", "have", "at", "least", "one", "key", "upon", "creation", "to", "be", "valid", "since", "we", "will", "reject", "the", "changelist", "while", "validating", "the", "threshold", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L35-L55
train
theupdateframework/notary
client/delegations.go
AddDelegationPaths
func (r *repository) AddDelegationPaths(name data.RoleName, paths []string) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Adding %s paths to delegation %s\n`, paths, name) tdJSON, err := json.Marshal(&changelist.TUFDelegation{ AddPaths: paths, }) if err != nil { return err } template := newCreateDelegationChange(name, tdJSON) return addChange(r.changelist, template, name) }
go
func (r *repository) AddDelegationPaths(name data.RoleName, paths []string) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Adding %s paths to delegation %s\n`, paths, name) tdJSON, err := json.Marshal(&changelist.TUFDelegation{ AddPaths: paths, }) if err != nil { return err } template := newCreateDelegationChange(name, tdJSON) return addChange(r.changelist, template, name) }
[ "func", "(", "r", "*", "repository", ")", "AddDelegationPaths", "(", "name", "data", ".", "RoleName", ",", "paths", "[", "]", "string", ")", "error", "{", "if", "!", "data", ".", "IsDelegation", "(", "name", ")", "{", "return", "data", ".", "ErrInvalidRole", "{", "Role", ":", "name", ",", "Reason", ":", "\"", "\"", "}", "\n", "}", "\n\n", "logrus", ".", "Debugf", "(", "`Adding %s paths to delegation %s\\n`", ",", "paths", ",", "name", ")", "\n\n", "tdJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "&", "changelist", ".", "TUFDelegation", "{", "AddPaths", ":", "paths", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "template", ":=", "newCreateDelegationChange", "(", "name", ",", "tdJSON", ")", "\n", "return", "addChange", "(", "r", ".", "changelist", ",", "template", ",", "name", ")", "\n", "}" ]
// AddDelegationPaths creates a changelist entry to add provided paths to an existing delegation. // This method cannot create a new delegation itself because the role must meet the key threshold upon creation.
[ "AddDelegationPaths", "creates", "a", "changelist", "entry", "to", "add", "provided", "paths", "to", "an", "existing", "delegation", ".", "This", "method", "cannot", "create", "a", "new", "delegation", "itself", "because", "the", "role", "must", "meet", "the", "key", "threshold", "upon", "creation", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L59-L76
train
theupdateframework/notary
client/delegations.go
RemoveDelegationRole
func (r *repository) RemoveDelegationRole(name data.RoleName) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Removing delegation "%s"\n`, name) template := newDeleteDelegationChange(name, nil) return addChange(r.changelist, template, name) }
go
func (r *repository) RemoveDelegationRole(name data.RoleName) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Removing delegation "%s"\n`, name) template := newDeleteDelegationChange(name, nil) return addChange(r.changelist, template, name) }
[ "func", "(", "r", "*", "repository", ")", "RemoveDelegationRole", "(", "name", "data", ".", "RoleName", ")", "error", "{", "if", "!", "data", ".", "IsDelegation", "(", "name", ")", "{", "return", "data", ".", "ErrInvalidRole", "{", "Role", ":", "name", ",", "Reason", ":", "\"", "\"", "}", "\n", "}", "\n\n", "logrus", ".", "Debugf", "(", "`Removing delegation \"%s\"\\n`", ",", "name", ")", "\n\n", "template", ":=", "newDeleteDelegationChange", "(", "name", ",", "nil", ")", "\n", "return", "addChange", "(", "r", ".", "changelist", ",", "template", ",", "name", ")", "\n", "}" ]
// RemoveDelegationRole creates a changelist to remove all paths and keys from a role, and delete the role in its entirety.
[ "RemoveDelegationRole", "creates", "a", "changelist", "to", "remove", "all", "paths", "and", "keys", "from", "a", "role", "and", "delete", "the", "role", "in", "its", "entirety", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L97-L107
train
theupdateframework/notary
client/delegations.go
RemoveDelegationPaths
func (r *repository) RemoveDelegationPaths(name data.RoleName, paths []string) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Removing %s paths from delegation "%s"\n`, paths, name) tdJSON, err := json.Marshal(&changelist.TUFDelegation{ RemovePaths: paths, }) if err != nil { return err } template := newUpdateDelegationChange(name, tdJSON) return addChange(r.changelist, template, name) }
go
func (r *repository) RemoveDelegationPaths(name data.RoleName, paths []string) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Removing %s paths from delegation "%s"\n`, paths, name) tdJSON, err := json.Marshal(&changelist.TUFDelegation{ RemovePaths: paths, }) if err != nil { return err } template := newUpdateDelegationChange(name, tdJSON) return addChange(r.changelist, template, name) }
[ "func", "(", "r", "*", "repository", ")", "RemoveDelegationPaths", "(", "name", "data", ".", "RoleName", ",", "paths", "[", "]", "string", ")", "error", "{", "if", "!", "data", ".", "IsDelegation", "(", "name", ")", "{", "return", "data", ".", "ErrInvalidRole", "{", "Role", ":", "name", ",", "Reason", ":", "\"", "\"", "}", "\n", "}", "\n\n", "logrus", ".", "Debugf", "(", "`Removing %s paths from delegation \"%s\"\\n`", ",", "paths", ",", "name", ")", "\n\n", "tdJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "&", "changelist", ".", "TUFDelegation", "{", "RemovePaths", ":", "paths", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "template", ":=", "newUpdateDelegationChange", "(", "name", ",", "tdJSON", ")", "\n", "return", "addChange", "(", "r", ".", "changelist", ",", "template", ",", "name", ")", "\n", "}" ]
// RemoveDelegationPaths creates a changelist entry to remove provided paths from an existing delegation.
[ "RemoveDelegationPaths", "creates", "a", "changelist", "entry", "to", "remove", "provided", "paths", "from", "an", "existing", "delegation", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L110-L127
train
theupdateframework/notary
client/delegations.go
RemoveDelegationKeys
func (r *repository) RemoveDelegationKeys(name data.RoleName, keyIDs []string) error { if !data.IsDelegation(name) && !data.IsWildDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Removing %s keys from delegation "%s"\n`, keyIDs, name) tdJSON, err := json.Marshal(&changelist.TUFDelegation{ RemoveKeys: keyIDs, }) if err != nil { return err } template := newUpdateDelegationChange(name, tdJSON) return addChange(r.changelist, template, name) }
go
func (r *repository) RemoveDelegationKeys(name data.RoleName, keyIDs []string) error { if !data.IsDelegation(name) && !data.IsWildDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Removing %s keys from delegation "%s"\n`, keyIDs, name) tdJSON, err := json.Marshal(&changelist.TUFDelegation{ RemoveKeys: keyIDs, }) if err != nil { return err } template := newUpdateDelegationChange(name, tdJSON) return addChange(r.changelist, template, name) }
[ "func", "(", "r", "*", "repository", ")", "RemoveDelegationKeys", "(", "name", "data", ".", "RoleName", ",", "keyIDs", "[", "]", "string", ")", "error", "{", "if", "!", "data", ".", "IsDelegation", "(", "name", ")", "&&", "!", "data", ".", "IsWildDelegation", "(", "name", ")", "{", "return", "data", ".", "ErrInvalidRole", "{", "Role", ":", "name", ",", "Reason", ":", "\"", "\"", "}", "\n", "}", "\n\n", "logrus", ".", "Debugf", "(", "`Removing %s keys from delegation \"%s\"\\n`", ",", "keyIDs", ",", "name", ")", "\n\n", "tdJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "&", "changelist", ".", "TUFDelegation", "{", "RemoveKeys", ":", "keyIDs", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "template", ":=", "newUpdateDelegationChange", "(", "name", ",", "tdJSON", ")", "\n", "return", "addChange", "(", "r", ".", "changelist", ",", "template", ",", "name", ")", "\n", "}" ]
// RemoveDelegationKeys creates a changelist entry to remove provided keys from an existing delegation. // When this changelist is applied, if the specified keys are the only keys left in the role, // the role itself will be deleted in its entirety. // It can also delete a key from all delegations under a parent using a name // with a wildcard at the end.
[ "RemoveDelegationKeys", "creates", "a", "changelist", "entry", "to", "remove", "provided", "keys", "from", "an", "existing", "delegation", ".", "When", "this", "changelist", "is", "applied", "if", "the", "specified", "keys", "are", "the", "only", "keys", "left", "in", "the", "role", "the", "role", "itself", "will", "be", "deleted", "in", "its", "entirety", ".", "It", "can", "also", "delete", "a", "key", "from", "all", "delegations", "under", "a", "parent", "using", "a", "name", "with", "a", "wildcard", "at", "the", "end", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L134-L151
train
theupdateframework/notary
client/delegations.go
ClearDelegationPaths
func (r *repository) ClearDelegationPaths(name data.RoleName) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Removing all paths from delegation "%s"\n`, name) tdJSON, err := json.Marshal(&changelist.TUFDelegation{ ClearAllPaths: true, }) if err != nil { return err } template := newUpdateDelegationChange(name, tdJSON) return addChange(r.changelist, template, name) }
go
func (r *repository) ClearDelegationPaths(name data.RoleName) error { if !data.IsDelegation(name) { return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"} } logrus.Debugf(`Removing all paths from delegation "%s"\n`, name) tdJSON, err := json.Marshal(&changelist.TUFDelegation{ ClearAllPaths: true, }) if err != nil { return err } template := newUpdateDelegationChange(name, tdJSON) return addChange(r.changelist, template, name) }
[ "func", "(", "r", "*", "repository", ")", "ClearDelegationPaths", "(", "name", "data", ".", "RoleName", ")", "error", "{", "if", "!", "data", ".", "IsDelegation", "(", "name", ")", "{", "return", "data", ".", "ErrInvalidRole", "{", "Role", ":", "name", ",", "Reason", ":", "\"", "\"", "}", "\n", "}", "\n\n", "logrus", ".", "Debugf", "(", "`Removing all paths from delegation \"%s\"\\n`", ",", "name", ")", "\n\n", "tdJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "&", "changelist", ".", "TUFDelegation", "{", "ClearAllPaths", ":", "true", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "template", ":=", "newUpdateDelegationChange", "(", "name", ",", "tdJSON", ")", "\n", "return", "addChange", "(", "r", ".", "changelist", ",", "template", ",", "name", ")", "\n", "}" ]
// ClearDelegationPaths creates a changelist entry to remove all paths from an existing delegation.
[ "ClearDelegationPaths", "creates", "a", "changelist", "entry", "to", "remove", "all", "paths", "from", "an", "existing", "delegation", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L154-L171
train
theupdateframework/notary
signer/client/signer_trust.go
Public
func (rs *RemoteSigner) Public() crypto.PublicKey { publicKey, err := x509.ParsePKIXPublicKey(rs.RemotePrivateKey.Public()) if err != nil { return nil } return publicKey }
go
func (rs *RemoteSigner) Public() crypto.PublicKey { publicKey, err := x509.ParsePKIXPublicKey(rs.RemotePrivateKey.Public()) if err != nil { return nil } return publicKey }
[ "func", "(", "rs", "*", "RemoteSigner", ")", "Public", "(", ")", "crypto", ".", "PublicKey", "{", "publicKey", ",", "err", ":=", "x509", ".", "ParsePKIXPublicKey", "(", "rs", ".", "RemotePrivateKey", ".", "Public", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "publicKey", "\n", "}" ]
// Public method of a crypto.Signer needs to return a crypto public key.
[ "Public", "method", "of", "a", "crypto", ".", "Signer", "needs", "to", "return", "a", "crypto", "public", "key", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L38-L45
train
theupdateframework/notary
signer/client/signer_trust.go
Sign
func (pk *RemotePrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) { keyID := pb.KeyID{ID: pk.ID()} sr := &pb.SignatureRequest{ Content: msg, KeyID: &keyID, } sig, err := pk.sClient.Sign(context.Background(), sr) if err != nil { return nil, err } return sig.Content, nil }
go
func (pk *RemotePrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) { keyID := pb.KeyID{ID: pk.ID()} sr := &pb.SignatureRequest{ Content: msg, KeyID: &keyID, } sig, err := pk.sClient.Sign(context.Background(), sr) if err != nil { return nil, err } return sig.Content, nil }
[ "func", "(", "pk", "*", "RemotePrivateKey", ")", "Sign", "(", "rand", "io", ".", "Reader", ",", "msg", "[", "]", "byte", ",", "opts", "crypto", ".", "SignerOpts", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "keyID", ":=", "pb", ".", "KeyID", "{", "ID", ":", "pk", ".", "ID", "(", ")", "}", "\n", "sr", ":=", "&", "pb", ".", "SignatureRequest", "{", "Content", ":", "msg", ",", "KeyID", ":", "&", "keyID", ",", "}", "\n", "sig", ",", "err", ":=", "pk", ".", "sClient", ".", "Sign", "(", "context", ".", "Background", "(", ")", ",", "sr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "sig", ".", "Content", ",", "nil", "\n", "}" ]
// Sign calls a remote service to sign a message.
[ "Sign", "calls", "a", "remote", "service", "to", "sign", "a", "message", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L62-L75
train
theupdateframework/notary
signer/client/signer_trust.go
SignatureAlgorithm
func (pk *RemotePrivateKey) SignatureAlgorithm() data.SigAlgorithm { switch pk.PublicKey.Algorithm() { case data.ECDSAKey, data.ECDSAx509Key: return data.ECDSASignature case data.RSAKey, data.RSAx509Key: return data.RSAPSSSignature case data.ED25519Key: return data.EDDSASignature default: // unknown return "" } }
go
func (pk *RemotePrivateKey) SignatureAlgorithm() data.SigAlgorithm { switch pk.PublicKey.Algorithm() { case data.ECDSAKey, data.ECDSAx509Key: return data.ECDSASignature case data.RSAKey, data.RSAx509Key: return data.RSAPSSSignature case data.ED25519Key: return data.EDDSASignature default: // unknown return "" } }
[ "func", "(", "pk", "*", "RemotePrivateKey", ")", "SignatureAlgorithm", "(", ")", "data", ".", "SigAlgorithm", "{", "switch", "pk", ".", "PublicKey", ".", "Algorithm", "(", ")", "{", "case", "data", ".", "ECDSAKey", ",", "data", ".", "ECDSAx509Key", ":", "return", "data", ".", "ECDSASignature", "\n", "case", "data", ".", "RSAKey", ",", "data", ".", "RSAx509Key", ":", "return", "data", ".", "RSAPSSSignature", "\n", "case", "data", ".", "ED25519Key", ":", "return", "data", ".", "EDDSASignature", "\n", "default", ":", "// unknown", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// SignatureAlgorithm returns the signing algorithm based on the type of // PublicKey algorithm.
[ "SignatureAlgorithm", "returns", "the", "signing", "algorithm", "based", "on", "the", "type", "of", "PublicKey", "algorithm", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L79-L90
train
theupdateframework/notary
signer/client/signer_trust.go
CheckHealth
func (trust *NotarySigner) CheckHealth(d time.Duration, serviceName string) error { switch serviceName { case notary.HealthCheckKeyManagement: return healthCheckKeyManagement(d, trust.healthClient) case notary.HealthCheckSigner: return healthCheckSigner(d, trust.healthClient) case notary.HealthCheckOverall: if err := healthCheckKeyManagement(d, trust.healthClient); err != nil { return err } return healthCheckSigner(d, trust.healthClient) default: return fmt.Errorf("Unknown grpc service %s", serviceName) } }
go
func (trust *NotarySigner) CheckHealth(d time.Duration, serviceName string) error { switch serviceName { case notary.HealthCheckKeyManagement: return healthCheckKeyManagement(d, trust.healthClient) case notary.HealthCheckSigner: return healthCheckSigner(d, trust.healthClient) case notary.HealthCheckOverall: if err := healthCheckKeyManagement(d, trust.healthClient); err != nil { return err } return healthCheckSigner(d, trust.healthClient) default: return fmt.Errorf("Unknown grpc service %s", serviceName) } }
[ "func", "(", "trust", "*", "NotarySigner", ")", "CheckHealth", "(", "d", "time", ".", "Duration", ",", "serviceName", "string", ")", "error", "{", "switch", "serviceName", "{", "case", "notary", ".", "HealthCheckKeyManagement", ":", "return", "healthCheckKeyManagement", "(", "d", ",", "trust", ".", "healthClient", ")", "\n", "case", "notary", ".", "HealthCheckSigner", ":", "return", "healthCheckSigner", "(", "d", ",", "trust", ".", "healthClient", ")", "\n", "case", "notary", ".", "HealthCheckOverall", ":", "if", "err", ":=", "healthCheckKeyManagement", "(", "d", ",", "trust", ".", "healthClient", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "healthCheckSigner", "(", "d", ",", "trust", ".", "healthClient", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "serviceName", ")", "\n", "}", "\n", "}" ]
// CheckHealth are used to probe whether the server is able to handle rpcs.
[ "CheckHealth", "are", "used", "to", "probe", "whether", "the", "server", "is", "able", "to", "handle", "rpcs", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L138-L152
train
theupdateframework/notary
signer/client/signer_trust.go
NewGRPCConnection
func NewGRPCConnection(hostname string, port string, tlsConfig *tls.Config) (*grpc.ClientConn, error) { var opts []grpc.DialOption netAddr := net.JoinHostPort(hostname, port) creds := credentials.NewTLS(tlsConfig) opts = append(opts, grpc.WithTransportCredentials(creds)) return grpc.Dial(netAddr, opts...) }
go
func NewGRPCConnection(hostname string, port string, tlsConfig *tls.Config) (*grpc.ClientConn, error) { var opts []grpc.DialOption netAddr := net.JoinHostPort(hostname, port) creds := credentials.NewTLS(tlsConfig) opts = append(opts, grpc.WithTransportCredentials(creds)) return grpc.Dial(netAddr, opts...) }
[ "func", "NewGRPCConnection", "(", "hostname", "string", ",", "port", "string", ",", "tlsConfig", "*", "tls", ".", "Config", ")", "(", "*", "grpc", ".", "ClientConn", ",", "error", ")", "{", "var", "opts", "[", "]", "grpc", ".", "DialOption", "\n", "netAddr", ":=", "net", ".", "JoinHostPort", "(", "hostname", ",", "port", ")", "\n", "creds", ":=", "credentials", ".", "NewTLS", "(", "tlsConfig", ")", "\n", "opts", "=", "append", "(", "opts", ",", "grpc", ".", "WithTransportCredentials", "(", "creds", ")", ")", "\n", "return", "grpc", ".", "Dial", "(", "netAddr", ",", "opts", "...", ")", "\n", "}" ]
// NewGRPCConnection is a convenience method that returns GRPC Client Connection given a hostname, endpoint, and TLS options
[ "NewGRPCConnection", "is", "a", "convenience", "method", "that", "returns", "GRPC", "Client", "Connection", "given", "a", "hostname", "endpoint", "and", "TLS", "options" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L155-L161
train
theupdateframework/notary
signer/client/signer_trust.go
NewNotarySigner
func NewNotarySigner(conn *grpc.ClientConn) *NotarySigner { kmClient := pb.NewKeyManagementClient(conn) sClient := pb.NewSignerClient(conn) hc := healthpb.NewHealthClient(conn) return &NotarySigner{ kmClient: kmClient, sClient: sClient, healthClient: hc, } }
go
func NewNotarySigner(conn *grpc.ClientConn) *NotarySigner { kmClient := pb.NewKeyManagementClient(conn) sClient := pb.NewSignerClient(conn) hc := healthpb.NewHealthClient(conn) return &NotarySigner{ kmClient: kmClient, sClient: sClient, healthClient: hc, } }
[ "func", "NewNotarySigner", "(", "conn", "*", "grpc", ".", "ClientConn", ")", "*", "NotarySigner", "{", "kmClient", ":=", "pb", ".", "NewKeyManagementClient", "(", "conn", ")", "\n", "sClient", ":=", "pb", ".", "NewSignerClient", "(", "conn", ")", "\n", "hc", ":=", "healthpb", ".", "NewHealthClient", "(", "conn", ")", "\n\n", "return", "&", "NotarySigner", "{", "kmClient", ":", "kmClient", ",", "sClient", ":", "sClient", ",", "healthClient", ":", "hc", ",", "}", "\n", "}" ]
// NewNotarySigner is a convenience method that returns NotarySigner given a GRPC connection
[ "NewNotarySigner", "is", "a", "convenience", "method", "that", "returns", "NotarySigner", "given", "a", "GRPC", "connection" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L164-L174
train
theupdateframework/notary
signer/client/signer_trust.go
Create
func (trust *NotarySigner) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) { publicKey, err := trust.kmClient.CreateKey(context.Background(), &pb.CreateKeyRequest{Algorithm: algorithm, Role: role.String(), Gun: gun.String()}) if err != nil { return nil, err } public := data.NewPublicKey(publicKey.KeyInfo.Algorithm.Algorithm, publicKey.PublicKey) return public, nil }
go
func (trust *NotarySigner) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) { publicKey, err := trust.kmClient.CreateKey(context.Background(), &pb.CreateKeyRequest{Algorithm: algorithm, Role: role.String(), Gun: gun.String()}) if err != nil { return nil, err } public := data.NewPublicKey(publicKey.KeyInfo.Algorithm.Algorithm, publicKey.PublicKey) return public, nil }
[ "func", "(", "trust", "*", "NotarySigner", ")", "Create", "(", "role", "data", ".", "RoleName", ",", "gun", "data", ".", "GUN", ",", "algorithm", "string", ")", "(", "data", ".", "PublicKey", ",", "error", ")", "{", "publicKey", ",", "err", ":=", "trust", ".", "kmClient", ".", "CreateKey", "(", "context", ".", "Background", "(", ")", ",", "&", "pb", ".", "CreateKeyRequest", "{", "Algorithm", ":", "algorithm", ",", "Role", ":", "role", ".", "String", "(", ")", ",", "Gun", ":", "gun", ".", "String", "(", ")", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "public", ":=", "data", ".", "NewPublicKey", "(", "publicKey", ".", "KeyInfo", ".", "Algorithm", ".", "Algorithm", ",", "publicKey", ".", "PublicKey", ")", "\n", "return", "public", ",", "nil", "\n", "}" ]
// Create creates a remote key and returns the PublicKey associated with the remote private key
[ "Create", "creates", "a", "remote", "key", "and", "returns", "the", "PublicKey", "associated", "with", "the", "remote", "private", "key" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L177-L185
train
theupdateframework/notary
signer/client/signer_trust.go
AddKey
func (trust *NotarySigner) AddKey(role data.RoleName, gun data.GUN, k data.PrivateKey) error { return errors.New("Adding a key to NotarySigner is not supported") }
go
func (trust *NotarySigner) AddKey(role data.RoleName, gun data.GUN, k data.PrivateKey) error { return errors.New("Adding a key to NotarySigner is not supported") }
[ "func", "(", "trust", "*", "NotarySigner", ")", "AddKey", "(", "role", "data", ".", "RoleName", ",", "gun", "data", ".", "GUN", ",", "k", "data", ".", "PrivateKey", ")", "error", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// AddKey adds a key
[ "AddKey", "adds", "a", "key" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L188-L190
train
theupdateframework/notary
signer/client/signer_trust.go
RemoveKey
func (trust *NotarySigner) RemoveKey(keyid string) error { _, err := trust.kmClient.DeleteKey(context.Background(), &pb.KeyID{ID: keyid}) return err }
go
func (trust *NotarySigner) RemoveKey(keyid string) error { _, err := trust.kmClient.DeleteKey(context.Background(), &pb.KeyID{ID: keyid}) return err }
[ "func", "(", "trust", "*", "NotarySigner", ")", "RemoveKey", "(", "keyid", "string", ")", "error", "{", "_", ",", "err", ":=", "trust", ".", "kmClient", ".", "DeleteKey", "(", "context", ".", "Background", "(", ")", ",", "&", "pb", ".", "KeyID", "{", "ID", ":", "keyid", "}", ")", "\n", "return", "err", "\n", "}" ]
// RemoveKey deletes a key by ID - if the key didn't exist, succeed anyway
[ "RemoveKey", "deletes", "a", "key", "by", "ID", "-", "if", "the", "key", "didn", "t", "exist", "succeed", "anyway" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L193-L196
train
theupdateframework/notary
signer/client/signer_trust.go
GetKey
func (trust *NotarySigner) GetKey(keyid string) data.PublicKey { pubKey, _, err := trust.getKeyInfo(keyid) if err != nil { return nil } return pubKey }
go
func (trust *NotarySigner) GetKey(keyid string) data.PublicKey { pubKey, _, err := trust.getKeyInfo(keyid) if err != nil { return nil } return pubKey }
[ "func", "(", "trust", "*", "NotarySigner", ")", "GetKey", "(", "keyid", "string", ")", "data", ".", "PublicKey", "{", "pubKey", ",", "_", ",", "err", ":=", "trust", ".", "getKeyInfo", "(", "keyid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "pubKey", "\n", "}" ]
// GetKey retrieves a key by ID - returns nil if the key doesn't exist
[ "GetKey", "retrieves", "a", "key", "by", "ID", "-", "returns", "nil", "if", "the", "key", "doesn", "t", "exist" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L199-L205
train
theupdateframework/notary
signer/client/signer_trust.go
GetPrivateKey
func (trust *NotarySigner) GetPrivateKey(keyid string) (data.PrivateKey, data.RoleName, error) { pubKey, role, err := trust.getKeyInfo(keyid) if err != nil { return nil, "", err } return NewRemotePrivateKey(pubKey, trust.sClient), role, nil }
go
func (trust *NotarySigner) GetPrivateKey(keyid string) (data.PrivateKey, data.RoleName, error) { pubKey, role, err := trust.getKeyInfo(keyid) if err != nil { return nil, "", err } return NewRemotePrivateKey(pubKey, trust.sClient), role, nil }
[ "func", "(", "trust", "*", "NotarySigner", ")", "GetPrivateKey", "(", "keyid", "string", ")", "(", "data", ".", "PrivateKey", ",", "data", ".", "RoleName", ",", "error", ")", "{", "pubKey", ",", "role", ",", "err", ":=", "trust", ".", "getKeyInfo", "(", "keyid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "NewRemotePrivateKey", "(", "pubKey", ",", "trust", ".", "sClient", ")", ",", "role", ",", "nil", "\n", "}" ]
// GetPrivateKey retrieves by ID an object that can be used to sign, but that does // not contain any private bytes. If the key doesn't exist, returns an error.
[ "GetPrivateKey", "retrieves", "by", "ID", "an", "object", "that", "can", "be", "used", "to", "sign", "but", "that", "does", "not", "contain", "any", "private", "bytes", ".", "If", "the", "key", "doesn", "t", "exist", "returns", "an", "error", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L217-L223
train
theupdateframework/notary
trustmanager/keystore.go
NewKeyFileStore
func NewKeyFileStore(baseDir string, p notary.PassRetriever) (*GenericKeyStore, error) { fileStore, err := store.NewPrivateKeyFileStorage(baseDir, notary.KeyExtension) if err != nil { return nil, err } return NewGenericKeyStore(fileStore, p), nil }
go
func NewKeyFileStore(baseDir string, p notary.PassRetriever) (*GenericKeyStore, error) { fileStore, err := store.NewPrivateKeyFileStorage(baseDir, notary.KeyExtension) if err != nil { return nil, err } return NewGenericKeyStore(fileStore, p), nil }
[ "func", "NewKeyFileStore", "(", "baseDir", "string", ",", "p", "notary", ".", "PassRetriever", ")", "(", "*", "GenericKeyStore", ",", "error", ")", "{", "fileStore", ",", "err", ":=", "store", ".", "NewPrivateKeyFileStorage", "(", "baseDir", ",", "notary", ".", "KeyExtension", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "NewGenericKeyStore", "(", "fileStore", ",", "p", ")", ",", "nil", "\n", "}" ]
// NewKeyFileStore returns a new KeyFileStore creating a private directory to // hold the keys.
[ "NewKeyFileStore", "returns", "a", "new", "KeyFileStore", "creating", "a", "private", "directory", "to", "hold", "the", "keys", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L35-L41
train
theupdateframework/notary
trustmanager/keystore.go
NewKeyMemoryStore
func NewKeyMemoryStore(p notary.PassRetriever) *GenericKeyStore { memStore := store.NewMemoryStore(nil) return NewGenericKeyStore(memStore, p) }
go
func NewKeyMemoryStore(p notary.PassRetriever) *GenericKeyStore { memStore := store.NewMemoryStore(nil) return NewGenericKeyStore(memStore, p) }
[ "func", "NewKeyMemoryStore", "(", "p", "notary", ".", "PassRetriever", ")", "*", "GenericKeyStore", "{", "memStore", ":=", "store", ".", "NewMemoryStore", "(", "nil", ")", "\n", "return", "NewGenericKeyStore", "(", "memStore", ",", "p", ")", "\n", "}" ]
// NewKeyMemoryStore returns a new KeyMemoryStore which holds keys in memory
[ "NewKeyMemoryStore", "returns", "a", "new", "KeyMemoryStore", "which", "holds", "keys", "in", "memory" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L44-L47
train
theupdateframework/notary
trustmanager/keystore.go
GetKeyInfo
func (s *GenericKeyStore) GetKeyInfo(keyID string) (KeyInfo, error) { if info, ok := s.keyInfoMap[keyID]; ok { return info, nil } return KeyInfo{}, fmt.Errorf("Could not find info for keyID %s", keyID) }
go
func (s *GenericKeyStore) GetKeyInfo(keyID string) (KeyInfo, error) { if info, ok := s.keyInfoMap[keyID]; ok { return info, nil } return KeyInfo{}, fmt.Errorf("Could not find info for keyID %s", keyID) }
[ "func", "(", "s", "*", "GenericKeyStore", ")", "GetKeyInfo", "(", "keyID", "string", ")", "(", "KeyInfo", ",", "error", ")", "{", "if", "info", ",", "ok", ":=", "s", ".", "keyInfoMap", "[", "keyID", "]", ";", "ok", "{", "return", "info", ",", "nil", "\n", "}", "\n", "return", "KeyInfo", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyID", ")", "\n", "}" ]
// GetKeyInfo returns the corresponding gun and role key info for a keyID
[ "GetKeyInfo", "returns", "the", "corresponding", "gun", "and", "role", "key", "info", "for", "a", "keyID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L85-L90
train
theupdateframework/notary
trustmanager/keystore.go
AddKey
func (s *GenericKeyStore) AddKey(keyInfo KeyInfo, privKey data.PrivateKey) error { var ( chosenPassphrase string giveup bool err error pemPrivKey []byte ) s.Lock() defer s.Unlock() if keyInfo.Role == data.CanonicalRootRole || data.IsDelegation(keyInfo.Role) || !data.ValidRole(keyInfo.Role) { keyInfo.Gun = "" } keyID := privKey.ID() for attempts := 0; ; attempts++ { chosenPassphrase, giveup, err = s.PassRetriever(keyID, keyInfo.Role.String(), true, attempts) if err == nil { break } if giveup || attempts > 10 { return ErrAttemptsExceeded{} } } pemPrivKey, err = utils.ConvertPrivateKeyToPKCS8(privKey, keyInfo.Role, keyInfo.Gun, chosenPassphrase) if err != nil { return err } s.cachedKeys[keyID] = &cachedKey{role: keyInfo.Role, key: privKey} err = s.store.Set(keyID, pemPrivKey) if err != nil { return err } s.keyInfoMap[privKey.ID()] = keyInfo return nil }
go
func (s *GenericKeyStore) AddKey(keyInfo KeyInfo, privKey data.PrivateKey) error { var ( chosenPassphrase string giveup bool err error pemPrivKey []byte ) s.Lock() defer s.Unlock() if keyInfo.Role == data.CanonicalRootRole || data.IsDelegation(keyInfo.Role) || !data.ValidRole(keyInfo.Role) { keyInfo.Gun = "" } keyID := privKey.ID() for attempts := 0; ; attempts++ { chosenPassphrase, giveup, err = s.PassRetriever(keyID, keyInfo.Role.String(), true, attempts) if err == nil { break } if giveup || attempts > 10 { return ErrAttemptsExceeded{} } } pemPrivKey, err = utils.ConvertPrivateKeyToPKCS8(privKey, keyInfo.Role, keyInfo.Gun, chosenPassphrase) if err != nil { return err } s.cachedKeys[keyID] = &cachedKey{role: keyInfo.Role, key: privKey} err = s.store.Set(keyID, pemPrivKey) if err != nil { return err } s.keyInfoMap[privKey.ID()] = keyInfo return nil }
[ "func", "(", "s", "*", "GenericKeyStore", ")", "AddKey", "(", "keyInfo", "KeyInfo", ",", "privKey", "data", ".", "PrivateKey", ")", "error", "{", "var", "(", "chosenPassphrase", "string", "\n", "giveup", "bool", "\n", "err", "error", "\n", "pemPrivKey", "[", "]", "byte", "\n", ")", "\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "if", "keyInfo", ".", "Role", "==", "data", ".", "CanonicalRootRole", "||", "data", ".", "IsDelegation", "(", "keyInfo", ".", "Role", ")", "||", "!", "data", ".", "ValidRole", "(", "keyInfo", ".", "Role", ")", "{", "keyInfo", ".", "Gun", "=", "\"", "\"", "\n", "}", "\n", "keyID", ":=", "privKey", ".", "ID", "(", ")", "\n", "for", "attempts", ":=", "0", ";", ";", "attempts", "++", "{", "chosenPassphrase", ",", "giveup", ",", "err", "=", "s", ".", "PassRetriever", "(", "keyID", ",", "keyInfo", ".", "Role", ".", "String", "(", ")", ",", "true", ",", "attempts", ")", "\n", "if", "err", "==", "nil", "{", "break", "\n", "}", "\n", "if", "giveup", "||", "attempts", ">", "10", "{", "return", "ErrAttemptsExceeded", "{", "}", "\n", "}", "\n", "}", "\n\n", "pemPrivKey", ",", "err", "=", "utils", ".", "ConvertPrivateKeyToPKCS8", "(", "privKey", ",", "keyInfo", ".", "Role", ",", "keyInfo", ".", "Gun", ",", "chosenPassphrase", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "cachedKeys", "[", "keyID", "]", "=", "&", "cachedKey", "{", "role", ":", "keyInfo", ".", "Role", ",", "key", ":", "privKey", "}", "\n", "err", "=", "s", ".", "store", ".", "Set", "(", "keyID", ",", "pemPrivKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "s", ".", "keyInfoMap", "[", "privKey", ".", "ID", "(", ")", "]", "=", "keyInfo", "\n", "return", "nil", "\n", "}" ]
// AddKey stores the contents of a PEM-encoded private key as a PEM block
[ "AddKey", "stores", "the", "contents", "of", "a", "PEM", "-", "encoded", "private", "key", "as", "a", "PEM", "block" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L93-L129
train
theupdateframework/notary
trustmanager/keystore.go
copyKeyInfoMap
func copyKeyInfoMap(keyInfoMap map[string]KeyInfo) map[string]KeyInfo { copyMap := make(map[string]KeyInfo) for keyID, keyInfo := range keyInfoMap { copyMap[keyID] = KeyInfo{Role: keyInfo.Role, Gun: keyInfo.Gun} } return copyMap }
go
func copyKeyInfoMap(keyInfoMap map[string]KeyInfo) map[string]KeyInfo { copyMap := make(map[string]KeyInfo) for keyID, keyInfo := range keyInfoMap { copyMap[keyID] = KeyInfo{Role: keyInfo.Role, Gun: keyInfo.Gun} } return copyMap }
[ "func", "copyKeyInfoMap", "(", "keyInfoMap", "map", "[", "string", "]", "KeyInfo", ")", "map", "[", "string", "]", "KeyInfo", "{", "copyMap", ":=", "make", "(", "map", "[", "string", "]", "KeyInfo", ")", "\n", "for", "keyID", ",", "keyInfo", ":=", "range", "keyInfoMap", "{", "copyMap", "[", "keyID", "]", "=", "KeyInfo", "{", "Role", ":", "keyInfo", ".", "Role", ",", "Gun", ":", "keyInfo", ".", "Gun", "}", "\n", "}", "\n", "return", "copyMap", "\n", "}" ]
// copyKeyInfoMap returns a deep copy of the passed-in keyInfoMap
[ "copyKeyInfoMap", "returns", "a", "deep", "copy", "of", "the", "passed", "-", "in", "keyInfoMap" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L190-L196
train
theupdateframework/notary
trustmanager/keystore.go
KeyInfoFromPEM
func KeyInfoFromPEM(pemBytes []byte, filename string) (string, KeyInfo, error) { var keyID string keyID = filepath.Base(filename) role, gun, err := utils.ExtractPrivateKeyAttributes(pemBytes) if err != nil { return "", KeyInfo{}, err } return keyID, KeyInfo{Gun: gun, Role: role}, nil }
go
func KeyInfoFromPEM(pemBytes []byte, filename string) (string, KeyInfo, error) { var keyID string keyID = filepath.Base(filename) role, gun, err := utils.ExtractPrivateKeyAttributes(pemBytes) if err != nil { return "", KeyInfo{}, err } return keyID, KeyInfo{Gun: gun, Role: role}, nil }
[ "func", "KeyInfoFromPEM", "(", "pemBytes", "[", "]", "byte", ",", "filename", "string", ")", "(", "string", ",", "KeyInfo", ",", "error", ")", "{", "var", "keyID", "string", "\n", "keyID", "=", "filepath", ".", "Base", "(", "filename", ")", "\n", "role", ",", "gun", ",", "err", ":=", "utils", ".", "ExtractPrivateKeyAttributes", "(", "pemBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "KeyInfo", "{", "}", ",", "err", "\n", "}", "\n", "return", "keyID", ",", "KeyInfo", "{", "Gun", ":", "gun", ",", "Role", ":", "role", "}", ",", "nil", "\n", "}" ]
// KeyInfoFromPEM attempts to get a keyID and KeyInfo from the filename and PEM bytes of a key
[ "KeyInfoFromPEM", "attempts", "to", "get", "a", "keyID", "and", "KeyInfo", "from", "the", "filename", "and", "PEM", "bytes", "of", "a", "key" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L199-L207
train
theupdateframework/notary
trustmanager/keystore.go
GetPasswdDecryptBytes
func GetPasswdDecryptBytes(passphraseRetriever notary.PassRetriever, pemBytes []byte, name, alias string) (data.PrivateKey, string, error) { var ( passwd string privKey data.PrivateKey ) for attempts := 0; ; attempts++ { var ( giveup bool err error ) if attempts > 10 { return nil, "", ErrAttemptsExceeded{} } passwd, giveup, err = passphraseRetriever(name, alias, false, attempts) // Check if the passphrase retriever got an error or if it is telling us to give up if giveup || err != nil { return nil, "", ErrPasswordInvalid{} } // Try to convert PEM encoded bytes back to a PrivateKey using the passphrase privKey, err = utils.ParsePEMPrivateKey(pemBytes, passwd) if err == nil { // We managed to parse the PrivateKey. We've succeeded! break } } return privKey, passwd, nil }
go
func GetPasswdDecryptBytes(passphraseRetriever notary.PassRetriever, pemBytes []byte, name, alias string) (data.PrivateKey, string, error) { var ( passwd string privKey data.PrivateKey ) for attempts := 0; ; attempts++ { var ( giveup bool err error ) if attempts > 10 { return nil, "", ErrAttemptsExceeded{} } passwd, giveup, err = passphraseRetriever(name, alias, false, attempts) // Check if the passphrase retriever got an error or if it is telling us to give up if giveup || err != nil { return nil, "", ErrPasswordInvalid{} } // Try to convert PEM encoded bytes back to a PrivateKey using the passphrase privKey, err = utils.ParsePEMPrivateKey(pemBytes, passwd) if err == nil { // We managed to parse the PrivateKey. We've succeeded! break } } return privKey, passwd, nil }
[ "func", "GetPasswdDecryptBytes", "(", "passphraseRetriever", "notary", ".", "PassRetriever", ",", "pemBytes", "[", "]", "byte", ",", "name", ",", "alias", "string", ")", "(", "data", ".", "PrivateKey", ",", "string", ",", "error", ")", "{", "var", "(", "passwd", "string", "\n", "privKey", "data", ".", "PrivateKey", "\n", ")", "\n", "for", "attempts", ":=", "0", ";", ";", "attempts", "++", "{", "var", "(", "giveup", "bool", "\n", "err", "error", "\n", ")", "\n", "if", "attempts", ">", "10", "{", "return", "nil", ",", "\"", "\"", ",", "ErrAttemptsExceeded", "{", "}", "\n", "}", "\n", "passwd", ",", "giveup", ",", "err", "=", "passphraseRetriever", "(", "name", ",", "alias", ",", "false", ",", "attempts", ")", "\n", "// Check if the passphrase retriever got an error or if it is telling us to give up", "if", "giveup", "||", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "ErrPasswordInvalid", "{", "}", "\n", "}", "\n\n", "// Try to convert PEM encoded bytes back to a PrivateKey using the passphrase", "privKey", ",", "err", "=", "utils", ".", "ParsePEMPrivateKey", "(", "pemBytes", ",", "passwd", ")", "\n", "if", "err", "==", "nil", "{", "// We managed to parse the PrivateKey. We've succeeded!", "break", "\n", "}", "\n", "}", "\n", "return", "privKey", ",", "passwd", ",", "nil", "\n", "}" ]
// GetPasswdDecryptBytes gets the password to decrypt the given pem bytes. // Returns the password and private key
[ "GetPasswdDecryptBytes", "gets", "the", "password", "to", "decrypt", "the", "given", "pem", "bytes", ".", "Returns", "the", "password", "and", "private", "key" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L235-L262
train
theupdateframework/notary
signer/keydbstore/sql_keydbstore.go
NewSQLKeyDBStore
func NewSQLKeyDBStore(passphraseRetriever notary.PassRetriever, defaultPassAlias string, dbDialect string, dbArgs ...interface{}) (*SQLKeyDBStore, error) { db, err := gorm.Open(dbDialect, dbArgs...) if err != nil { return nil, err } return &SQLKeyDBStore{ db: *db, dbType: dbDialect, defaultPassAlias: defaultPassAlias, retriever: passphraseRetriever, nowFunc: time.Now, }, nil }
go
func NewSQLKeyDBStore(passphraseRetriever notary.PassRetriever, defaultPassAlias string, dbDialect string, dbArgs ...interface{}) (*SQLKeyDBStore, error) { db, err := gorm.Open(dbDialect, dbArgs...) if err != nil { return nil, err } return &SQLKeyDBStore{ db: *db, dbType: dbDialect, defaultPassAlias: defaultPassAlias, retriever: passphraseRetriever, nowFunc: time.Now, }, nil }
[ "func", "NewSQLKeyDBStore", "(", "passphraseRetriever", "notary", ".", "PassRetriever", ",", "defaultPassAlias", "string", ",", "dbDialect", "string", ",", "dbArgs", "...", "interface", "{", "}", ")", "(", "*", "SQLKeyDBStore", ",", "error", ")", "{", "db", ",", "err", ":=", "gorm", ".", "Open", "(", "dbDialect", ",", "dbArgs", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "SQLKeyDBStore", "{", "db", ":", "*", "db", ",", "dbType", ":", "dbDialect", ",", "defaultPassAlias", ":", "defaultPassAlias", ",", "retriever", ":", "passphraseRetriever", ",", "nowFunc", ":", "time", ".", "Now", ",", "}", ",", "nil", "\n", "}" ]
// NewSQLKeyDBStore returns a new SQLKeyDBStore backed by a SQL database
[ "NewSQLKeyDBStore", "returns", "a", "new", "SQLKeyDBStore", "backed", "by", "a", "SQL", "database" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/sql_keydbstore.go#L50-L65
train
theupdateframework/notary
signer/keydbstore/sql_keydbstore.go
GetPrivateKey
func (s *SQLKeyDBStore) GetPrivateKey(keyID string) (data.PrivateKey, data.RoleName, error) { // Retrieve the GORM private key from the database dbPrivateKey, decryptedPrivKey, err := s.getKey(keyID, true) if err != nil { return nil, "", err } pubKey := data.NewPublicKey(dbPrivateKey.Algorithm, []byte(dbPrivateKey.Public)) // Create a new PrivateKey with unencrypted bytes privKey, err := data.NewPrivateKey(pubKey, []byte(decryptedPrivKey)) if err != nil { return nil, "", err } return activatingPrivateKey{PrivateKey: privKey, activationFunc: s.markActive}, data.RoleName(dbPrivateKey.Role), nil }
go
func (s *SQLKeyDBStore) GetPrivateKey(keyID string) (data.PrivateKey, data.RoleName, error) { // Retrieve the GORM private key from the database dbPrivateKey, decryptedPrivKey, err := s.getKey(keyID, true) if err != nil { return nil, "", err } pubKey := data.NewPublicKey(dbPrivateKey.Algorithm, []byte(dbPrivateKey.Public)) // Create a new PrivateKey with unencrypted bytes privKey, err := data.NewPrivateKey(pubKey, []byte(decryptedPrivKey)) if err != nil { return nil, "", err } return activatingPrivateKey{PrivateKey: privKey, activationFunc: s.markActive}, data.RoleName(dbPrivateKey.Role), nil }
[ "func", "(", "s", "*", "SQLKeyDBStore", ")", "GetPrivateKey", "(", "keyID", "string", ")", "(", "data", ".", "PrivateKey", ",", "data", ".", "RoleName", ",", "error", ")", "{", "// Retrieve the GORM private key from the database", "dbPrivateKey", ",", "decryptedPrivKey", ",", "err", ":=", "s", ".", "getKey", "(", "keyID", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "pubKey", ":=", "data", ".", "NewPublicKey", "(", "dbPrivateKey", ".", "Algorithm", ",", "[", "]", "byte", "(", "dbPrivateKey", ".", "Public", ")", ")", "\n", "// Create a new PrivateKey with unencrypted bytes", "privKey", ",", "err", ":=", "data", ".", "NewPrivateKey", "(", "pubKey", ",", "[", "]", "byte", "(", "decryptedPrivKey", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "activatingPrivateKey", "{", "PrivateKey", ":", "privKey", ",", "activationFunc", ":", "s", ".", "markActive", "}", ",", "data", ".", "RoleName", "(", "dbPrivateKey", ".", "Role", ")", ",", "nil", "\n", "}" ]
// GetPrivateKey returns the PrivateKey given a KeyID
[ "GetPrivateKey", "returns", "the", "PrivateKey", "given", "a", "KeyID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/sql_keydbstore.go#L131-L146
train
theupdateframework/notary
signer/keydbstore/sql_keydbstore.go
GetKey
func (s *SQLKeyDBStore) GetKey(keyID string) data.PublicKey { privKey, _, err := s.getKey(keyID, false) if err != nil { return nil } return data.NewPublicKey(privKey.Algorithm, []byte(privKey.Public)) }
go
func (s *SQLKeyDBStore) GetKey(keyID string) data.PublicKey { privKey, _, err := s.getKey(keyID, false) if err != nil { return nil } return data.NewPublicKey(privKey.Algorithm, []byte(privKey.Public)) }
[ "func", "(", "s", "*", "SQLKeyDBStore", ")", "GetKey", "(", "keyID", "string", ")", "data", ".", "PublicKey", "{", "privKey", ",", "_", ",", "err", ":=", "s", ".", "getKey", "(", "keyID", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "data", ".", "NewPublicKey", "(", "privKey", ".", "Algorithm", ",", "[", "]", "byte", "(", "privKey", ".", "Public", ")", ")", "\n", "}" ]
// GetKey performs the same get as GetPrivateKey, but does not mark the as active and only returns the public bytes
[ "GetKey", "performs", "the", "same", "get", "as", "GetPrivateKey", "but", "does", "not", "mark", "the", "as", "active", "and", "only", "returns", "the", "public", "bytes" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/sql_keydbstore.go#L223-L229
train
theupdateframework/notary
signer/keydbstore/sql_keydbstore.go
HealthCheck
func (s *SQLKeyDBStore) HealthCheck() error { dbPrivateKey := GormPrivateKey{} tableOk := s.db.HasTable(&dbPrivateKey) switch { case s.db.Error != nil: return s.db.Error case !tableOk: return fmt.Errorf( "Cannot access table: %s", dbPrivateKey.TableName()) } return nil }
go
func (s *SQLKeyDBStore) HealthCheck() error { dbPrivateKey := GormPrivateKey{} tableOk := s.db.HasTable(&dbPrivateKey) switch { case s.db.Error != nil: return s.db.Error case !tableOk: return fmt.Errorf( "Cannot access table: %s", dbPrivateKey.TableName()) } return nil }
[ "func", "(", "s", "*", "SQLKeyDBStore", ")", "HealthCheck", "(", ")", "error", "{", "dbPrivateKey", ":=", "GormPrivateKey", "{", "}", "\n", "tableOk", ":=", "s", ".", "db", ".", "HasTable", "(", "&", "dbPrivateKey", ")", "\n", "switch", "{", "case", "s", ".", "db", ".", "Error", "!=", "nil", ":", "return", "s", ".", "db", ".", "Error", "\n", "case", "!", "tableOk", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dbPrivateKey", ".", "TableName", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// HealthCheck verifies that DB exists and is query-able
[ "HealthCheck", "verifies", "that", "DB", "exists", "and", "is", "query", "-", "able" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/sql_keydbstore.go#L232-L243
train
theupdateframework/notary
cryptoservice/certificate.go
GenerateCertificate
func GenerateCertificate(rootKey data.PrivateKey, gun data.GUN, startTime, endTime time.Time) (*x509.Certificate, error) { signer := rootKey.CryptoSigner() if signer == nil { return nil, fmt.Errorf("key type not supported for Certificate generation: %s", rootKey.Algorithm()) } return generateCertificate(signer, gun, startTime, endTime) }
go
func GenerateCertificate(rootKey data.PrivateKey, gun data.GUN, startTime, endTime time.Time) (*x509.Certificate, error) { signer := rootKey.CryptoSigner() if signer == nil { return nil, fmt.Errorf("key type not supported for Certificate generation: %s", rootKey.Algorithm()) } return generateCertificate(signer, gun, startTime, endTime) }
[ "func", "GenerateCertificate", "(", "rootKey", "data", ".", "PrivateKey", ",", "gun", "data", ".", "GUN", ",", "startTime", ",", "endTime", "time", ".", "Time", ")", "(", "*", "x509", ".", "Certificate", ",", "error", ")", "{", "signer", ":=", "rootKey", ".", "CryptoSigner", "(", ")", "\n", "if", "signer", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rootKey", ".", "Algorithm", "(", ")", ")", "\n", "}", "\n\n", "return", "generateCertificate", "(", "signer", ",", "gun", ",", "startTime", ",", "endTime", ")", "\n", "}" ]
// GenerateCertificate generates an X509 Certificate from a template, given a GUN and validity interval
[ "GenerateCertificate", "generates", "an", "X509", "Certificate", "from", "a", "template", "given", "a", "GUN", "and", "validity", "interval" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/certificate.go#L15-L22
train
theupdateframework/notary
server/storage/rethinkdb.go
NewRethinkDBStorage
func NewRethinkDBStorage(dbName, user, password string, sess *gorethink.Session) RethinkDB { return RethinkDB{ dbName: dbName, sess: sess, user: user, password: password, } }
go
func NewRethinkDBStorage(dbName, user, password string, sess *gorethink.Session) RethinkDB { return RethinkDB{ dbName: dbName, sess: sess, user: user, password: password, } }
[ "func", "NewRethinkDBStorage", "(", "dbName", ",", "user", ",", "password", "string", ",", "sess", "*", "gorethink", ".", "Session", ")", "RethinkDB", "{", "return", "RethinkDB", "{", "dbName", ":", "dbName", ",", "sess", ":", "sess", ",", "user", ":", "user", ",", "password", ":", "password", ",", "}", "\n", "}" ]
// NewRethinkDBStorage initializes a RethinkDB object
[ "NewRethinkDBStorage", "initializes", "a", "RethinkDB", "object" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L106-L113
train
theupdateframework/notary
server/storage/rethinkdb.go
UpdateCurrent
func (rdb RethinkDB) UpdateCurrent(gun data.GUN, update MetaUpdate) error { // empty string is the zero value for tsChecksum in the RDBTUFFile struct. // Therefore we can just call through to updateCurrentWithTSChecksum passing // "" for the tsChecksum value. if err := rdb.updateCurrentWithTSChecksum(gun.String(), "", update); err != nil { return err } if update.Role == data.CanonicalTimestampRole { tsChecksumBytes := sha256.Sum256(update.Data) return rdb.writeChange( gun.String(), update.Version, hex.EncodeToString(tsChecksumBytes[:]), changeCategoryUpdate, ) } return nil }
go
func (rdb RethinkDB) UpdateCurrent(gun data.GUN, update MetaUpdate) error { // empty string is the zero value for tsChecksum in the RDBTUFFile struct. // Therefore we can just call through to updateCurrentWithTSChecksum passing // "" for the tsChecksum value. if err := rdb.updateCurrentWithTSChecksum(gun.String(), "", update); err != nil { return err } if update.Role == data.CanonicalTimestampRole { tsChecksumBytes := sha256.Sum256(update.Data) return rdb.writeChange( gun.String(), update.Version, hex.EncodeToString(tsChecksumBytes[:]), changeCategoryUpdate, ) } return nil }
[ "func", "(", "rdb", "RethinkDB", ")", "UpdateCurrent", "(", "gun", "data", ".", "GUN", ",", "update", "MetaUpdate", ")", "error", "{", "// empty string is the zero value for tsChecksum in the RDBTUFFile struct.", "// Therefore we can just call through to updateCurrentWithTSChecksum passing", "// \"\" for the tsChecksum value.", "if", "err", ":=", "rdb", ".", "updateCurrentWithTSChecksum", "(", "gun", ".", "String", "(", ")", ",", "\"", "\"", ",", "update", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "update", ".", "Role", "==", "data", ".", "CanonicalTimestampRole", "{", "tsChecksumBytes", ":=", "sha256", ".", "Sum256", "(", "update", ".", "Data", ")", "\n", "return", "rdb", ".", "writeChange", "(", "gun", ".", "String", "(", ")", ",", "update", ".", "Version", ",", "hex", ".", "EncodeToString", "(", "tsChecksumBytes", "[", ":", "]", ")", ",", "changeCategoryUpdate", ",", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateCurrent adds new metadata version for the given GUN if and only // if it's a new role, or the version is greater than the current version // for the role. Otherwise an error is returned.
[ "UpdateCurrent", "adds", "new", "metadata", "version", "for", "the", "given", "GUN", "if", "and", "only", "if", "it", "s", "a", "new", "role", "or", "the", "version", "is", "greater", "than", "the", "current", "version", "for", "the", "role", ".", "Otherwise", "an", "error", "is", "returned", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L118-L135
train
theupdateframework/notary
server/storage/rethinkdb.go
updateCurrentWithTSChecksum
func (rdb RethinkDB) updateCurrentWithTSChecksum(gun, tsChecksum string, update MetaUpdate) error { now := time.Now() checksum := sha256.Sum256(update.Data) file := RDBTUFFile{ Timing: rethinkdb.Timing{ CreatedAt: now, UpdatedAt: now, }, GunRoleVersion: []interface{}{gun, update.Role, update.Version}, Gun: gun, Role: update.Role.String(), Version: update.Version, SHA256: hex.EncodeToString(checksum[:]), TSchecksum: tsChecksum, Data: update.Data, } _, err := gorethink.DB(rdb.dbName).Table(file.TableName()).Insert( file, gorethink.InsertOpts{ Conflict: "error", // default but explicit for clarity of intent }, ).RunWrite(rdb.sess) if err != nil && gorethink.IsConflictErr(err) { return ErrOldVersion{} } return err }
go
func (rdb RethinkDB) updateCurrentWithTSChecksum(gun, tsChecksum string, update MetaUpdate) error { now := time.Now() checksum := sha256.Sum256(update.Data) file := RDBTUFFile{ Timing: rethinkdb.Timing{ CreatedAt: now, UpdatedAt: now, }, GunRoleVersion: []interface{}{gun, update.Role, update.Version}, Gun: gun, Role: update.Role.String(), Version: update.Version, SHA256: hex.EncodeToString(checksum[:]), TSchecksum: tsChecksum, Data: update.Data, } _, err := gorethink.DB(rdb.dbName).Table(file.TableName()).Insert( file, gorethink.InsertOpts{ Conflict: "error", // default but explicit for clarity of intent }, ).RunWrite(rdb.sess) if err != nil && gorethink.IsConflictErr(err) { return ErrOldVersion{} } return err }
[ "func", "(", "rdb", "RethinkDB", ")", "updateCurrentWithTSChecksum", "(", "gun", ",", "tsChecksum", "string", ",", "update", "MetaUpdate", ")", "error", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "checksum", ":=", "sha256", ".", "Sum256", "(", "update", ".", "Data", ")", "\n", "file", ":=", "RDBTUFFile", "{", "Timing", ":", "rethinkdb", ".", "Timing", "{", "CreatedAt", ":", "now", ",", "UpdatedAt", ":", "now", ",", "}", ",", "GunRoleVersion", ":", "[", "]", "interface", "{", "}", "{", "gun", ",", "update", ".", "Role", ",", "update", ".", "Version", "}", ",", "Gun", ":", "gun", ",", "Role", ":", "update", ".", "Role", ".", "String", "(", ")", ",", "Version", ":", "update", ".", "Version", ",", "SHA256", ":", "hex", ".", "EncodeToString", "(", "checksum", "[", ":", "]", ")", ",", "TSchecksum", ":", "tsChecksum", ",", "Data", ":", "update", ".", "Data", ",", "}", "\n", "_", ",", "err", ":=", "gorethink", ".", "DB", "(", "rdb", ".", "dbName", ")", ".", "Table", "(", "file", ".", "TableName", "(", ")", ")", ".", "Insert", "(", "file", ",", "gorethink", ".", "InsertOpts", "{", "Conflict", ":", "\"", "\"", ",", "// default but explicit for clarity of intent", "}", ",", ")", ".", "RunWrite", "(", "rdb", ".", "sess", ")", "\n", "if", "err", "!=", "nil", "&&", "gorethink", ".", "IsConflictErr", "(", "err", ")", "{", "return", "ErrOldVersion", "{", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// updateCurrentWithTSChecksum adds new metadata version for the given GUN with an associated // checksum for the timestamp it belongs to, to afford us transaction-like functionality
[ "updateCurrentWithTSChecksum", "adds", "new", "metadata", "version", "for", "the", "given", "GUN", "with", "an", "associated", "checksum", "for", "the", "timestamp", "it", "belongs", "to", "to", "afford", "us", "transaction", "-", "like", "functionality" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L139-L165
train
theupdateframework/notary
server/storage/rethinkdb.go
UpdateMany
func (rdb RethinkDB) UpdateMany(gun data.GUN, updates []MetaUpdate) error { // find the timestamp first and save its checksum // then apply the updates in alphabetic role order with the timestamp last // if there are any failures, we roll back in the same alphabetic order var ( tsChecksum string tsVersion int ) for _, up := range updates { if up.Role == data.CanonicalTimestampRole { tsChecksumBytes := sha256.Sum256(up.Data) tsChecksum = hex.EncodeToString(tsChecksumBytes[:]) tsVersion = up.Version break } } // alphabetize the updates by Role name sort.Stable(updateSorter(updates)) for _, up := range updates { if err := rdb.updateCurrentWithTSChecksum(gun.String(), tsChecksum, up); err != nil { // roll back with best-effort deletion, and then error out rollbackErr := rdb.deleteByTSChecksum(tsChecksum) if rollbackErr != nil { logrus.Errorf("Unable to rollback DB conflict - items with timestamp_checksum %s: %v", tsChecksum, rollbackErr) } return err } } // if the update included a timestamp, write a change object if tsChecksum != "" { return rdb.writeChange(gun.String(), tsVersion, tsChecksum, changeCategoryUpdate) } return nil }
go
func (rdb RethinkDB) UpdateMany(gun data.GUN, updates []MetaUpdate) error { // find the timestamp first and save its checksum // then apply the updates in alphabetic role order with the timestamp last // if there are any failures, we roll back in the same alphabetic order var ( tsChecksum string tsVersion int ) for _, up := range updates { if up.Role == data.CanonicalTimestampRole { tsChecksumBytes := sha256.Sum256(up.Data) tsChecksum = hex.EncodeToString(tsChecksumBytes[:]) tsVersion = up.Version break } } // alphabetize the updates by Role name sort.Stable(updateSorter(updates)) for _, up := range updates { if err := rdb.updateCurrentWithTSChecksum(gun.String(), tsChecksum, up); err != nil { // roll back with best-effort deletion, and then error out rollbackErr := rdb.deleteByTSChecksum(tsChecksum) if rollbackErr != nil { logrus.Errorf("Unable to rollback DB conflict - items with timestamp_checksum %s: %v", tsChecksum, rollbackErr) } return err } } // if the update included a timestamp, write a change object if tsChecksum != "" { return rdb.writeChange(gun.String(), tsVersion, tsChecksum, changeCategoryUpdate) } return nil }
[ "func", "(", "rdb", "RethinkDB", ")", "UpdateMany", "(", "gun", "data", ".", "GUN", ",", "updates", "[", "]", "MetaUpdate", ")", "error", "{", "// find the timestamp first and save its checksum", "// then apply the updates in alphabetic role order with the timestamp last", "// if there are any failures, we roll back in the same alphabetic order", "var", "(", "tsChecksum", "string", "\n", "tsVersion", "int", "\n", ")", "\n", "for", "_", ",", "up", ":=", "range", "updates", "{", "if", "up", ".", "Role", "==", "data", ".", "CanonicalTimestampRole", "{", "tsChecksumBytes", ":=", "sha256", ".", "Sum256", "(", "up", ".", "Data", ")", "\n", "tsChecksum", "=", "hex", ".", "EncodeToString", "(", "tsChecksumBytes", "[", ":", "]", ")", "\n", "tsVersion", "=", "up", ".", "Version", "\n", "break", "\n", "}", "\n", "}", "\n\n", "// alphabetize the updates by Role name", "sort", ".", "Stable", "(", "updateSorter", "(", "updates", ")", ")", "\n\n", "for", "_", ",", "up", ":=", "range", "updates", "{", "if", "err", ":=", "rdb", ".", "updateCurrentWithTSChecksum", "(", "gun", ".", "String", "(", ")", ",", "tsChecksum", ",", "up", ")", ";", "err", "!=", "nil", "{", "// roll back with best-effort deletion, and then error out", "rollbackErr", ":=", "rdb", ".", "deleteByTSChecksum", "(", "tsChecksum", ")", "\n", "if", "rollbackErr", "!=", "nil", "{", "logrus", ".", "Errorf", "(", "\"", "\"", ",", "tsChecksum", ",", "rollbackErr", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}", "\n\n", "// if the update included a timestamp, write a change object", "if", "tsChecksum", "!=", "\"", "\"", "{", "return", "rdb", ".", "writeChange", "(", "gun", ".", "String", "(", ")", ",", "tsVersion", ",", "tsChecksum", ",", "changeCategoryUpdate", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateMany adds multiple new metadata for the given GUN. RethinkDB does // not support transactions, therefore we will attempt to insert the timestamp // last as this represents a published version of the repo. However, we will // insert all other role data in alphabetical order first, and also include the // associated timestamp checksum so that we can easily roll back this pseudotransaction
[ "UpdateMany", "adds", "multiple", "new", "metadata", "for", "the", "given", "GUN", ".", "RethinkDB", "does", "not", "support", "transactions", "therefore", "we", "will", "attempt", "to", "insert", "the", "timestamp", "last", "as", "this", "represents", "a", "published", "version", "of", "the", "repo", ".", "However", "we", "will", "insert", "all", "other", "role", "data", "in", "alphabetical", "order", "first", "and", "also", "include", "the", "associated", "timestamp", "checksum", "so", "that", "we", "can", "easily", "roll", "back", "this", "pseudotransaction" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L182-L219
train
theupdateframework/notary
server/storage/rethinkdb.go
Delete
func (rdb RethinkDB) Delete(gun data.GUN) error { resp, err := gorethink.DB(rdb.dbName).Table(RDBTUFFile{}.TableName()).GetAllByIndex( "gun", gun.String(), ).Delete().RunWrite(rdb.sess) if err != nil { return fmt.Errorf("unable to delete %s from database: %s", gun.String(), err.Error()) } if resp.Deleted > 0 { return rdb.writeChange(gun.String(), 0, "", changeCategoryDeletion) } return nil }
go
func (rdb RethinkDB) Delete(gun data.GUN) error { resp, err := gorethink.DB(rdb.dbName).Table(RDBTUFFile{}.TableName()).GetAllByIndex( "gun", gun.String(), ).Delete().RunWrite(rdb.sess) if err != nil { return fmt.Errorf("unable to delete %s from database: %s", gun.String(), err.Error()) } if resp.Deleted > 0 { return rdb.writeChange(gun.String(), 0, "", changeCategoryDeletion) } return nil }
[ "func", "(", "rdb", "RethinkDB", ")", "Delete", "(", "gun", "data", ".", "GUN", ")", "error", "{", "resp", ",", "err", ":=", "gorethink", ".", "DB", "(", "rdb", ".", "dbName", ")", ".", "Table", "(", "RDBTUFFile", "{", "}", ".", "TableName", "(", ")", ")", ".", "GetAllByIndex", "(", "\"", "\"", ",", "gun", ".", "String", "(", ")", ",", ")", ".", "Delete", "(", ")", ".", "RunWrite", "(", "rdb", ".", "sess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "gun", ".", "String", "(", ")", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "if", "resp", ".", "Deleted", ">", "0", "{", "return", "rdb", ".", "writeChange", "(", "gun", ".", "String", "(", ")", ",", "0", ",", "\"", "\"", ",", "changeCategoryDeletion", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Delete removes all metadata for a given GUN. It does not return an // error if no metadata exists for the given GUN.
[ "Delete", "removes", "all", "metadata", "for", "a", "given", "GUN", ".", "It", "does", "not", "return", "an", "error", "if", "no", "metadata", "exists", "for", "the", "given", "GUN", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L285-L296
train
theupdateframework/notary
server/storage/rethinkdb.go
deleteByTSChecksum
func (rdb RethinkDB) deleteByTSChecksum(tsChecksum string) error { _, err := gorethink.DB(rdb.dbName).Table(RDBTUFFile{}.TableName()).GetAllByIndex( "timestamp_checksum", tsChecksum, ).Delete().RunWrite(rdb.sess) if err != nil { return fmt.Errorf("unable to delete timestamp checksum data: %s from database: %s", tsChecksum, err.Error()) } // DO NOT WRITE CHANGE! THIS IS USED _ONLY_ TO ROLLBACK A FAILED INSERT return nil }
go
func (rdb RethinkDB) deleteByTSChecksum(tsChecksum string) error { _, err := gorethink.DB(rdb.dbName).Table(RDBTUFFile{}.TableName()).GetAllByIndex( "timestamp_checksum", tsChecksum, ).Delete().RunWrite(rdb.sess) if err != nil { return fmt.Errorf("unable to delete timestamp checksum data: %s from database: %s", tsChecksum, err.Error()) } // DO NOT WRITE CHANGE! THIS IS USED _ONLY_ TO ROLLBACK A FAILED INSERT return nil }
[ "func", "(", "rdb", "RethinkDB", ")", "deleteByTSChecksum", "(", "tsChecksum", "string", ")", "error", "{", "_", ",", "err", ":=", "gorethink", ".", "DB", "(", "rdb", ".", "dbName", ")", ".", "Table", "(", "RDBTUFFile", "{", "}", ".", "TableName", "(", ")", ")", ".", "GetAllByIndex", "(", "\"", "\"", ",", "tsChecksum", ",", ")", ".", "Delete", "(", ")", ".", "RunWrite", "(", "rdb", ".", "sess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tsChecksum", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "// DO NOT WRITE CHANGE! THIS IS USED _ONLY_ TO ROLLBACK A FAILED INSERT", "return", "nil", "\n", "}" ]
// deleteByTSChecksum removes all metadata by a timestamp checksum, used for rolling back a "transaction" // from a call to rethinkdb's UpdateMany
[ "deleteByTSChecksum", "removes", "all", "metadata", "by", "a", "timestamp", "checksum", "used", "for", "rolling", "back", "a", "transaction", "from", "a", "call", "to", "rethinkdb", "s", "UpdateMany" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L300-L309
train
theupdateframework/notary
server/storage/rethinkdb.go
Bootstrap
func (rdb RethinkDB) Bootstrap() error { if err := rethinkdb.SetupDB(rdb.sess, rdb.dbName, []rethinkdb.Table{ TUFFilesRethinkTable, ChangeRethinkTable, }); err != nil { return err } return rethinkdb.CreateAndGrantDBUser(rdb.sess, rdb.dbName, rdb.user, rdb.password) }
go
func (rdb RethinkDB) Bootstrap() error { if err := rethinkdb.SetupDB(rdb.sess, rdb.dbName, []rethinkdb.Table{ TUFFilesRethinkTable, ChangeRethinkTable, }); err != nil { return err } return rethinkdb.CreateAndGrantDBUser(rdb.sess, rdb.dbName, rdb.user, rdb.password) }
[ "func", "(", "rdb", "RethinkDB", ")", "Bootstrap", "(", ")", "error", "{", "if", "err", ":=", "rethinkdb", ".", "SetupDB", "(", "rdb", ".", "sess", ",", "rdb", ".", "dbName", ",", "[", "]", "rethinkdb", ".", "Table", "{", "TUFFilesRethinkTable", ",", "ChangeRethinkTable", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "rethinkdb", ".", "CreateAndGrantDBUser", "(", "rdb", ".", "sess", ",", "rdb", ".", "dbName", ",", "rdb", ".", "user", ",", "rdb", ".", "password", ")", "\n", "}" ]
// Bootstrap sets up the database and tables, also creating the notary server user with appropriate db permission
[ "Bootstrap", "sets", "up", "the", "database", "and", "tables", "also", "creating", "the", "notary", "server", "user", "with", "appropriate", "db", "permission" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L312-L320
train
theupdateframework/notary
server/storage/rethinkdb.go
CheckHealth
func (rdb RethinkDB) CheckHealth() error { res, err := gorethink.DB(rdb.dbName).Table(TUFFilesRethinkTable.Name).Info().Run(rdb.sess) if err != nil { return fmt.Errorf("%s is unavailable, or missing one or more tables, or permissions are incorrectly set", rdb.dbName) } defer res.Close() return nil }
go
func (rdb RethinkDB) CheckHealth() error { res, err := gorethink.DB(rdb.dbName).Table(TUFFilesRethinkTable.Name).Info().Run(rdb.sess) if err != nil { return fmt.Errorf("%s is unavailable, or missing one or more tables, or permissions are incorrectly set", rdb.dbName) } defer res.Close() return nil }
[ "func", "(", "rdb", "RethinkDB", ")", "CheckHealth", "(", ")", "error", "{", "res", ",", "err", ":=", "gorethink", ".", "DB", "(", "rdb", ".", "dbName", ")", ".", "Table", "(", "TUFFilesRethinkTable", ".", "Name", ")", ".", "Info", "(", ")", ".", "Run", "(", "rdb", ".", "sess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rdb", ".", "dbName", ")", "\n", "}", "\n", "defer", "res", ".", "Close", "(", ")", "\n", "return", "nil", "\n", "}" ]
// CheckHealth checks that all tables and databases exist and are query-able
[ "CheckHealth", "checks", "that", "all", "tables", "and", "databases", "exist", "and", "are", "query", "-", "able" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L323-L330
train
theupdateframework/notary
server/storage/rethinkdb.go
GetChanges
func (rdb RethinkDB) GetChanges(changeID string, pageSize int, filterName string) ([]Change, error) { var ( lower, upper, bound []interface{} idx = "rdb_created_at_id" max = []interface{}{gorethink.Now().Sub(blackoutTime), gorethink.MaxVal} min = []interface{}{gorethink.MinVal, gorethink.MinVal} order gorethink.OrderByOpts reversed bool ) if filterName != "" { idx = "rdb_gun_created_at_id" max = append([]interface{}{filterName}, max...) min = append([]interface{}{filterName}, min...) } switch changeID { case "0", "-1": lower = min upper = max default: bound, idx = rdb.bound(changeID, filterName) if pageSize < 0 { lower = min upper = bound } else { lower = bound upper = max } } if changeID == "-1" || pageSize < 0 { reversed = true order = gorethink.OrderByOpts{Index: gorethink.Desc(idx)} } else { order = gorethink.OrderByOpts{Index: gorethink.Asc(idx)} } if pageSize < 0 { pageSize = pageSize * -1 } changes := make([]Change, 0, pageSize) // Between returns a slice of results from the rethinkdb table. // The results are ordered using BetweenOpts.Index, which will // default to the index of the immediately preceding OrderBy. // The lower and upper are the start and end points for the slice // and the Left/RightBound values determine whether the lower and // upper values are included in the result per normal set semantics // of "open" and "closed" res, err := gorethink.DB(rdb.dbName). Table(Change{}.TableName(), gorethink.TableOpts{ReadMode: "majority"}). OrderBy(order). Between( lower, upper, gorethink.BetweenOpts{ LeftBound: "open", RightBound: "open", }, ).Limit(pageSize).Run(rdb.sess) if err != nil { return nil, err } defer res.Close() defer func() { if reversed { // results are currently newest to oldest, should be oldest to newest for i, j := 0, len(changes)-1; i < j; i, j = i+1, j-1 { changes[i], changes[j] = changes[j], changes[i] } } }() return changes, res.All(&changes) }
go
func (rdb RethinkDB) GetChanges(changeID string, pageSize int, filterName string) ([]Change, error) { var ( lower, upper, bound []interface{} idx = "rdb_created_at_id" max = []interface{}{gorethink.Now().Sub(blackoutTime), gorethink.MaxVal} min = []interface{}{gorethink.MinVal, gorethink.MinVal} order gorethink.OrderByOpts reversed bool ) if filterName != "" { idx = "rdb_gun_created_at_id" max = append([]interface{}{filterName}, max...) min = append([]interface{}{filterName}, min...) } switch changeID { case "0", "-1": lower = min upper = max default: bound, idx = rdb.bound(changeID, filterName) if pageSize < 0 { lower = min upper = bound } else { lower = bound upper = max } } if changeID == "-1" || pageSize < 0 { reversed = true order = gorethink.OrderByOpts{Index: gorethink.Desc(idx)} } else { order = gorethink.OrderByOpts{Index: gorethink.Asc(idx)} } if pageSize < 0 { pageSize = pageSize * -1 } changes := make([]Change, 0, pageSize) // Between returns a slice of results from the rethinkdb table. // The results are ordered using BetweenOpts.Index, which will // default to the index of the immediately preceding OrderBy. // The lower and upper are the start and end points for the slice // and the Left/RightBound values determine whether the lower and // upper values are included in the result per normal set semantics // of "open" and "closed" res, err := gorethink.DB(rdb.dbName). Table(Change{}.TableName(), gorethink.TableOpts{ReadMode: "majority"}). OrderBy(order). Between( lower, upper, gorethink.BetweenOpts{ LeftBound: "open", RightBound: "open", }, ).Limit(pageSize).Run(rdb.sess) if err != nil { return nil, err } defer res.Close() defer func() { if reversed { // results are currently newest to oldest, should be oldest to newest for i, j := 0, len(changes)-1; i < j; i, j = i+1, j-1 { changes[i], changes[j] = changes[j], changes[i] } } }() return changes, res.All(&changes) }
[ "func", "(", "rdb", "RethinkDB", ")", "GetChanges", "(", "changeID", "string", ",", "pageSize", "int", ",", "filterName", "string", ")", "(", "[", "]", "Change", ",", "error", ")", "{", "var", "(", "lower", ",", "upper", ",", "bound", "[", "]", "interface", "{", "}", "\n", "idx", "=", "\"", "\"", "\n", "max", "=", "[", "]", "interface", "{", "}", "{", "gorethink", ".", "Now", "(", ")", ".", "Sub", "(", "blackoutTime", ")", ",", "gorethink", ".", "MaxVal", "}", "\n", "min", "=", "[", "]", "interface", "{", "}", "{", "gorethink", ".", "MinVal", ",", "gorethink", ".", "MinVal", "}", "\n", "order", "gorethink", ".", "OrderByOpts", "\n", "reversed", "bool", "\n", ")", "\n", "if", "filterName", "!=", "\"", "\"", "{", "idx", "=", "\"", "\"", "\n", "max", "=", "append", "(", "[", "]", "interface", "{", "}", "{", "filterName", "}", ",", "max", "...", ")", "\n", "min", "=", "append", "(", "[", "]", "interface", "{", "}", "{", "filterName", "}", ",", "min", "...", ")", "\n", "}", "\n\n", "switch", "changeID", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "lower", "=", "min", "\n", "upper", "=", "max", "\n", "default", ":", "bound", ",", "idx", "=", "rdb", ".", "bound", "(", "changeID", ",", "filterName", ")", "\n", "if", "pageSize", "<", "0", "{", "lower", "=", "min", "\n", "upper", "=", "bound", "\n", "}", "else", "{", "lower", "=", "bound", "\n", "upper", "=", "max", "\n", "}", "\n", "}", "\n\n", "if", "changeID", "==", "\"", "\"", "||", "pageSize", "<", "0", "{", "reversed", "=", "true", "\n", "order", "=", "gorethink", ".", "OrderByOpts", "{", "Index", ":", "gorethink", ".", "Desc", "(", "idx", ")", "}", "\n", "}", "else", "{", "order", "=", "gorethink", ".", "OrderByOpts", "{", "Index", ":", "gorethink", ".", "Asc", "(", "idx", ")", "}", "\n", "}", "\n\n", "if", "pageSize", "<", "0", "{", "pageSize", "=", "pageSize", "*", "-", "1", "\n", "}", "\n\n", "changes", ":=", "make", "(", "[", "]", "Change", ",", "0", ",", "pageSize", ")", "\n\n", "// Between returns a slice of results from the rethinkdb table.", "// The results are ordered using BetweenOpts.Index, which will", "// default to the index of the immediately preceding OrderBy.", "// The lower and upper are the start and end points for the slice", "// and the Left/RightBound values determine whether the lower and", "// upper values are included in the result per normal set semantics", "// of \"open\" and \"closed\"", "res", ",", "err", ":=", "gorethink", ".", "DB", "(", "rdb", ".", "dbName", ")", ".", "Table", "(", "Change", "{", "}", ".", "TableName", "(", ")", ",", "gorethink", ".", "TableOpts", "{", "ReadMode", ":", "\"", "\"", "}", ")", ".", "OrderBy", "(", "order", ")", ".", "Between", "(", "lower", ",", "upper", ",", "gorethink", ".", "BetweenOpts", "{", "LeftBound", ":", "\"", "\"", ",", "RightBound", ":", "\"", "\"", ",", "}", ",", ")", ".", "Limit", "(", "pageSize", ")", ".", "Run", "(", "rdb", ".", "sess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "res", ".", "Close", "(", ")", "\n\n", "defer", "func", "(", ")", "{", "if", "reversed", "{", "// results are currently newest to oldest, should be oldest to newest", "for", "i", ",", "j", ":=", "0", ",", "len", "(", "changes", ")", "-", "1", ";", "i", "<", "j", ";", "i", ",", "j", "=", "i", "+", "1", ",", "j", "-", "1", "{", "changes", "[", "i", "]", ",", "changes", "[", "j", "]", "=", "changes", "[", "j", "]", ",", "changes", "[", "i", "]", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "changes", ",", "res", ".", "All", "(", "&", "changes", ")", "\n", "}" ]
// GetChanges returns up to pageSize changes starting from changeID. It uses the // blackout to account for RethinkDB's eventual consistency model
[ "GetChanges", "returns", "up", "to", "pageSize", "changes", "starting", "from", "changeID", ".", "It", "uses", "the", "blackout", "to", "account", "for", "RethinkDB", "s", "eventual", "consistency", "model" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L352-L428
train
theupdateframework/notary
server/storage/rethinkdb.go
bound
func (rdb RethinkDB) bound(changeID, filterName string) ([]interface{}, string) { createdAtTerm := gorethink.DB(rdb.dbName).Table(Change{}.TableName()).Get(changeID).Field("created_at") if filterName != "" { return []interface{}{filterName, createdAtTerm, changeID}, "rdb_gun_created_at_id" } return []interface{}{createdAtTerm, changeID}, "rdb_created_at_id" }
go
func (rdb RethinkDB) bound(changeID, filterName string) ([]interface{}, string) { createdAtTerm := gorethink.DB(rdb.dbName).Table(Change{}.TableName()).Get(changeID).Field("created_at") if filterName != "" { return []interface{}{filterName, createdAtTerm, changeID}, "rdb_gun_created_at_id" } return []interface{}{createdAtTerm, changeID}, "rdb_created_at_id" }
[ "func", "(", "rdb", "RethinkDB", ")", "bound", "(", "changeID", ",", "filterName", "string", ")", "(", "[", "]", "interface", "{", "}", ",", "string", ")", "{", "createdAtTerm", ":=", "gorethink", ".", "DB", "(", "rdb", ".", "dbName", ")", ".", "Table", "(", "Change", "{", "}", ".", "TableName", "(", ")", ")", ".", "Get", "(", "changeID", ")", ".", "Field", "(", "\"", "\"", ")", "\n", "if", "filterName", "!=", "\"", "\"", "{", "return", "[", "]", "interface", "{", "}", "{", "filterName", ",", "createdAtTerm", ",", "changeID", "}", ",", "\"", "\"", "\n", "}", "\n", "return", "[", "]", "interface", "{", "}", "{", "createdAtTerm", ",", "changeID", "}", ",", "\"", "\"", "\n", "}" ]
// bound creates the correct boundary based in the index that should be used for // querying the changefeed.
[ "bound", "creates", "the", "correct", "boundary", "based", "in", "the", "index", "that", "should", "be", "used", "for", "querying", "the", "changefeed", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L432-L438
train
theupdateframework/notary
storage/filestore.go
NewFileStore
func NewFileStore(baseDir, fileExt string) (*FilesystemStore, error) { baseDir = filepath.Clean(baseDir) if err := createDirectory(baseDir, notary.PrivExecPerms); err != nil { return nil, err } if !strings.HasPrefix(fileExt, ".") { fileExt = "." + fileExt } return &FilesystemStore{ baseDir: baseDir, ext: fileExt, }, nil }
go
func NewFileStore(baseDir, fileExt string) (*FilesystemStore, error) { baseDir = filepath.Clean(baseDir) if err := createDirectory(baseDir, notary.PrivExecPerms); err != nil { return nil, err } if !strings.HasPrefix(fileExt, ".") { fileExt = "." + fileExt } return &FilesystemStore{ baseDir: baseDir, ext: fileExt, }, nil }
[ "func", "NewFileStore", "(", "baseDir", ",", "fileExt", "string", ")", "(", "*", "FilesystemStore", ",", "error", ")", "{", "baseDir", "=", "filepath", ".", "Clean", "(", "baseDir", ")", "\n", "if", "err", ":=", "createDirectory", "(", "baseDir", ",", "notary", ".", "PrivExecPerms", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "fileExt", ",", "\"", "\"", ")", "{", "fileExt", "=", "\"", "\"", "+", "fileExt", "\n", "}", "\n\n", "return", "&", "FilesystemStore", "{", "baseDir", ":", "baseDir", ",", "ext", ":", "fileExt", ",", "}", ",", "nil", "\n", "}" ]
// NewFileStore creates a fully configurable file store
[ "NewFileStore", "creates", "a", "fully", "configurable", "file", "store" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/filestore.go#L18-L31
train
theupdateframework/notary
storage/filestore.go
NewPrivateKeyFileStorage
func NewPrivateKeyFileStorage(baseDir, fileExt string) (*FilesystemStore, error) { baseDir = filepath.Join(baseDir, notary.PrivDir) myStore, err := NewFileStore(baseDir, fileExt) myStore.migrateTo0Dot4() return myStore, err }
go
func NewPrivateKeyFileStorage(baseDir, fileExt string) (*FilesystemStore, error) { baseDir = filepath.Join(baseDir, notary.PrivDir) myStore, err := NewFileStore(baseDir, fileExt) myStore.migrateTo0Dot4() return myStore, err }
[ "func", "NewPrivateKeyFileStorage", "(", "baseDir", ",", "fileExt", "string", ")", "(", "*", "FilesystemStore", ",", "error", ")", "{", "baseDir", "=", "filepath", ".", "Join", "(", "baseDir", ",", "notary", ".", "PrivDir", ")", "\n", "myStore", ",", "err", ":=", "NewFileStore", "(", "baseDir", ",", "fileExt", ")", "\n", "myStore", ".", "migrateTo0Dot4", "(", ")", "\n", "return", "myStore", ",", "err", "\n", "}" ]
// NewPrivateKeyFileStorage initializes a new filestore for private keys, appending // the notary.PrivDir to the baseDir.
[ "NewPrivateKeyFileStorage", "initializes", "a", "new", "filestore", "for", "private", "keys", "appending", "the", "notary", ".", "PrivDir", "to", "the", "baseDir", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/filestore.go#L35-L40
train
theupdateframework/notary
storage/filestore.go
Get
func (f *FilesystemStore) Get(name string) ([]byte, error) { p, err := f.getPath(name) if err != nil { return nil, err } meta, err := ioutil.ReadFile(p) if err != nil { if os.IsNotExist(err) { err = ErrMetaNotFound{Resource: name} } return nil, err } return meta, nil }
go
func (f *FilesystemStore) Get(name string) ([]byte, error) { p, err := f.getPath(name) if err != nil { return nil, err } meta, err := ioutil.ReadFile(p) if err != nil { if os.IsNotExist(err) { err = ErrMetaNotFound{Resource: name} } return nil, err } return meta, nil }
[ "func", "(", "f", "*", "FilesystemStore", ")", "Get", "(", "name", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "p", ",", "err", ":=", "f", ".", "getPath", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "meta", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "err", "=", "ErrMetaNotFound", "{", "Resource", ":", "name", "}", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "meta", ",", "nil", "\n", "}" ]
// Get returns the meta for the given name.
[ "Get", "returns", "the", "meta", "for", "the", "given", "name", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/filestore.go#L166-L179
train
theupdateframework/notary
storage/filestore.go
SetMulti
func (f *FilesystemStore) SetMulti(metas map[string][]byte) error { for role, blob := range metas { err := f.Set(role, blob) if err != nil { return err } } return nil }
go
func (f *FilesystemStore) SetMulti(metas map[string][]byte) error { for role, blob := range metas { err := f.Set(role, blob) if err != nil { return err } } return nil }
[ "func", "(", "f", "*", "FilesystemStore", ")", "SetMulti", "(", "metas", "map", "[", "string", "]", "[", "]", "byte", ")", "error", "{", "for", "role", ",", "blob", ":=", "range", "metas", "{", "err", ":=", "f", ".", "Set", "(", "role", ",", "blob", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetMulti sets the metadata for multiple roles in one operation
[ "SetMulti", "sets", "the", "metadata", "for", "multiple", "roles", "in", "one", "operation" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/filestore.go#L182-L190
train
theupdateframework/notary
storage/filestore.go
Set
func (f *FilesystemStore) Set(name string, meta []byte) error { fp, err := f.getPath(name) if err != nil { return err } // Ensures the parent directories of the file we are about to write exist err = os.MkdirAll(filepath.Dir(fp), notary.PrivExecPerms) if err != nil { return err } // if something already exists, just delete it and re-write it os.RemoveAll(fp) // Write the file to disk return ioutil.WriteFile(fp, meta, notary.PrivNoExecPerms) }
go
func (f *FilesystemStore) Set(name string, meta []byte) error { fp, err := f.getPath(name) if err != nil { return err } // Ensures the parent directories of the file we are about to write exist err = os.MkdirAll(filepath.Dir(fp), notary.PrivExecPerms) if err != nil { return err } // if something already exists, just delete it and re-write it os.RemoveAll(fp) // Write the file to disk return ioutil.WriteFile(fp, meta, notary.PrivNoExecPerms) }
[ "func", "(", "f", "*", "FilesystemStore", ")", "Set", "(", "name", "string", ",", "meta", "[", "]", "byte", ")", "error", "{", "fp", ",", "err", ":=", "f", ".", "getPath", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Ensures the parent directories of the file we are about to write exist", "err", "=", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "fp", ")", ",", "notary", ".", "PrivExecPerms", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// if something already exists, just delete it and re-write it", "os", ".", "RemoveAll", "(", "fp", ")", "\n\n", "// Write the file to disk", "return", "ioutil", ".", "WriteFile", "(", "fp", ",", "meta", ",", "notary", ".", "PrivNoExecPerms", ")", "\n", "}" ]
// Set sets the meta for a single role
[ "Set", "sets", "the", "meta", "for", "a", "single", "role" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/filestore.go#L193-L210
train
theupdateframework/notary
storage/httpstore.go
NewNotaryServerStore
func NewNotaryServerStore(serverURL string, gun data.GUN, roundTrip http.RoundTripper) (RemoteStore, error) { return NewHTTPStore( serverURL+"/v2/"+gun.String()+"/_trust/tuf/", "", "json", "key", roundTrip, ) }
go
func NewNotaryServerStore(serverURL string, gun data.GUN, roundTrip http.RoundTripper) (RemoteStore, error) { return NewHTTPStore( serverURL+"/v2/"+gun.String()+"/_trust/tuf/", "", "json", "key", roundTrip, ) }
[ "func", "NewNotaryServerStore", "(", "serverURL", "string", ",", "gun", "data", ".", "GUN", ",", "roundTrip", "http", ".", "RoundTripper", ")", "(", "RemoteStore", ",", "error", ")", "{", "return", "NewHTTPStore", "(", "serverURL", "+", "\"", "\"", "+", "gun", ".", "String", "(", ")", "+", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "roundTrip", ",", ")", "\n", "}" ]
// NewNotaryServerStore returns a new HTTPStore against a URL which should represent a notary // server
[ "NewNotaryServerStore", "returns", "a", "new", "HTTPStore", "against", "a", "URL", "which", "should", "represent", "a", "notary", "server" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L116-L124
train
theupdateframework/notary
storage/httpstore.go
NewHTTPStore
func NewHTTPStore(baseURL, metaPrefix, metaExtension, keyExtension string, roundTrip http.RoundTripper) (RemoteStore, error) { base, err := url.Parse(baseURL) if err != nil { return nil, err } if !base.IsAbs() { return nil, errors.New("HTTPStore requires an absolute baseURL") } if roundTrip == nil { return &OfflineStore{}, nil } return &HTTPStore{ baseURL: *base, metaPrefix: metaPrefix, metaExtension: metaExtension, keyExtension: keyExtension, roundTrip: roundTrip, }, nil }
go
func NewHTTPStore(baseURL, metaPrefix, metaExtension, keyExtension string, roundTrip http.RoundTripper) (RemoteStore, error) { base, err := url.Parse(baseURL) if err != nil { return nil, err } if !base.IsAbs() { return nil, errors.New("HTTPStore requires an absolute baseURL") } if roundTrip == nil { return &OfflineStore{}, nil } return &HTTPStore{ baseURL: *base, metaPrefix: metaPrefix, metaExtension: metaExtension, keyExtension: keyExtension, roundTrip: roundTrip, }, nil }
[ "func", "NewHTTPStore", "(", "baseURL", ",", "metaPrefix", ",", "metaExtension", ",", "keyExtension", "string", ",", "roundTrip", "http", ".", "RoundTripper", ")", "(", "RemoteStore", ",", "error", ")", "{", "base", ",", "err", ":=", "url", ".", "Parse", "(", "baseURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "base", ".", "IsAbs", "(", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "roundTrip", "==", "nil", "{", "return", "&", "OfflineStore", "{", "}", ",", "nil", "\n", "}", "\n", "return", "&", "HTTPStore", "{", "baseURL", ":", "*", "base", ",", "metaPrefix", ":", "metaPrefix", ",", "metaExtension", ":", "metaExtension", ",", "keyExtension", ":", "keyExtension", ",", "roundTrip", ":", "roundTrip", ",", "}", ",", "nil", "\n", "}" ]
// NewHTTPStore initializes a new store against a URL and a number of configuration options. // // In case of a nil `roundTrip`, a default offline store is used instead.
[ "NewHTTPStore", "initializes", "a", "new", "store", "against", "a", "URL", "and", "a", "number", "of", "configuration", "options", ".", "In", "case", "of", "a", "nil", "roundTrip", "a", "default", "offline", "store", "is", "used", "instead", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L129-L147
train
theupdateframework/notary
storage/httpstore.go
GetSized
func (s HTTPStore) GetSized(name string, size int64) ([]byte, error) { url, err := s.buildMetaURL(name) if err != nil { return nil, err } req, err := http.NewRequest("GET", url.String(), nil) if err != nil { return nil, err } resp, err := s.roundTrip.RoundTrip(req) if err != nil { return nil, NetworkError{Wrapped: err} } defer resp.Body.Close() if err := translateStatusToError(resp, name); err != nil { logrus.Debugf("received HTTP status %d when requesting %s.", resp.StatusCode, name) return nil, err } if size == NoSizeLimit { size = notary.MaxDownloadSize } if resp.ContentLength > size { return nil, ErrMaliciousServer{} } logrus.Debugf("%d when retrieving metadata for %s", resp.StatusCode, name) b := io.LimitReader(resp.Body, size) body, err := ioutil.ReadAll(b) if err != nil { return nil, err } return body, nil }
go
func (s HTTPStore) GetSized(name string, size int64) ([]byte, error) { url, err := s.buildMetaURL(name) if err != nil { return nil, err } req, err := http.NewRequest("GET", url.String(), nil) if err != nil { return nil, err } resp, err := s.roundTrip.RoundTrip(req) if err != nil { return nil, NetworkError{Wrapped: err} } defer resp.Body.Close() if err := translateStatusToError(resp, name); err != nil { logrus.Debugf("received HTTP status %d when requesting %s.", resp.StatusCode, name) return nil, err } if size == NoSizeLimit { size = notary.MaxDownloadSize } if resp.ContentLength > size { return nil, ErrMaliciousServer{} } logrus.Debugf("%d when retrieving metadata for %s", resp.StatusCode, name) b := io.LimitReader(resp.Body, size) body, err := ioutil.ReadAll(b) if err != nil { return nil, err } return body, nil }
[ "func", "(", "s", "HTTPStore", ")", "GetSized", "(", "name", "string", ",", "size", "int64", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "url", ",", "err", ":=", "s", ".", "buildMetaURL", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ".", "String", "(", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "s", ".", "roundTrip", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "NetworkError", "{", "Wrapped", ":", "err", "}", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", ":=", "translateStatusToError", "(", "resp", ",", "name", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "resp", ".", "StatusCode", ",", "name", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "size", "==", "NoSizeLimit", "{", "size", "=", "notary", ".", "MaxDownloadSize", "\n", "}", "\n", "if", "resp", ".", "ContentLength", ">", "size", "{", "return", "nil", ",", "ErrMaliciousServer", "{", "}", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "resp", ".", "StatusCode", ",", "name", ")", "\n", "b", ":=", "io", ".", "LimitReader", "(", "resp", ".", "Body", ",", "size", ")", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "body", ",", "nil", "\n", "}" ]
// GetSized downloads the named meta file with the given size. A short body // is acceptable because in the case of timestamp.json, the size is a cap, // not an exact length. // If size is "NoSizeLimit", this corresponds to "infinite," but we cut off at a // predefined threshold "notary.MaxDownloadSize".
[ "GetSized", "downloads", "the", "named", "meta", "file", "with", "the", "given", "size", ".", "A", "short", "body", "is", "acceptable", "because", "in", "the", "case", "of", "timestamp", ".", "json", "the", "size", "is", "a", "cap", "not", "an", "exact", "length", ".", "If", "size", "is", "NoSizeLimit", "this", "corresponds", "to", "infinite", "but", "we", "cut", "off", "at", "a", "predefined", "threshold", "notary", ".", "MaxDownloadSize", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L191-L222
train
theupdateframework/notary
storage/httpstore.go
Set
func (s HTTPStore) Set(name string, blob []byte) error { return s.SetMulti(map[string][]byte{name: blob}) }
go
func (s HTTPStore) Set(name string, blob []byte) error { return s.SetMulti(map[string][]byte{name: blob}) }
[ "func", "(", "s", "HTTPStore", ")", "Set", "(", "name", "string", ",", "blob", "[", "]", "byte", ")", "error", "{", "return", "s", ".", "SetMulti", "(", "map", "[", "string", "]", "[", "]", "byte", "{", "name", ":", "blob", "}", ")", "\n", "}" ]
// Set sends a single piece of metadata to the TUF server
[ "Set", "sends", "a", "single", "piece", "of", "metadata", "to", "the", "TUF", "server" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L225-L227
train
theupdateframework/notary
storage/httpstore.go
NewMultiPartMetaRequest
func NewMultiPartMetaRequest(url string, metas map[string][]byte) (*http.Request, error) { body := &bytes.Buffer{} writer := multipart.NewWriter(body) for role, blob := range metas { part, err := writer.CreateFormFile("files", role) if err != nil { return nil, err } _, err = io.Copy(part, bytes.NewBuffer(blob)) if err != nil { return nil, err } } err := writer.Close() if err != nil { return nil, err } req, err := http.NewRequest("POST", url, body) if err != nil { return nil, err } req.Header.Set("Content-Type", writer.FormDataContentType()) return req, nil }
go
func NewMultiPartMetaRequest(url string, metas map[string][]byte) (*http.Request, error) { body := &bytes.Buffer{} writer := multipart.NewWriter(body) for role, blob := range metas { part, err := writer.CreateFormFile("files", role) if err != nil { return nil, err } _, err = io.Copy(part, bytes.NewBuffer(blob)) if err != nil { return nil, err } } err := writer.Close() if err != nil { return nil, err } req, err := http.NewRequest("POST", url, body) if err != nil { return nil, err } req.Header.Set("Content-Type", writer.FormDataContentType()) return req, nil }
[ "func", "NewMultiPartMetaRequest", "(", "url", "string", ",", "metas", "map", "[", "string", "]", "[", "]", "byte", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "body", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "writer", ":=", "multipart", ".", "NewWriter", "(", "body", ")", "\n", "for", "role", ",", "blob", ":=", "range", "metas", "{", "part", ",", "err", ":=", "writer", ".", "CreateFormFile", "(", "\"", "\"", ",", "role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "part", ",", "bytes", ".", "NewBuffer", "(", "blob", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "err", ":=", "writer", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "writer", ".", "FormDataContentType", "(", ")", ")", "\n", "return", "req", ",", "nil", "\n", "}" ]
// NewMultiPartMetaRequest builds a request with the provided metadata updates // in multipart form
[ "NewMultiPartMetaRequest", "builds", "a", "request", "with", "the", "provided", "metadata", "updates", "in", "multipart", "form" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L237-L260
train
theupdateframework/notary
storage/httpstore.go
SetMulti
func (s HTTPStore) SetMulti(metas map[string][]byte) error { url, err := s.buildMetaURL("") if err != nil { return err } req, err := NewMultiPartMetaRequest(url.String(), metas) if err != nil { return err } resp, err := s.roundTrip.RoundTrip(req) if err != nil { return NetworkError{Wrapped: err} } defer resp.Body.Close() // if this 404's something is pretty wrong return translateStatusToError(resp, "POST metadata endpoint") }
go
func (s HTTPStore) SetMulti(metas map[string][]byte) error { url, err := s.buildMetaURL("") if err != nil { return err } req, err := NewMultiPartMetaRequest(url.String(), metas) if err != nil { return err } resp, err := s.roundTrip.RoundTrip(req) if err != nil { return NetworkError{Wrapped: err} } defer resp.Body.Close() // if this 404's something is pretty wrong return translateStatusToError(resp, "POST metadata endpoint") }
[ "func", "(", "s", "HTTPStore", ")", "SetMulti", "(", "metas", "map", "[", "string", "]", "[", "]", "byte", ")", "error", "{", "url", ",", "err", ":=", "s", ".", "buildMetaURL", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "req", ",", "err", ":=", "NewMultiPartMetaRequest", "(", "url", ".", "String", "(", ")", ",", "metas", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "s", ".", "roundTrip", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NetworkError", "{", "Wrapped", ":", "err", "}", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "// if this 404's something is pretty wrong", "return", "translateStatusToError", "(", "resp", ",", "\"", "\"", ")", "\n", "}" ]
// SetMulti does a single batch upload of multiple pieces of TUF metadata. // This should be preferred for updating a remote server as it enable the server // to remain consistent, either accepting or rejecting the complete update.
[ "SetMulti", "does", "a", "single", "batch", "upload", "of", "multiple", "pieces", "of", "TUF", "metadata", ".", "This", "should", "be", "preferred", "for", "updating", "a", "remote", "server", "as", "it", "enable", "the", "server", "to", "remain", "consistent", "either", "accepting", "or", "rejecting", "the", "complete", "update", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L265-L281
train
theupdateframework/notary
storage/httpstore.go
RemoveAll
func (s HTTPStore) RemoveAll() error { url, err := s.buildMetaURL("") if err != nil { return err } req, err := http.NewRequest("DELETE", url.String(), nil) if err != nil { return err } resp, err := s.roundTrip.RoundTrip(req) if err != nil { return NetworkError{Wrapped: err} } defer resp.Body.Close() return translateStatusToError(resp, "DELETE metadata for GUN endpoint") }
go
func (s HTTPStore) RemoveAll() error { url, err := s.buildMetaURL("") if err != nil { return err } req, err := http.NewRequest("DELETE", url.String(), nil) if err != nil { return err } resp, err := s.roundTrip.RoundTrip(req) if err != nil { return NetworkError{Wrapped: err} } defer resp.Body.Close() return translateStatusToError(resp, "DELETE metadata for GUN endpoint") }
[ "func", "(", "s", "HTTPStore", ")", "RemoveAll", "(", ")", "error", "{", "url", ",", "err", ":=", "s", ".", "buildMetaURL", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ".", "String", "(", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "s", ".", "roundTrip", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NetworkError", "{", "Wrapped", ":", "err", "}", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "return", "translateStatusToError", "(", "resp", ",", "\"", "\"", ")", "\n", "}" ]
// RemoveAll will attempt to delete all TUF metadata for a GUN
[ "RemoveAll", "will", "attempt", "to", "delete", "all", "TUF", "metadata", "for", "a", "GUN" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L284-L299
train
theupdateframework/notary
storage/httpstore.go
GetKey
func (s HTTPStore) GetKey(role data.RoleName) ([]byte, error) { url, err := s.buildKeyURL(role) if err != nil { return nil, err } req, err := http.NewRequest("GET", url.String(), nil) if err != nil { return nil, err } resp, err := s.roundTrip.RoundTrip(req) if err != nil { return nil, NetworkError{Wrapped: err} } defer resp.Body.Close() if err := translateStatusToError(resp, role.String()+" key"); err != nil { return nil, err } b := io.LimitReader(resp.Body, MaxKeySize) body, err := ioutil.ReadAll(b) if err != nil { return nil, err } return body, nil }
go
func (s HTTPStore) GetKey(role data.RoleName) ([]byte, error) { url, err := s.buildKeyURL(role) if err != nil { return nil, err } req, err := http.NewRequest("GET", url.String(), nil) if err != nil { return nil, err } resp, err := s.roundTrip.RoundTrip(req) if err != nil { return nil, NetworkError{Wrapped: err} } defer resp.Body.Close() if err := translateStatusToError(resp, role.String()+" key"); err != nil { return nil, err } b := io.LimitReader(resp.Body, MaxKeySize) body, err := ioutil.ReadAll(b) if err != nil { return nil, err } return body, nil }
[ "func", "(", "s", "HTTPStore", ")", "GetKey", "(", "role", "data", ".", "RoleName", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "url", ",", "err", ":=", "s", ".", "buildKeyURL", "(", "role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ".", "String", "(", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "s", ".", "roundTrip", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "NetworkError", "{", "Wrapped", ":", "err", "}", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", ":=", "translateStatusToError", "(", "resp", ",", "role", ".", "String", "(", ")", "+", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "b", ":=", "io", ".", "LimitReader", "(", "resp", ".", "Body", ",", "MaxKeySize", ")", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "body", ",", "nil", "\n", "}" ]
// GetKey retrieves a public key from the remote server
[ "GetKey", "retrieves", "a", "public", "key", "from", "the", "remote", "server" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/httpstore.go#L325-L348
train
go-gomail/gomail
send.go
Send
func Send(s Sender, msg ...*Message) error { for i, m := range msg { if err := send(s, m); err != nil { return fmt.Errorf("gomail: could not send email %d: %v", i+1, err) } } return nil }
go
func Send(s Sender, msg ...*Message) error { for i, m := range msg { if err := send(s, m); err != nil { return fmt.Errorf("gomail: could not send email %d: %v", i+1, err) } } return nil }
[ "func", "Send", "(", "s", "Sender", ",", "msg", "...", "*", "Message", ")", "error", "{", "for", "i", ",", "m", ":=", "range", "msg", "{", "if", "err", ":=", "send", "(", "s", ",", "m", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "i", "+", "1", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Send sends emails using the given Sender.
[ "Send", "sends", "emails", "using", "the", "given", "Sender", "." ]
81ebce5c23dfd25c6c67194b37d3dd3f338c98b1
https://github.com/go-gomail/gomail/blob/81ebce5c23dfd25c6c67194b37d3dd3f338c98b1/send.go#L36-L44
train
go-gomail/gomail
smtp.go
NewDialer
func NewDialer(host string, port int, username, password string) *Dialer { return &Dialer{ Host: host, Port: port, Username: username, Password: password, SSL: port == 465, } }
go
func NewDialer(host string, port int, username, password string) *Dialer { return &Dialer{ Host: host, Port: port, Username: username, Password: password, SSL: port == 465, } }
[ "func", "NewDialer", "(", "host", "string", ",", "port", "int", ",", "username", ",", "password", "string", ")", "*", "Dialer", "{", "return", "&", "Dialer", "{", "Host", ":", "host", ",", "Port", ":", "port", ",", "Username", ":", "username", ",", "Password", ":", "password", ",", "SSL", ":", "port", "==", "465", ",", "}", "\n", "}" ]
// NewDialer returns a new SMTP Dialer. The given parameters are used to connect // to the SMTP server.
[ "NewDialer", "returns", "a", "new", "SMTP", "Dialer", ".", "The", "given", "parameters", "are", "used", "to", "connect", "to", "the", "SMTP", "server", "." ]
81ebce5c23dfd25c6c67194b37d3dd3f338c98b1
https://github.com/go-gomail/gomail/blob/81ebce5c23dfd25c6c67194b37d3dd3f338c98b1/smtp.go#L40-L48
train
go-gomail/gomail
smtp.go
Dial
func (d *Dialer) Dial() (SendCloser, error) { conn, err := netDialTimeout("tcp", addr(d.Host, d.Port), 10*time.Second) if err != nil { return nil, err } if d.SSL { conn = tlsClient(conn, d.tlsConfig()) } c, err := smtpNewClient(conn, d.Host) if err != nil { return nil, err } if d.LocalName != "" { if err := c.Hello(d.LocalName); err != nil { return nil, err } } if !d.SSL { if ok, _ := c.Extension("STARTTLS"); ok { if err := c.StartTLS(d.tlsConfig()); err != nil { c.Close() return nil, err } } } if d.Auth == nil && d.Username != "" { if ok, auths := c.Extension("AUTH"); ok { if strings.Contains(auths, "CRAM-MD5") { d.Auth = smtp.CRAMMD5Auth(d.Username, d.Password) } else if strings.Contains(auths, "LOGIN") && !strings.Contains(auths, "PLAIN") { d.Auth = &loginAuth{ username: d.Username, password: d.Password, host: d.Host, } } else { d.Auth = smtp.PlainAuth("", d.Username, d.Password, d.Host) } } } if d.Auth != nil { if err = c.Auth(d.Auth); err != nil { c.Close() return nil, err } } return &smtpSender{c, d}, nil }
go
func (d *Dialer) Dial() (SendCloser, error) { conn, err := netDialTimeout("tcp", addr(d.Host, d.Port), 10*time.Second) if err != nil { return nil, err } if d.SSL { conn = tlsClient(conn, d.tlsConfig()) } c, err := smtpNewClient(conn, d.Host) if err != nil { return nil, err } if d.LocalName != "" { if err := c.Hello(d.LocalName); err != nil { return nil, err } } if !d.SSL { if ok, _ := c.Extension("STARTTLS"); ok { if err := c.StartTLS(d.tlsConfig()); err != nil { c.Close() return nil, err } } } if d.Auth == nil && d.Username != "" { if ok, auths := c.Extension("AUTH"); ok { if strings.Contains(auths, "CRAM-MD5") { d.Auth = smtp.CRAMMD5Auth(d.Username, d.Password) } else if strings.Contains(auths, "LOGIN") && !strings.Contains(auths, "PLAIN") { d.Auth = &loginAuth{ username: d.Username, password: d.Password, host: d.Host, } } else { d.Auth = smtp.PlainAuth("", d.Username, d.Password, d.Host) } } } if d.Auth != nil { if err = c.Auth(d.Auth); err != nil { c.Close() return nil, err } } return &smtpSender{c, d}, nil }
[ "func", "(", "d", "*", "Dialer", ")", "Dial", "(", ")", "(", "SendCloser", ",", "error", ")", "{", "conn", ",", "err", ":=", "netDialTimeout", "(", "\"", "\"", ",", "addr", "(", "d", ".", "Host", ",", "d", ".", "Port", ")", ",", "10", "*", "time", ".", "Second", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "d", ".", "SSL", "{", "conn", "=", "tlsClient", "(", "conn", ",", "d", ".", "tlsConfig", "(", ")", ")", "\n", "}", "\n\n", "c", ",", "err", ":=", "smtpNewClient", "(", "conn", ",", "d", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "d", ".", "LocalName", "!=", "\"", "\"", "{", "if", "err", ":=", "c", ".", "Hello", "(", "d", ".", "LocalName", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "!", "d", ".", "SSL", "{", "if", "ok", ",", "_", ":=", "c", ".", "Extension", "(", "\"", "\"", ")", ";", "ok", "{", "if", "err", ":=", "c", ".", "StartTLS", "(", "d", ".", "tlsConfig", "(", ")", ")", ";", "err", "!=", "nil", "{", "c", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "d", ".", "Auth", "==", "nil", "&&", "d", ".", "Username", "!=", "\"", "\"", "{", "if", "ok", ",", "auths", ":=", "c", ".", "Extension", "(", "\"", "\"", ")", ";", "ok", "{", "if", "strings", ".", "Contains", "(", "auths", ",", "\"", "\"", ")", "{", "d", ".", "Auth", "=", "smtp", ".", "CRAMMD5Auth", "(", "d", ".", "Username", ",", "d", ".", "Password", ")", "\n", "}", "else", "if", "strings", ".", "Contains", "(", "auths", ",", "\"", "\"", ")", "&&", "!", "strings", ".", "Contains", "(", "auths", ",", "\"", "\"", ")", "{", "d", ".", "Auth", "=", "&", "loginAuth", "{", "username", ":", "d", ".", "Username", ",", "password", ":", "d", ".", "Password", ",", "host", ":", "d", ".", "Host", ",", "}", "\n", "}", "else", "{", "d", ".", "Auth", "=", "smtp", ".", "PlainAuth", "(", "\"", "\"", ",", "d", ".", "Username", ",", "d", ".", "Password", ",", "d", ".", "Host", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "d", ".", "Auth", "!=", "nil", "{", "if", "err", "=", "c", ".", "Auth", "(", "d", ".", "Auth", ")", ";", "err", "!=", "nil", "{", "c", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "&", "smtpSender", "{", "c", ",", "d", "}", ",", "nil", "\n", "}" ]
// Dial dials and authenticates to an SMTP server. The returned SendCloser // should be closed when done using it.
[ "Dial", "dials", "and", "authenticates", "to", "an", "SMTP", "server", ".", "The", "returned", "SendCloser", "should", "be", "closed", "when", "done", "using", "it", "." ]
81ebce5c23dfd25c6c67194b37d3dd3f338c98b1
https://github.com/go-gomail/gomail/blob/81ebce5c23dfd25c6c67194b37d3dd3f338c98b1/smtp.go#L60-L115
train
go-gomail/gomail
message.go
SetBody
func (m *Message) SetBody(contentType, body string, settings ...PartSetting) { m.parts = []*part{m.newPart(contentType, newCopier(body), settings)} }
go
func (m *Message) SetBody(contentType, body string, settings ...PartSetting) { m.parts = []*part{m.newPart(contentType, newCopier(body), settings)} }
[ "func", "(", "m", "*", "Message", ")", "SetBody", "(", "contentType", ",", "body", "string", ",", "settings", "...", "PartSetting", ")", "{", "m", ".", "parts", "=", "[", "]", "*", "part", "{", "m", ".", "newPart", "(", "contentType", ",", "newCopier", "(", "body", ")", ",", "settings", ")", "}", "\n", "}" ]
// SetBody sets the body of the message. It replaces any content previously set // by SetBody, AddAlternative or AddAlternativeWriter.
[ "SetBody", "sets", "the", "body", "of", "the", "message", ".", "It", "replaces", "any", "content", "previously", "set", "by", "SetBody", "AddAlternative", "or", "AddAlternativeWriter", "." ]
81ebce5c23dfd25c6c67194b37d3dd3f338c98b1
https://github.com/go-gomail/gomail/blob/81ebce5c23dfd25c6c67194b37d3dd3f338c98b1/message.go#L187-L189
train
swaggo/gin-swagger
swaggerFiles/ab0x.go
Open
func (hfs *HTTPFS) Open(path string) (http.File, error) { f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644) if err != nil { return nil, err } return f, nil }
go
func (hfs *HTTPFS) Open(path string) (http.File, error) { f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644) if err != nil { return nil, err } return f, nil }
[ "func", "(", "hfs", "*", "HTTPFS", ")", "Open", "(", "path", "string", ")", "(", "http", ".", "File", ",", "error", ")", "{", "f", ",", "err", ":=", "FS", ".", "OpenFile", "(", "CTX", ",", "path", ",", "os", ".", "O_RDONLY", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "f", ",", "nil", "\n", "}" ]
// Open a file
[ "Open", "a", "file" ]
dbf6ef410096ed3b4a467a14040e019fd7a0f85a
https://github.com/swaggo/gin-swagger/blob/dbf6ef410096ed3b4a467a14040e019fd7a0f85a/swaggerFiles/ab0x.go#L50-L57
train
swaggo/gin-swagger
swaggerFiles/ab0x.go
ReadFile
func ReadFile(path string) ([]byte, error) { f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644) if err != nil { return nil, err } buf := bytes.NewBuffer(make([]byte, 0, bytes.MinRead)) // If the buffer overflows, we will get bytes.ErrTooLarge. // Return that as an error. Any other panic remains. defer func() { e := recover() if e == nil { return } if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge { err = panicErr } else { panic(e) } }() _, err = buf.ReadFrom(f) return buf.Bytes(), err }
go
func ReadFile(path string) ([]byte, error) { f, err := FS.OpenFile(CTX, path, os.O_RDONLY, 0644) if err != nil { return nil, err } buf := bytes.NewBuffer(make([]byte, 0, bytes.MinRead)) // If the buffer overflows, we will get bytes.ErrTooLarge. // Return that as an error. Any other panic remains. defer func() { e := recover() if e == nil { return } if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge { err = panicErr } else { panic(e) } }() _, err = buf.ReadFrom(f) return buf.Bytes(), err }
[ "func", "ReadFile", "(", "path", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "f", ",", "err", ":=", "FS", ".", "OpenFile", "(", "CTX", ",", "path", ",", "os", ".", "O_RDONLY", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "bytes", ".", "MinRead", ")", ")", "\n\n", "// If the buffer overflows, we will get bytes.ErrTooLarge.", "// Return that as an error. Any other panic remains.", "defer", "func", "(", ")", "{", "e", ":=", "recover", "(", ")", "\n", "if", "e", "==", "nil", "{", "return", "\n", "}", "\n", "if", "panicErr", ",", "ok", ":=", "e", ".", "(", "error", ")", ";", "ok", "&&", "panicErr", "==", "bytes", ".", "ErrTooLarge", "{", "err", "=", "panicErr", "\n", "}", "else", "{", "panic", "(", "e", ")", "\n", "}", "\n", "}", "(", ")", "\n", "_", ",", "err", "=", "buf", ".", "ReadFrom", "(", "f", ")", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "err", "\n", "}" ]
// ReadFile is adapTed from ioutil
[ "ReadFile", "is", "adapTed", "from", "ioutil" ]
dbf6ef410096ed3b4a467a14040e019fd7a0f85a
https://github.com/swaggo/gin-swagger/blob/dbf6ef410096ed3b4a467a14040e019fd7a0f85a/swaggerFiles/ab0x.go#L60-L83
train
swaggo/gin-swagger
swagger.go
WrapHandler
func WrapHandler(h *webdav.Handler, confs ...func(c *Config)) gin.HandlerFunc { defaultConfig := &Config{ URL: "doc.json", } for _, c := range confs { c(defaultConfig) } return CustomWrapHandler(defaultConfig, h) }
go
func WrapHandler(h *webdav.Handler, confs ...func(c *Config)) gin.HandlerFunc { defaultConfig := &Config{ URL: "doc.json", } for _, c := range confs { c(defaultConfig) } return CustomWrapHandler(defaultConfig, h) }
[ "func", "WrapHandler", "(", "h", "*", "webdav", ".", "Handler", ",", "confs", "...", "func", "(", "c", "*", "Config", ")", ")", "gin", ".", "HandlerFunc", "{", "defaultConfig", ":=", "&", "Config", "{", "URL", ":", "\"", "\"", ",", "}", "\n\n", "for", "_", ",", "c", ":=", "range", "confs", "{", "c", "(", "defaultConfig", ")", "\n", "}", "\n\n", "return", "CustomWrapHandler", "(", "defaultConfig", ",", "h", ")", "\n", "}" ]
// WrapHandler wraps `http.Handler` into `gin.HandlerFunc`.
[ "WrapHandler", "wraps", "http", ".", "Handler", "into", "gin", ".", "HandlerFunc", "." ]
dbf6ef410096ed3b4a467a14040e019fd7a0f85a
https://github.com/swaggo/gin-swagger/blob/dbf6ef410096ed3b4a467a14040e019fd7a0f85a/swagger.go#L29-L39
train
swaggo/gin-swagger
swagger.go
CustomWrapHandler
func CustomWrapHandler(config *Config, h *webdav.Handler) gin.HandlerFunc { //create a template with name t := template.New("swagger_index.html") index, _ := t.Parse(swagger_index_templ) var rexp = regexp.MustCompile(`(.*)(index\.html|doc\.json|favicon-16x16\.png|favicon-32x32\.png|/oauth2-redirect\.html|swagger-ui\.css|swagger-ui\.css\.map|swagger-ui\.js|swagger-ui\.js\.map|swagger-ui-bundle\.js|swagger-ui-bundle\.js\.map|swagger-ui-standalone-preset\.js|swagger-ui-standalone-preset\.js\.map)[\?|.]*`) return func(c *gin.Context) { type swaggerUIBundle struct { URL string } var matches []string if matches = rexp.FindStringSubmatch(c.Request.RequestURI); len(matches) != 3 { c.Status(404) c.Writer.Write([]byte("404 page not found")) return } path := matches[2] prefix := matches[1] h.Prefix = prefix if strings.HasSuffix(path, ".html") { c.Header("Content-Type", "text/html; charset=utf-8") } else if strings.HasSuffix(path, ".css") { c.Header("Content-Type", "text/css; charset=utf-8") } else if strings.HasSuffix(path, ".js") { c.Header("Content-Type", "application/javascript") } else if strings.HasSuffix(path, ".json") { c.Header("Content-Type", "application/json") } switch path { case "index.html": index.Execute(c.Writer, &swaggerUIBundle{ URL: config.URL, }) case "doc.json": doc, err := swag.ReadDoc() if err != nil { panic(err) } c.Writer.Write([]byte(doc)) return default: h.ServeHTTP(c.Writer, c.Request) } } }
go
func CustomWrapHandler(config *Config, h *webdav.Handler) gin.HandlerFunc { //create a template with name t := template.New("swagger_index.html") index, _ := t.Parse(swagger_index_templ) var rexp = regexp.MustCompile(`(.*)(index\.html|doc\.json|favicon-16x16\.png|favicon-32x32\.png|/oauth2-redirect\.html|swagger-ui\.css|swagger-ui\.css\.map|swagger-ui\.js|swagger-ui\.js\.map|swagger-ui-bundle\.js|swagger-ui-bundle\.js\.map|swagger-ui-standalone-preset\.js|swagger-ui-standalone-preset\.js\.map)[\?|.]*`) return func(c *gin.Context) { type swaggerUIBundle struct { URL string } var matches []string if matches = rexp.FindStringSubmatch(c.Request.RequestURI); len(matches) != 3 { c.Status(404) c.Writer.Write([]byte("404 page not found")) return } path := matches[2] prefix := matches[1] h.Prefix = prefix if strings.HasSuffix(path, ".html") { c.Header("Content-Type", "text/html; charset=utf-8") } else if strings.HasSuffix(path, ".css") { c.Header("Content-Type", "text/css; charset=utf-8") } else if strings.HasSuffix(path, ".js") { c.Header("Content-Type", "application/javascript") } else if strings.HasSuffix(path, ".json") { c.Header("Content-Type", "application/json") } switch path { case "index.html": index.Execute(c.Writer, &swaggerUIBundle{ URL: config.URL, }) case "doc.json": doc, err := swag.ReadDoc() if err != nil { panic(err) } c.Writer.Write([]byte(doc)) return default: h.ServeHTTP(c.Writer, c.Request) } } }
[ "func", "CustomWrapHandler", "(", "config", "*", "Config", ",", "h", "*", "webdav", ".", "Handler", ")", "gin", ".", "HandlerFunc", "{", "//create a template with name", "t", ":=", "template", ".", "New", "(", "\"", "\"", ")", "\n", "index", ",", "_", ":=", "t", ".", "Parse", "(", "swagger_index_templ", ")", "\n\n", "var", "rexp", "=", "regexp", ".", "MustCompile", "(", "`(.*)(index\\.html|doc\\.json|favicon-16x16\\.png|favicon-32x32\\.png|/oauth2-redirect\\.html|swagger-ui\\.css|swagger-ui\\.css\\.map|swagger-ui\\.js|swagger-ui\\.js\\.map|swagger-ui-bundle\\.js|swagger-ui-bundle\\.js\\.map|swagger-ui-standalone-preset\\.js|swagger-ui-standalone-preset\\.js\\.map)[\\?|.]*`", ")", "\n\n", "return", "func", "(", "c", "*", "gin", ".", "Context", ")", "{", "type", "swaggerUIBundle", "struct", "{", "URL", "string", "\n", "}", "\n\n", "var", "matches", "[", "]", "string", "\n", "if", "matches", "=", "rexp", ".", "FindStringSubmatch", "(", "c", ".", "Request", ".", "RequestURI", ")", ";", "len", "(", "matches", ")", "!=", "3", "{", "c", ".", "Status", "(", "404", ")", "\n", "c", ".", "Writer", ".", "Write", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", "\n", "return", "\n", "}", "\n", "path", ":=", "matches", "[", "2", "]", "\n", "prefix", ":=", "matches", "[", "1", "]", "\n", "h", ".", "Prefix", "=", "prefix", "\n\n", "if", "strings", ".", "HasSuffix", "(", "path", ",", "\"", "\"", ")", "{", "c", ".", "Header", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "else", "if", "strings", ".", "HasSuffix", "(", "path", ",", "\"", "\"", ")", "{", "c", ".", "Header", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "else", "if", "strings", ".", "HasSuffix", "(", "path", ",", "\"", "\"", ")", "{", "c", ".", "Header", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "else", "if", "strings", ".", "HasSuffix", "(", "path", ",", "\"", "\"", ")", "{", "c", ".", "Header", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "switch", "path", "{", "case", "\"", "\"", ":", "index", ".", "Execute", "(", "c", ".", "Writer", ",", "&", "swaggerUIBundle", "{", "URL", ":", "config", ".", "URL", ",", "}", ")", "\n", "case", "\"", "\"", ":", "doc", ",", "err", ":=", "swag", ".", "ReadDoc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "c", ".", "Writer", ".", "Write", "(", "[", "]", "byte", "(", "doc", ")", ")", "\n", "return", "\n", "default", ":", "h", ".", "ServeHTTP", "(", "c", ".", "Writer", ",", "c", ".", "Request", ")", "\n", "}", "\n", "}", "\n", "}" ]
// CustomWrapHandler wraps `http.Handler` into `gin.HandlerFunc`
[ "CustomWrapHandler", "wraps", "http", ".", "Handler", "into", "gin", ".", "HandlerFunc" ]
dbf6ef410096ed3b4a467a14040e019fd7a0f85a
https://github.com/swaggo/gin-swagger/blob/dbf6ef410096ed3b4a467a14040e019fd7a0f85a/swagger.go#L42-L91
train
swaggo/gin-swagger
swagger.go
DisablingWrapHandler
func DisablingWrapHandler(h *webdav.Handler, envName string) gin.HandlerFunc { eFlag := os.Getenv(envName) if eFlag != "" { return func(c *gin.Context) { // Simulate behavior when route unspecified and // return 404 HTTP code c.String(404, "") } } return WrapHandler(h) }
go
func DisablingWrapHandler(h *webdav.Handler, envName string) gin.HandlerFunc { eFlag := os.Getenv(envName) if eFlag != "" { return func(c *gin.Context) { // Simulate behavior when route unspecified and // return 404 HTTP code c.String(404, "") } } return WrapHandler(h) }
[ "func", "DisablingWrapHandler", "(", "h", "*", "webdav", ".", "Handler", ",", "envName", "string", ")", "gin", ".", "HandlerFunc", "{", "eFlag", ":=", "os", ".", "Getenv", "(", "envName", ")", "\n", "if", "eFlag", "!=", "\"", "\"", "{", "return", "func", "(", "c", "*", "gin", ".", "Context", ")", "{", "// Simulate behavior when route unspecified and", "// return 404 HTTP code", "c", ".", "String", "(", "404", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "WrapHandler", "(", "h", ")", "\n", "}" ]
// DisablingWrapHandler turn handler off // if specified environment variable passed
[ "DisablingWrapHandler", "turn", "handler", "off", "if", "specified", "environment", "variable", "passed" ]
dbf6ef410096ed3b4a467a14040e019fd7a0f85a
https://github.com/swaggo/gin-swagger/blob/dbf6ef410096ed3b4a467a14040e019fd7a0f85a/swagger.go#L95-L106
train