repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
hprose/hprose-golang
rpc/filter/jsonrpc/client_filter.go
NewClientFilter
func NewClientFilter(version string) *ClientFilter { if version == "1.0" || version == "1.1" || version == "2.0" { return &ClientFilter{Version: version} } panic("version must be 1.0, 1.1 or 2.0 in string format.") }
go
func NewClientFilter(version string) *ClientFilter { if version == "1.0" || version == "1.1" || version == "2.0" { return &ClientFilter{Version: version} } panic("version must be 1.0, 1.1 or 2.0 in string format.") }
[ "func", "NewClientFilter", "(", "version", "string", ")", "*", "ClientFilter", "{", "if", "version", "==", "\"1.0\"", "||", "version", "==", "\"1.1\"", "||", "version", "==", "\"2.0\"", "{", "return", "&", "ClientFilter", "{", "Version", ":", "version", "}",...
// NewClientFilter is a constructor for JSONRPCClientFilter
[ "NewClientFilter", "is", "a", "constructor", "for", "JSONRPCClientFilter" ]
6c2a3b7138ea2c7dc4a8907d644f9f134e0fae74
https://github.com/hprose/hprose-golang/blob/6c2a3b7138ea2c7dc4a8907d644f9f134e0fae74/rpc/filter/jsonrpc/client_filter.go#L37-L42
train
hprose/hprose-golang
rpc/filter/jsonrpc/client_filter.go
InputFilter
func (filter *ClientFilter) InputFilter(data []byte, context rpc.Context) []byte { if context.GetBool("jsonrpc") { var response map[string]interface{} if err := json.Unmarshal(data, &response); err != nil { return data } err := response["error"] writer := io.NewWriter(true) if err != nil { e := err.(map[string]interface{}) writer.WriteByte(io.TagError) writer.WriteString(e["message"].(string)) } else { writer.WriteByte(io.TagResult) writer.Serialize(response["result"]) } writer.WriteByte(io.TagEnd) data = writer.Bytes() } return data }
go
func (filter *ClientFilter) InputFilter(data []byte, context rpc.Context) []byte { if context.GetBool("jsonrpc") { var response map[string]interface{} if err := json.Unmarshal(data, &response); err != nil { return data } err := response["error"] writer := io.NewWriter(true) if err != nil { e := err.(map[string]interface{}) writer.WriteByte(io.TagError) writer.WriteString(e["message"].(string)) } else { writer.WriteByte(io.TagResult) writer.Serialize(response["result"]) } writer.WriteByte(io.TagEnd) data = writer.Bytes() } return data }
[ "func", "(", "filter", "*", "ClientFilter", ")", "InputFilter", "(", "data", "[", "]", "byte", ",", "context", "rpc", ".", "Context", ")", "[", "]", "byte", "{", "if", "context", ".", "GetBool", "(", "\"jsonrpc\"", ")", "{", "var", "response", "map", ...
// InputFilter for JSONRPC Client
[ "InputFilter", "for", "JSONRPC", "Client" ]
6c2a3b7138ea2c7dc4a8907d644f9f134e0fae74
https://github.com/hprose/hprose-golang/blob/6c2a3b7138ea2c7dc4a8907d644f9f134e0fae74/rpc/filter/jsonrpc/client_filter.go#L45-L65
train
hprose/hprose-golang
rpc/filter/jsonrpc/client_filter.go
OutputFilter
func (filter *ClientFilter) OutputFilter(data []byte, context rpc.Context) []byte { if context.GetBool("jsonrpc") { request := make(map[string]interface{}) if filter.Version == "1.1" { request["version"] = "1.1" } else if filter.Version == "2.0" { request["jsonrpc"] = "2.0" } reader := io.NewReader(data, false) reader.JSONCompatible = true tag, _ := reader.ReadByte() if tag == io.TagCall { request["method"] = reader.ReadString() tag, _ = reader.ReadByte() if tag == io.TagList { reader.Reset() count := reader.ReadCount() params := make([]interface{}, count) for i := 0; i < count; i++ { reader.Unserialize(&params[i]) } request["params"] = params } } request["id"] = atomic.AddInt32(&filter.id, 1) data, _ = json.Marshal(request) } return data }
go
func (filter *ClientFilter) OutputFilter(data []byte, context rpc.Context) []byte { if context.GetBool("jsonrpc") { request := make(map[string]interface{}) if filter.Version == "1.1" { request["version"] = "1.1" } else if filter.Version == "2.0" { request["jsonrpc"] = "2.0" } reader := io.NewReader(data, false) reader.JSONCompatible = true tag, _ := reader.ReadByte() if tag == io.TagCall { request["method"] = reader.ReadString() tag, _ = reader.ReadByte() if tag == io.TagList { reader.Reset() count := reader.ReadCount() params := make([]interface{}, count) for i := 0; i < count; i++ { reader.Unserialize(&params[i]) } request["params"] = params } } request["id"] = atomic.AddInt32(&filter.id, 1) data, _ = json.Marshal(request) } return data }
[ "func", "(", "filter", "*", "ClientFilter", ")", "OutputFilter", "(", "data", "[", "]", "byte", ",", "context", "rpc", ".", "Context", ")", "[", "]", "byte", "{", "if", "context", ".", "GetBool", "(", "\"jsonrpc\"", ")", "{", "request", ":=", "make", ...
// OutputFilter for JSONRPC Client
[ "OutputFilter", "for", "JSONRPC", "Client" ]
6c2a3b7138ea2c7dc4a8907d644f9f134e0fae74
https://github.com/hprose/hprose-golang/blob/6c2a3b7138ea2c7dc4a8907d644f9f134e0fae74/rpc/filter/jsonrpc/client_filter.go#L68-L96
train
theupdateframework/notary
tuf/utils/x509.go
X509PublicKeyID
func X509PublicKeyID(certPubKey data.PublicKey) (string, error) { // Note that this only loads the first certificate from the public key cert, err := LoadCertFromPEM(certPubKey.Public()) if err != nil { return "", err } pubKeyBytes, err := x509.MarshalPKIXPublicKey(cert.PublicKey) if err != nil { return "", err } var key data.PublicKey switch certPubKey.Algorithm() { case data.ECDSAx509Key: key = data.NewECDSAPublicKey(pubKeyBytes) case data.RSAx509Key: key = data.NewRSAPublicKey(pubKeyBytes) } return key.ID(), nil }
go
func X509PublicKeyID(certPubKey data.PublicKey) (string, error) { // Note that this only loads the first certificate from the public key cert, err := LoadCertFromPEM(certPubKey.Public()) if err != nil { return "", err } pubKeyBytes, err := x509.MarshalPKIXPublicKey(cert.PublicKey) if err != nil { return "", err } var key data.PublicKey switch certPubKey.Algorithm() { case data.ECDSAx509Key: key = data.NewECDSAPublicKey(pubKeyBytes) case data.RSAx509Key: key = data.NewRSAPublicKey(pubKeyBytes) } return key.ID(), nil }
[ "func", "X509PublicKeyID", "(", "certPubKey", "data", ".", "PublicKey", ")", "(", "string", ",", "error", ")", "{", "cert", ",", "err", ":=", "LoadCertFromPEM", "(", "certPubKey", ".", "Public", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "retu...
// X509PublicKeyID returns a public key ID as a string, given a // data.PublicKey that contains an X509 Certificate
[ "X509PublicKeyID", "returns", "a", "public", "key", "ID", "as", "a", "string", "given", "a", "data", ".", "PublicKey", "that", "contains", "an", "X509", "Certificate" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L66-L86
train
theupdateframework/notary
tuf/utils/x509.go
CertToPEM
func CertToPEM(cert *x509.Certificate) []byte { pemCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}) return pemCert }
go
func CertToPEM(cert *x509.Certificate) []byte { pemCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}) return pemCert }
[ "func", "CertToPEM", "(", "cert", "*", "x509", ".", "Certificate", ")", "[", "]", "byte", "{", "pemCert", ":=", "pem", ".", "EncodeToMemory", "(", "&", "pem", ".", "Block", "{", "Type", ":", "\"CERTIFICATE\"", ",", "Bytes", ":", "cert", ".", "Raw", "...
// CertToPEM is a utility function returns a PEM encoded x509 Certificate
[ "CertToPEM", "is", "a", "utility", "function", "returns", "a", "PEM", "encoded", "x509", "Certificate" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L171-L175
train
theupdateframework/notary
tuf/utils/x509.go
CertChainToPEM
func CertChainToPEM(certChain []*x509.Certificate) ([]byte, error) { var pemBytes bytes.Buffer for _, cert := range certChain { if err := pem.Encode(&pemBytes, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}); err != nil { return nil, err } } return pemBytes.Bytes(), nil }
go
func CertChainToPEM(certChain []*x509.Certificate) ([]byte, error) { var pemBytes bytes.Buffer for _, cert := range certChain { if err := pem.Encode(&pemBytes, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}); err != nil { return nil, err } } return pemBytes.Bytes(), nil }
[ "func", "CertChainToPEM", "(", "certChain", "[", "]", "*", "x509", ".", "Certificate", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "pemBytes", "bytes", ".", "Buffer", "\n", "for", "_", ",", "cert", ":=", "range", "certChain", "{", "if"...
// CertChainToPEM is a utility function returns a PEM encoded chain of x509 Certificates, in the order they are passed
[ "CertChainToPEM", "is", "a", "utility", "function", "returns", "a", "PEM", "encoded", "chain", "of", "x509", "Certificates", "in", "the", "order", "they", "are", "passed" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L178-L186
train
theupdateframework/notary
tuf/utils/x509.go
LoadCertFromFile
func LoadCertFromFile(filename string) (*x509.Certificate, error) { certs, err := LoadCertBundleFromFile(filename) if err != nil { return nil, err } return certs[0], nil }
go
func LoadCertFromFile(filename string) (*x509.Certificate, error) { certs, err := LoadCertBundleFromFile(filename) if err != nil { return nil, err } return certs[0], nil }
[ "func", "LoadCertFromFile", "(", "filename", "string", ")", "(", "*", "x509", ".", "Certificate", ",", "error", ")", "{", "certs", ",", "err", ":=", "LoadCertBundleFromFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ","...
// LoadCertFromFile loads the first certificate from the file provided. The // data is expected to be PEM Encoded and contain one of more certificates // with PEM type "CERTIFICATE"
[ "LoadCertFromFile", "loads", "the", "first", "certificate", "from", "the", "file", "provided", ".", "The", "data", "is", "expected", "to", "be", "PEM", "Encoded", "and", "contain", "one", "of", "more", "certificates", "with", "PEM", "type", "CERTIFICATE" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L191-L197
train
theupdateframework/notary
tuf/utils/x509.go
GetLeafCerts
func GetLeafCerts(certs []*x509.Certificate) []*x509.Certificate { var leafCerts []*x509.Certificate for _, cert := range certs { if cert.IsCA { continue } leafCerts = append(leafCerts, cert) } return leafCerts }
go
func GetLeafCerts(certs []*x509.Certificate) []*x509.Certificate { var leafCerts []*x509.Certificate for _, cert := range certs { if cert.IsCA { continue } leafCerts = append(leafCerts, cert) } return leafCerts }
[ "func", "GetLeafCerts", "(", "certs", "[", "]", "*", "x509", ".", "Certificate", ")", "[", "]", "*", "x509", ".", "Certificate", "{", "var", "leafCerts", "[", "]", "*", "x509", ".", "Certificate", "\n", "for", "_", ",", "cert", ":=", "range", "certs"...
// GetLeafCerts parses a list of x509 Certificates and returns all of them // that aren't CA
[ "GetLeafCerts", "parses", "a", "list", "of", "x509", "Certificates", "and", "returns", "all", "of", "them", "that", "aren", "t", "CA" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L239-L248
train
theupdateframework/notary
tuf/utils/x509.go
GetIntermediateCerts
func GetIntermediateCerts(certs []*x509.Certificate) []*x509.Certificate { var intCerts []*x509.Certificate for _, cert := range certs { if cert.IsCA { intCerts = append(intCerts, cert) } } return intCerts }
go
func GetIntermediateCerts(certs []*x509.Certificate) []*x509.Certificate { var intCerts []*x509.Certificate for _, cert := range certs { if cert.IsCA { intCerts = append(intCerts, cert) } } return intCerts }
[ "func", "GetIntermediateCerts", "(", "certs", "[", "]", "*", "x509", ".", "Certificate", ")", "[", "]", "*", "x509", ".", "Certificate", "{", "var", "intCerts", "[", "]", "*", "x509", ".", "Certificate", "\n", "for", "_", ",", "cert", ":=", "range", ...
// GetIntermediateCerts parses a list of x509 Certificates and returns all of the // ones marked as a CA, to be used as intermediates
[ "GetIntermediateCerts", "parses", "a", "list", "of", "x509", "Certificates", "and", "returns", "all", "of", "the", "ones", "marked", "as", "a", "CA", "to", "be", "used", "as", "intermediates" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L252-L260
train
theupdateframework/notary
tuf/utils/x509.go
ParsePEMPublicKey
func ParsePEMPublicKey(pubKeyBytes []byte) (data.PublicKey, error) { pemBlock, _ := pem.Decode(pubKeyBytes) if pemBlock == nil { return nil, errors.New("no valid public key found") } switch pemBlock.Type { case "CERTIFICATE": cert, err := x509.ParseCertificate(pemBlock.Bytes) if err != nil { return nil, fmt.Errorf("could not parse provided certificate: %v", err) } err = ValidateCertificate(cert, true) if err != nil { return nil, fmt.Errorf("invalid certificate: %v", err) } return CertToKey(cert), nil case "PUBLIC KEY": keyType, err := keyTypeForPublicKey(pemBlock.Bytes) if err != nil { return nil, err } return data.NewPublicKey(keyType, pemBlock.Bytes), nil default: return nil, fmt.Errorf("unsupported PEM block type %q, expected CERTIFICATE or PUBLIC KEY", pemBlock.Type) } }
go
func ParsePEMPublicKey(pubKeyBytes []byte) (data.PublicKey, error) { pemBlock, _ := pem.Decode(pubKeyBytes) if pemBlock == nil { return nil, errors.New("no valid public key found") } switch pemBlock.Type { case "CERTIFICATE": cert, err := x509.ParseCertificate(pemBlock.Bytes) if err != nil { return nil, fmt.Errorf("could not parse provided certificate: %v", err) } err = ValidateCertificate(cert, true) if err != nil { return nil, fmt.Errorf("invalid certificate: %v", err) } return CertToKey(cert), nil case "PUBLIC KEY": keyType, err := keyTypeForPublicKey(pemBlock.Bytes) if err != nil { return nil, err } return data.NewPublicKey(keyType, pemBlock.Bytes), nil default: return nil, fmt.Errorf("unsupported PEM block type %q, expected CERTIFICATE or PUBLIC KEY", pemBlock.Type) } }
[ "func", "ParsePEMPublicKey", "(", "pubKeyBytes", "[", "]", "byte", ")", "(", "data", ".", "PublicKey", ",", "error", ")", "{", "pemBlock", ",", "_", ":=", "pem", ".", "Decode", "(", "pubKeyBytes", ")", "\n", "if", "pemBlock", "==", "nil", "{", "return"...
// ParsePEMPublicKey returns a data.PublicKey from a PEM encoded public key or certificate.
[ "ParsePEMPublicKey", "returns", "a", "data", ".", "PublicKey", "from", "a", "PEM", "encoded", "public", "key", "or", "certificate", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L263-L289
train
theupdateframework/notary
tuf/utils/x509.go
ValidateCertificate
func ValidateCertificate(c *x509.Certificate, checkExpiry bool) error { if (c.NotBefore).After(c.NotAfter) { return fmt.Errorf("certificate validity window is invalid") } // Can't have SHA1 sig algorithm if c.SignatureAlgorithm == x509.SHA1WithRSA || c.SignatureAlgorithm == x509.DSAWithSHA1 || c.SignatureAlgorithm == x509.ECDSAWithSHA1 { return fmt.Errorf("certificate with CN %s uses invalid SHA1 signature algorithm", c.Subject.CommonName) } // If we have an RSA key, make sure it's long enough if c.PublicKeyAlgorithm == x509.RSA { rsaKey, ok := c.PublicKey.(*rsa.PublicKey) if !ok { return fmt.Errorf("unable to parse RSA public key") } if rsaKey.N.BitLen() < notary.MinRSABitSize { return fmt.Errorf("RSA bit length is too short") } } if checkExpiry { now := time.Now() tomorrow := now.AddDate(0, 0, 1) // Give one day leeway on creation "before" time, check "after" against today if (tomorrow).Before(c.NotBefore) || now.After(c.NotAfter) { return data.ErrCertExpired{CN: c.Subject.CommonName} } // If this certificate is expiring within 6 months, put out a warning if (c.NotAfter).Before(time.Now().AddDate(0, 6, 0)) { logrus.Warnf("certificate with CN %s is near expiry", c.Subject.CommonName) } } return nil }
go
func ValidateCertificate(c *x509.Certificate, checkExpiry bool) error { if (c.NotBefore).After(c.NotAfter) { return fmt.Errorf("certificate validity window is invalid") } // Can't have SHA1 sig algorithm if c.SignatureAlgorithm == x509.SHA1WithRSA || c.SignatureAlgorithm == x509.DSAWithSHA1 || c.SignatureAlgorithm == x509.ECDSAWithSHA1 { return fmt.Errorf("certificate with CN %s uses invalid SHA1 signature algorithm", c.Subject.CommonName) } // If we have an RSA key, make sure it's long enough if c.PublicKeyAlgorithm == x509.RSA { rsaKey, ok := c.PublicKey.(*rsa.PublicKey) if !ok { return fmt.Errorf("unable to parse RSA public key") } if rsaKey.N.BitLen() < notary.MinRSABitSize { return fmt.Errorf("RSA bit length is too short") } } if checkExpiry { now := time.Now() tomorrow := now.AddDate(0, 0, 1) // Give one day leeway on creation "before" time, check "after" against today if (tomorrow).Before(c.NotBefore) || now.After(c.NotAfter) { return data.ErrCertExpired{CN: c.Subject.CommonName} } // If this certificate is expiring within 6 months, put out a warning if (c.NotAfter).Before(time.Now().AddDate(0, 6, 0)) { logrus.Warnf("certificate with CN %s is near expiry", c.Subject.CommonName) } } return nil }
[ "func", "ValidateCertificate", "(", "c", "*", "x509", ".", "Certificate", ",", "checkExpiry", "bool", ")", "error", "{", "if", "(", "c", ".", "NotBefore", ")", ".", "After", "(", "c", ".", "NotAfter", ")", "{", "return", "fmt", ".", "Errorf", "(", "\...
// ValidateCertificate returns an error if the certificate is not valid for notary // Currently this is only ensuring the public key has a large enough modulus if RSA, // using a non SHA1 signature algorithm, and an optional time expiry check
[ "ValidateCertificate", "returns", "an", "error", "if", "the", "certificate", "is", "not", "valid", "for", "notary", "Currently", "this", "is", "only", "ensuring", "the", "public", "key", "has", "a", "large", "enough", "modulus", "if", "RSA", "using", "a", "n...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L308-L339
train
theupdateframework/notary
tuf/utils/x509.go
GenerateKey
func GenerateKey(algorithm string) (data.PrivateKey, error) { switch algorithm { case data.ECDSAKey: return GenerateECDSAKey(rand.Reader) case data.ED25519Key: return GenerateED25519Key(rand.Reader) } return nil, fmt.Errorf("private key type not supported for key generation: %s", algorithm) }
go
func GenerateKey(algorithm string) (data.PrivateKey, error) { switch algorithm { case data.ECDSAKey: return GenerateECDSAKey(rand.Reader) case data.ED25519Key: return GenerateED25519Key(rand.Reader) } return nil, fmt.Errorf("private key type not supported for key generation: %s", algorithm) }
[ "func", "GenerateKey", "(", "algorithm", "string", ")", "(", "data", ".", "PrivateKey", ",", "error", ")", "{", "switch", "algorithm", "{", "case", "data", ".", "ECDSAKey", ":", "return", "GenerateECDSAKey", "(", "rand", ".", "Reader", ")", "\n", "case", ...
// GenerateKey returns a new private key using the provided algorithm or an // error detailing why the key could not be generated
[ "GenerateKey", "returns", "a", "new", "private", "key", "using", "the", "provided", "algorithm", "or", "an", "error", "detailing", "why", "the", "key", "could", "not", "be", "generated" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L343-L351
train
theupdateframework/notary
tuf/utils/x509.go
RSAToPrivateKey
func RSAToPrivateKey(rsaPrivKey *rsa.PrivateKey) (data.PrivateKey, error) { // Get a DER-encoded representation of the PublicKey rsaPubBytes, err := x509.MarshalPKIXPublicKey(&rsaPrivKey.PublicKey) if err != nil { return nil, fmt.Errorf("failed to marshal public key: %v", err) } // Get a DER-encoded representation of the PrivateKey rsaPrivBytes := x509.MarshalPKCS1PrivateKey(rsaPrivKey) pubKey := data.NewRSAPublicKey(rsaPubBytes) return data.NewRSAPrivateKey(pubKey, rsaPrivBytes) }
go
func RSAToPrivateKey(rsaPrivKey *rsa.PrivateKey) (data.PrivateKey, error) { // Get a DER-encoded representation of the PublicKey rsaPubBytes, err := x509.MarshalPKIXPublicKey(&rsaPrivKey.PublicKey) if err != nil { return nil, fmt.Errorf("failed to marshal public key: %v", err) } // Get a DER-encoded representation of the PrivateKey rsaPrivBytes := x509.MarshalPKCS1PrivateKey(rsaPrivKey) pubKey := data.NewRSAPublicKey(rsaPubBytes) return data.NewRSAPrivateKey(pubKey, rsaPrivBytes) }
[ "func", "RSAToPrivateKey", "(", "rsaPrivKey", "*", "rsa", ".", "PrivateKey", ")", "(", "data", ".", "PrivateKey", ",", "error", ")", "{", "rsaPubBytes", ",", "err", ":=", "x509", ".", "MarshalPKIXPublicKey", "(", "&", "rsaPrivKey", ".", "PublicKey", ")", "...
// RSAToPrivateKey converts an rsa.Private key to a TUF data.PrivateKey type
[ "RSAToPrivateKey", "converts", "an", "rsa", ".", "Private", "key", "to", "a", "TUF", "data", ".", "PrivateKey", "type" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L354-L366
train
theupdateframework/notary
tuf/utils/x509.go
GenerateECDSAKey
func GenerateECDSAKey(random io.Reader) (data.PrivateKey, error) { ecdsaPrivKey, err := ecdsa.GenerateKey(elliptic.P256(), random) if err != nil { return nil, err } tufPrivKey, err := ECDSAToPrivateKey(ecdsaPrivKey) if err != nil { return nil, err } logrus.Debugf("generated ECDSA key with keyID: %s", tufPrivKey.ID()) return tufPrivKey, nil }
go
func GenerateECDSAKey(random io.Reader) (data.PrivateKey, error) { ecdsaPrivKey, err := ecdsa.GenerateKey(elliptic.P256(), random) if err != nil { return nil, err } tufPrivKey, err := ECDSAToPrivateKey(ecdsaPrivKey) if err != nil { return nil, err } logrus.Debugf("generated ECDSA key with keyID: %s", tufPrivKey.ID()) return tufPrivKey, nil }
[ "func", "GenerateECDSAKey", "(", "random", "io", ".", "Reader", ")", "(", "data", ".", "PrivateKey", ",", "error", ")", "{", "ecdsaPrivKey", ",", "err", ":=", "ecdsa", ".", "GenerateKey", "(", "elliptic", ".", "P256", "(", ")", ",", "random", ")", "\n"...
// GenerateECDSAKey generates an ECDSA Private key and returns a TUF PrivateKey
[ "GenerateECDSAKey", "generates", "an", "ECDSA", "Private", "key", "and", "returns", "a", "TUF", "PrivateKey" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L369-L383
train
theupdateframework/notary
tuf/utils/x509.go
GenerateED25519Key
func GenerateED25519Key(random io.Reader) (data.PrivateKey, error) { pub, priv, err := ed25519.GenerateKey(random) if err != nil { return nil, err } var serialized [ed25519.PublicKeySize + ed25519.PrivateKeySize]byte copy(serialized[:], pub[:]) copy(serialized[ed25519.PublicKeySize:], priv[:]) tufPrivKey, err := ED25519ToPrivateKey(serialized[:]) if err != nil { return nil, err } logrus.Debugf("generated ED25519 key with keyID: %s", tufPrivKey.ID()) return tufPrivKey, nil }
go
func GenerateED25519Key(random io.Reader) (data.PrivateKey, error) { pub, priv, err := ed25519.GenerateKey(random) if err != nil { return nil, err } var serialized [ed25519.PublicKeySize + ed25519.PrivateKeySize]byte copy(serialized[:], pub[:]) copy(serialized[ed25519.PublicKeySize:], priv[:]) tufPrivKey, err := ED25519ToPrivateKey(serialized[:]) if err != nil { return nil, err } logrus.Debugf("generated ED25519 key with keyID: %s", tufPrivKey.ID()) return tufPrivKey, nil }
[ "func", "GenerateED25519Key", "(", "random", "io", ".", "Reader", ")", "(", "data", ".", "PrivateKey", ",", "error", ")", "{", "pub", ",", "priv", ",", "err", ":=", "ed25519", ".", "GenerateKey", "(", "random", ")", "\n", "if", "err", "!=", "nil", "{...
// GenerateED25519Key generates an ED25519 private key and returns a TUF // PrivateKey. The serialization format we use is just the public key bytes // followed by the private key bytes
[ "GenerateED25519Key", "generates", "an", "ED25519", "private", "key", "and", "returns", "a", "TUF", "PrivateKey", ".", "The", "serialization", "format", "we", "use", "is", "just", "the", "public", "key", "bytes", "followed", "by", "the", "private", "key", "byt...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L388-L406
train
theupdateframework/notary
tuf/utils/x509.go
ECDSAToPrivateKey
func ECDSAToPrivateKey(ecdsaPrivKey *ecdsa.PrivateKey) (data.PrivateKey, error) { // Get a DER-encoded representation of the PublicKey ecdsaPubBytes, err := x509.MarshalPKIXPublicKey(&ecdsaPrivKey.PublicKey) if err != nil { return nil, fmt.Errorf("failed to marshal public key: %v", err) } // Get a DER-encoded representation of the PrivateKey ecdsaPrivKeyBytes, err := x509.MarshalECPrivateKey(ecdsaPrivKey) if err != nil { return nil, fmt.Errorf("failed to marshal private key: %v", err) } pubKey := data.NewECDSAPublicKey(ecdsaPubBytes) return data.NewECDSAPrivateKey(pubKey, ecdsaPrivKeyBytes) }
go
func ECDSAToPrivateKey(ecdsaPrivKey *ecdsa.PrivateKey) (data.PrivateKey, error) { // Get a DER-encoded representation of the PublicKey ecdsaPubBytes, err := x509.MarshalPKIXPublicKey(&ecdsaPrivKey.PublicKey) if err != nil { return nil, fmt.Errorf("failed to marshal public key: %v", err) } // Get a DER-encoded representation of the PrivateKey ecdsaPrivKeyBytes, err := x509.MarshalECPrivateKey(ecdsaPrivKey) if err != nil { return nil, fmt.Errorf("failed to marshal private key: %v", err) } pubKey := data.NewECDSAPublicKey(ecdsaPubBytes) return data.NewECDSAPrivateKey(pubKey, ecdsaPrivKeyBytes) }
[ "func", "ECDSAToPrivateKey", "(", "ecdsaPrivKey", "*", "ecdsa", ".", "PrivateKey", ")", "(", "data", ".", "PrivateKey", ",", "error", ")", "{", "ecdsaPubBytes", ",", "err", ":=", "x509", ".", "MarshalPKIXPublicKey", "(", "&", "ecdsaPrivKey", ".", "PublicKey", ...
// ECDSAToPrivateKey converts an ecdsa.Private key to a TUF data.PrivateKey type
[ "ECDSAToPrivateKey", "converts", "an", "ecdsa", ".", "Private", "key", "to", "a", "TUF", "data", ".", "PrivateKey", "type" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L409-L424
train
theupdateframework/notary
tuf/utils/x509.go
ED25519ToPrivateKey
func ED25519ToPrivateKey(privKeyBytes []byte) (data.PrivateKey, error) { if len(privKeyBytes) != ed25519.PublicKeySize+ed25519.PrivateKeySize { return nil, errors.New("malformed ed25519 private key") } pubKey := data.NewED25519PublicKey(privKeyBytes[:ed25519.PublicKeySize]) return data.NewED25519PrivateKey(*pubKey, privKeyBytes) }
go
func ED25519ToPrivateKey(privKeyBytes []byte) (data.PrivateKey, error) { if len(privKeyBytes) != ed25519.PublicKeySize+ed25519.PrivateKeySize { return nil, errors.New("malformed ed25519 private key") } pubKey := data.NewED25519PublicKey(privKeyBytes[:ed25519.PublicKeySize]) return data.NewED25519PrivateKey(*pubKey, privKeyBytes) }
[ "func", "ED25519ToPrivateKey", "(", "privKeyBytes", "[", "]", "byte", ")", "(", "data", ".", "PrivateKey", ",", "error", ")", "{", "if", "len", "(", "privKeyBytes", ")", "!=", "ed25519", ".", "PublicKeySize", "+", "ed25519", ".", "PrivateKeySize", "{", "re...
// ED25519ToPrivateKey converts a serialized ED25519 key to a TUF // data.PrivateKey type
[ "ED25519ToPrivateKey", "converts", "a", "serialized", "ED25519", "key", "to", "a", "TUF", "data", ".", "PrivateKey", "type" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L428-L435
train
theupdateframework/notary
tuf/utils/x509.go
ExtractPrivateKeyAttributes
func ExtractPrivateKeyAttributes(pemBytes []byte) (data.RoleName, data.GUN, error) { return extractPrivateKeyAttributes(pemBytes, notary.FIPSEnabled()) }
go
func ExtractPrivateKeyAttributes(pemBytes []byte) (data.RoleName, data.GUN, error) { return extractPrivateKeyAttributes(pemBytes, notary.FIPSEnabled()) }
[ "func", "ExtractPrivateKeyAttributes", "(", "pemBytes", "[", "]", "byte", ")", "(", "data", ".", "RoleName", ",", "data", ".", "GUN", ",", "error", ")", "{", "return", "extractPrivateKeyAttributes", "(", "pemBytes", ",", "notary", ".", "FIPSEnabled", "(", ")...
// ExtractPrivateKeyAttributes extracts role and gun values from private key bytes
[ "ExtractPrivateKeyAttributes", "extracts", "role", "and", "gun", "values", "from", "private", "key", "bytes" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L438-L440
train
theupdateframework/notary
tuf/utils/x509.go
CertToKey
func CertToKey(cert *x509.Certificate) data.PublicKey { block := pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw} pemdata := pem.EncodeToMemory(&block) switch cert.PublicKeyAlgorithm { case x509.RSA: return data.NewRSAx509PublicKey(pemdata) case x509.ECDSA: return data.NewECDSAx509PublicKey(pemdata) default: logrus.Debugf("Unknown key type parsed from certificate: %v", cert.PublicKeyAlgorithm) return nil } }
go
func CertToKey(cert *x509.Certificate) data.PublicKey { block := pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw} pemdata := pem.EncodeToMemory(&block) switch cert.PublicKeyAlgorithm { case x509.RSA: return data.NewRSAx509PublicKey(pemdata) case x509.ECDSA: return data.NewECDSAx509PublicKey(pemdata) default: logrus.Debugf("Unknown key type parsed from certificate: %v", cert.PublicKeyAlgorithm) return nil } }
[ "func", "CertToKey", "(", "cert", "*", "x509", ".", "Certificate", ")", "data", ".", "PublicKey", "{", "block", ":=", "pem", ".", "Block", "{", "Type", ":", "\"CERTIFICATE\"", ",", "Bytes", ":", "cert", ".", "Raw", "}", "\n", "pemdata", ":=", "pem", ...
// CertToKey transforms a single input certificate into its corresponding // PublicKey
[ "CertToKey", "transforms", "a", "single", "input", "certificate", "into", "its", "corresponding", "PublicKey" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L493-L506
train
theupdateframework/notary
tuf/utils/x509.go
CertsToKeys
func CertsToKeys(leafCerts map[string]*x509.Certificate, intCerts map[string][]*x509.Certificate) map[string]data.PublicKey { keys := make(map[string]data.PublicKey) for id, leafCert := range leafCerts { if key, err := CertBundleToKey(leafCert, intCerts[id]); err == nil { keys[key.ID()] = key } } return keys }
go
func CertsToKeys(leafCerts map[string]*x509.Certificate, intCerts map[string][]*x509.Certificate) map[string]data.PublicKey { keys := make(map[string]data.PublicKey) for id, leafCert := range leafCerts { if key, err := CertBundleToKey(leafCert, intCerts[id]); err == nil { keys[key.ID()] = key } } return keys }
[ "func", "CertsToKeys", "(", "leafCerts", "map", "[", "string", "]", "*", "x509", ".", "Certificate", ",", "intCerts", "map", "[", "string", "]", "[", "]", "*", "x509", ".", "Certificate", ")", "map", "[", "string", "]", "data", ".", "PublicKey", "{", ...
// CertsToKeys transforms each of the input certificate chains into its corresponding // PublicKey
[ "CertsToKeys", "transforms", "each", "of", "the", "input", "certificate", "chains", "into", "its", "corresponding", "PublicKey" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L510-L518
train
theupdateframework/notary
tuf/utils/x509.go
CertBundleToKey
func CertBundleToKey(leafCert *x509.Certificate, intCerts []*x509.Certificate) (data.PublicKey, error) { certBundle := []*x509.Certificate{leafCert} certBundle = append(certBundle, intCerts...) certChainPEM, err := CertChainToPEM(certBundle) if err != nil { return nil, err } var newKey data.PublicKey // Use the leaf cert's public key algorithm for typing switch leafCert.PublicKeyAlgorithm { case x509.RSA: newKey = data.NewRSAx509PublicKey(certChainPEM) case x509.ECDSA: newKey = data.NewECDSAx509PublicKey(certChainPEM) default: logrus.Debugf("Unknown key type parsed from certificate: %v", leafCert.PublicKeyAlgorithm) return nil, x509.ErrUnsupportedAlgorithm } return newKey, nil }
go
func CertBundleToKey(leafCert *x509.Certificate, intCerts []*x509.Certificate) (data.PublicKey, error) { certBundle := []*x509.Certificate{leafCert} certBundle = append(certBundle, intCerts...) certChainPEM, err := CertChainToPEM(certBundle) if err != nil { return nil, err } var newKey data.PublicKey // Use the leaf cert's public key algorithm for typing switch leafCert.PublicKeyAlgorithm { case x509.RSA: newKey = data.NewRSAx509PublicKey(certChainPEM) case x509.ECDSA: newKey = data.NewECDSAx509PublicKey(certChainPEM) default: logrus.Debugf("Unknown key type parsed from certificate: %v", leafCert.PublicKeyAlgorithm) return nil, x509.ErrUnsupportedAlgorithm } return newKey, nil }
[ "func", "CertBundleToKey", "(", "leafCert", "*", "x509", ".", "Certificate", ",", "intCerts", "[", "]", "*", "x509", ".", "Certificate", ")", "(", "data", ".", "PublicKey", ",", "error", ")", "{", "certBundle", ":=", "[", "]", "*", "x509", ".", "Certif...
// CertBundleToKey creates a TUF key from a leaf certs and a list of // intermediates
[ "CertBundleToKey", "creates", "a", "TUF", "key", "from", "a", "leaf", "certs", "and", "a", "list", "of", "intermediates" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L522-L541
train
theupdateframework/notary
tuf/utils/x509.go
NewCertificate
func NewCertificate(commonName string, startTime, endTime time.Time) (*x509.Certificate, error) { serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, fmt.Errorf("failed to generate new certificate: %v", err) } return &x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ CommonName: commonName, }, NotBefore: startTime, NotAfter: endTime, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}, BasicConstraintsValid: true, }, nil }
go
func NewCertificate(commonName string, startTime, endTime time.Time) (*x509.Certificate, error) { serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, fmt.Errorf("failed to generate new certificate: %v", err) } return &x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ CommonName: commonName, }, NotBefore: startTime, NotAfter: endTime, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning}, BasicConstraintsValid: true, }, nil }
[ "func", "NewCertificate", "(", "commonName", "string", ",", "startTime", ",", "endTime", "time", ".", "Time", ")", "(", "*", "x509", ".", "Certificate", ",", "error", ")", "{", "serialNumberLimit", ":=", "new", "(", "big", ".", "Int", ")", ".", "Lsh", ...
// NewCertificate returns an X509 Certificate following a template, given a Common Name and validity interval.
[ "NewCertificate", "returns", "an", "X509", "Certificate", "following", "a", "template", "given", "a", "Common", "Name", "and", "validity", "interval", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/x509.go#L544-L564
train
theupdateframework/notary
client/changelist/changelist.go
Add
func (cl *memChangelist) Add(c Change) error { cl.changes = append(cl.changes, c) return nil }
go
func (cl *memChangelist) Add(c Change) error { cl.changes = append(cl.changes, c) return nil }
[ "func", "(", "cl", "*", "memChangelist", ")", "Add", "(", "c", "Change", ")", "error", "{", "cl", ".", "changes", "=", "append", "(", "cl", ".", "changes", ",", "c", ")", "\n", "return", "nil", "\n", "}" ]
// Add adds a change to the in-memory change list
[ "Add", "adds", "a", "change", "to", "the", "in", "-", "memory", "change", "list" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/changelist.go#L19-L22
train
theupdateframework/notary
client/changelist/changelist.go
Clear
func (cl *memChangelist) Clear(archive string) error { // appending to a nil list initializes it. cl.changes = nil return nil }
go
func (cl *memChangelist) Clear(archive string) error { // appending to a nil list initializes it. cl.changes = nil return nil }
[ "func", "(", "cl", "*", "memChangelist", ")", "Clear", "(", "archive", "string", ")", "error", "{", "cl", ".", "changes", "=", "nil", "\n", "return", "nil", "\n", "}" ]
// Clear empties the changelist file.
[ "Clear", "empties", "the", "changelist", "file", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/changelist.go#L48-L52
train
theupdateframework/notary
client/changelist/changelist.go
Next
func (m *MemChangeListIterator) Next() (item Change, err error) { if m.index >= len(m.collection) { return nil, IteratorBoundsError(m.index) } item = m.collection[m.index] m.index++ return item, err }
go
func (m *MemChangeListIterator) Next() (item Change, err error) { if m.index >= len(m.collection) { return nil, IteratorBoundsError(m.index) } item = m.collection[m.index] m.index++ return item, err }
[ "func", "(", "m", "*", "MemChangeListIterator", ")", "Next", "(", ")", "(", "item", "Change", ",", "err", "error", ")", "{", "if", "m", ".", "index", ">=", "len", "(", "m", ".", "collection", ")", "{", "return", "nil", ",", "IteratorBoundsError", "("...
// Next returns the next Change
[ "Next", "returns", "the", "next", "Change" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/changelist.go#L70-L77
train
theupdateframework/notary
client/changelist/file_changelist.go
NewFileChangelist
func NewFileChangelist(dir string) (*FileChangelist, error) { logrus.Debug("Making dir path: ", dir) err := os.MkdirAll(dir, 0700) if err != nil { return nil, err } return &FileChangelist{dir: dir}, nil }
go
func NewFileChangelist(dir string) (*FileChangelist, error) { logrus.Debug("Making dir path: ", dir) err := os.MkdirAll(dir, 0700) if err != nil { return nil, err } return &FileChangelist{dir: dir}, nil }
[ "func", "NewFileChangelist", "(", "dir", "string", ")", "(", "*", "FileChangelist", ",", "error", ")", "{", "logrus", ".", "Debug", "(", "\"Making dir path: \"", ",", "dir", ")", "\n", "err", ":=", "os", ".", "MkdirAll", "(", "dir", ",", "0700", ")", "...
// NewFileChangelist is a convenience method for returning FileChangeLists
[ "NewFileChangelist", "is", "a", "convenience", "method", "for", "returning", "FileChangeLists" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L22-L29
train
theupdateframework/notary
client/changelist/file_changelist.go
getFileNames
func getFileNames(dirName string) ([]os.FileInfo, error) { var dirListing, fileInfos []os.FileInfo dir, err := os.Open(dirName) if err != nil { return fileInfos, err } defer dir.Close() dirListing, err = dir.Readdir(0) if err != nil { return fileInfos, err } for _, f := range dirListing { if f.IsDir() { continue } fileInfos = append(fileInfos, f) } sort.Sort(fileChanges(fileInfos)) return fileInfos, nil }
go
func getFileNames(dirName string) ([]os.FileInfo, error) { var dirListing, fileInfos []os.FileInfo dir, err := os.Open(dirName) if err != nil { return fileInfos, err } defer dir.Close() dirListing, err = dir.Readdir(0) if err != nil { return fileInfos, err } for _, f := range dirListing { if f.IsDir() { continue } fileInfos = append(fileInfos, f) } sort.Sort(fileChanges(fileInfos)) return fileInfos, nil }
[ "func", "getFileNames", "(", "dirName", "string", ")", "(", "[", "]", "os", ".", "FileInfo", ",", "error", ")", "{", "var", "dirListing", ",", "fileInfos", "[", "]", "os", ".", "FileInfo", "\n", "dir", ",", "err", ":=", "os", ".", "Open", "(", "dir...
// getFileNames reads directory, filtering out child directories
[ "getFileNames", "reads", "directory", "filtering", "out", "child", "directories" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L32-L51
train
theupdateframework/notary
client/changelist/file_changelist.go
unmarshalFile
func unmarshalFile(dirname string, f os.FileInfo) (*TUFChange, error) { c := &TUFChange{} raw, err := ioutil.ReadFile(filepath.Join(dirname, f.Name())) if err != nil { return c, err } err = json.Unmarshal(raw, c) if err != nil { return c, err } return c, nil }
go
func unmarshalFile(dirname string, f os.FileInfo) (*TUFChange, error) { c := &TUFChange{} raw, err := ioutil.ReadFile(filepath.Join(dirname, f.Name())) if err != nil { return c, err } err = json.Unmarshal(raw, c) if err != nil { return c, err } return c, nil }
[ "func", "unmarshalFile", "(", "dirname", "string", ",", "f", "os", ".", "FileInfo", ")", "(", "*", "TUFChange", ",", "error", ")", "{", "c", ":=", "&", "TUFChange", "{", "}", "\n", "raw", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ...
// Read a JSON formatted file from disk; convert to TUFChange struct
[ "Read", "a", "JSON", "formatted", "file", "from", "disk", ";", "convert", "to", "TUFChange", "struct" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L54-L65
train
theupdateframework/notary
client/changelist/file_changelist.go
List
func (cl FileChangelist) List() []Change { var changes []Change fileInfos, err := getFileNames(cl.dir) if err != nil { return changes } for _, f := range fileInfos { c, err := unmarshalFile(cl.dir, f) if err != nil { logrus.Warn(err.Error()) continue } changes = append(changes, c) } return changes }
go
func (cl FileChangelist) List() []Change { var changes []Change fileInfos, err := getFileNames(cl.dir) if err != nil { return changes } for _, f := range fileInfos { c, err := unmarshalFile(cl.dir, f) if err != nil { logrus.Warn(err.Error()) continue } changes = append(changes, c) } return changes }
[ "func", "(", "cl", "FileChangelist", ")", "List", "(", ")", "[", "]", "Change", "{", "var", "changes", "[", "]", "Change", "\n", "fileInfos", ",", "err", ":=", "getFileNames", "(", "cl", ".", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return...
// List returns a list of sorted changes
[ "List", "returns", "a", "list", "of", "sorted", "changes" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L68-L83
train
theupdateframework/notary
client/changelist/file_changelist.go
Add
func (cl FileChangelist) Add(c Change) error { cJSON, err := json.Marshal(c) if err != nil { return err } filename := fmt.Sprintf("%020d_%s.change", time.Now().UnixNano(), uuid.Generate()) return ioutil.WriteFile(filepath.Join(cl.dir, filename), cJSON, 0644) }
go
func (cl FileChangelist) Add(c Change) error { cJSON, err := json.Marshal(c) if err != nil { return err } filename := fmt.Sprintf("%020d_%s.change", time.Now().UnixNano(), uuid.Generate()) return ioutil.WriteFile(filepath.Join(cl.dir, filename), cJSON, 0644) }
[ "func", "(", "cl", "FileChangelist", ")", "Add", "(", "c", "Change", ")", "error", "{", "cJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "filename", ":=", "fm...
// Add adds a change to the file change list
[ "Add", "adds", "a", "change", "to", "the", "file", "change", "list" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L86-L93
train
theupdateframework/notary
client/changelist/file_changelist.go
Clear
func (cl FileChangelist) Clear(archive string) error { dir, err := os.Open(cl.dir) if err != nil { return err } defer dir.Close() files, err := dir.Readdir(0) if err != nil { return err } for _, f := range files { os.Remove(filepath.Join(cl.dir, f.Name())) } return nil }
go
func (cl FileChangelist) Clear(archive string) error { dir, err := os.Open(cl.dir) if err != nil { return err } defer dir.Close() files, err := dir.Readdir(0) if err != nil { return err } for _, f := range files { os.Remove(filepath.Join(cl.dir, f.Name())) } return nil }
[ "func", "(", "cl", "FileChangelist", ")", "Clear", "(", "archive", "string", ")", "error", "{", "dir", ",", "err", ":=", "os", ".", "Open", "(", "cl", ".", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer"...
// Clear clears the change list // N.B. archiving not currently implemented
[ "Clear", "clears", "the", "change", "list", "N", ".", "B", ".", "archiving", "not", "currently", "implemented" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L118-L132
train
theupdateframework/notary
client/changelist/file_changelist.go
NewIterator
func (cl FileChangelist) NewIterator() (ChangeIterator, error) { fileInfos, err := getFileNames(cl.dir) if err != nil { return &FileChangeListIterator{}, err } return &FileChangeListIterator{dirname: cl.dir, collection: fileInfos}, nil }
go
func (cl FileChangelist) NewIterator() (ChangeIterator, error) { fileInfos, err := getFileNames(cl.dir) if err != nil { return &FileChangeListIterator{}, err } return &FileChangeListIterator{dirname: cl.dir, collection: fileInfos}, nil }
[ "func", "(", "cl", "FileChangelist", ")", "NewIterator", "(", ")", "(", "ChangeIterator", ",", "error", ")", "{", "fileInfos", ",", "err", ":=", "getFileNames", "(", "cl", ".", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "FileChange...
// NewIterator creates an iterator from FileChangelist
[ "NewIterator", "creates", "an", "iterator", "from", "FileChangelist" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L146-L152
train
theupdateframework/notary
client/changelist/file_changelist.go
Next
func (m *FileChangeListIterator) Next() (item Change, err error) { if m.index >= len(m.collection) { return nil, IteratorBoundsError(m.index) } f := m.collection[m.index] m.index++ item, err = unmarshalFile(m.dirname, f) return }
go
func (m *FileChangeListIterator) Next() (item Change, err error) { if m.index >= len(m.collection) { return nil, IteratorBoundsError(m.index) } f := m.collection[m.index] m.index++ item, err = unmarshalFile(m.dirname, f) return }
[ "func", "(", "m", "*", "FileChangeListIterator", ")", "Next", "(", ")", "(", "item", "Change", ",", "err", "error", ")", "{", "if", "m", ".", "index", ">=", "len", "(", "m", ".", "collection", ")", "{", "return", "nil", ",", "IteratorBoundsError", "(...
// Next returns the next Change in the FileChangeList
[ "Next", "returns", "the", "next", "Change", "in", "the", "FileChangeList" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L170-L178
train
theupdateframework/notary
client/changelist/file_changelist.go
Less
func (cs fileChanges) Less(i, j int) bool { return cs[i].Name() < cs[j].Name() }
go
func (cs fileChanges) Less(i, j int) bool { return cs[i].Name() < cs[j].Name() }
[ "func", "(", "cs", "fileChanges", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "cs", "[", "i", "]", ".", "Name", "(", ")", "<", "cs", "[", "j", "]", ".", "Name", "(", ")", "\n", "}" ]
// Less compares the names of two different file changes
[ "Less", "compares", "the", "names", "of", "two", "different", "file", "changes" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L193-L195
train
theupdateframework/notary
client/changelist/file_changelist.go
Swap
func (cs fileChanges) Swap(i, j int) { tmp := cs[i] cs[i] = cs[j] cs[j] = tmp }
go
func (cs fileChanges) Swap(i, j int) { tmp := cs[i] cs[i] = cs[j] cs[j] = tmp }
[ "func", "(", "cs", "fileChanges", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "tmp", ":=", "cs", "[", "i", "]", "\n", "cs", "[", "i", "]", "=", "cs", "[", "j", "]", "\n", "cs", "[", "j", "]", "=", "tmp", "\n", "}" ]
// Swap swaps the position of two file changes
[ "Swap", "swaps", "the", "position", "of", "two", "file", "changes" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L198-L202
train
theupdateframework/notary
trustmanager/remoteks/server.go
Set
func (s *GRPCStorage) Set(ctx context.Context, msg *SetMsg) (*google_protobuf.Empty, error) { logrus.Debugf("storing: %s", msg.FileName) err := s.backend.Set(msg.FileName, msg.Data) if err != nil { logrus.Errorf("failed to store: %s", err.Error()) } return &google_protobuf.Empty{}, err }
go
func (s *GRPCStorage) Set(ctx context.Context, msg *SetMsg) (*google_protobuf.Empty, error) { logrus.Debugf("storing: %s", msg.FileName) err := s.backend.Set(msg.FileName, msg.Data) if err != nil { logrus.Errorf("failed to store: %s", err.Error()) } return &google_protobuf.Empty{}, err }
[ "func", "(", "s", "*", "GRPCStorage", ")", "Set", "(", "ctx", "context", ".", "Context", ",", "msg", "*", "SetMsg", ")", "(", "*", "google_protobuf", ".", "Empty", ",", "error", ")", "{", "logrus", ".", "Debugf", "(", "\"storing: %s\"", ",", "msg", "...
// Set writes the provided data under the given identifier.
[ "Set", "writes", "the", "provided", "data", "under", "the", "given", "identifier", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/server.go#L27-L34
train
theupdateframework/notary
trustmanager/remoteks/server.go
Remove
func (s *GRPCStorage) Remove(ctx context.Context, fn *FileNameMsg) (*google_protobuf.Empty, error) { return &google_protobuf.Empty{}, s.backend.Remove(fn.FileName) }
go
func (s *GRPCStorage) Remove(ctx context.Context, fn *FileNameMsg) (*google_protobuf.Empty, error) { return &google_protobuf.Empty{}, s.backend.Remove(fn.FileName) }
[ "func", "(", "s", "*", "GRPCStorage", ")", "Remove", "(", "ctx", "context", ".", "Context", ",", "fn", "*", "FileNameMsg", ")", "(", "*", "google_protobuf", ".", "Empty", ",", "error", ")", "{", "return", "&", "google_protobuf", ".", "Empty", "{", "}",...
// Remove deletes the data associated with the provided identifier.
[ "Remove", "deletes", "the", "data", "associated", "with", "the", "provided", "identifier", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/server.go#L37-L39
train
theupdateframework/notary
trustmanager/remoteks/server.go
Get
func (s *GRPCStorage) Get(ctx context.Context, fn *FileNameMsg) (*ByteMsg, error) { data, err := s.backend.Get(fn.FileName) if err != nil { return &ByteMsg{}, err } return &ByteMsg{Data: data}, nil }
go
func (s *GRPCStorage) Get(ctx context.Context, fn *FileNameMsg) (*ByteMsg, error) { data, err := s.backend.Get(fn.FileName) if err != nil { return &ByteMsg{}, err } return &ByteMsg{Data: data}, nil }
[ "func", "(", "s", "*", "GRPCStorage", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "fn", "*", "FileNameMsg", ")", "(", "*", "ByteMsg", ",", "error", ")", "{", "data", ",", "err", ":=", "s", ".", "backend", ".", "Get", "(", "fn", ".", ...
// Get returns the data associated with the provided identifier.
[ "Get", "returns", "the", "data", "associated", "with", "the", "provided", "identifier", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/server.go#L42-L48
train
theupdateframework/notary
trustmanager/remoteks/server.go
ListFiles
func (s *GRPCStorage) ListFiles(ctx context.Context, _ *google_protobuf.Empty) (*StringListMsg, error) { lst := s.backend.ListFiles() logrus.Debugf("found %d keys", len(lst)) return &StringListMsg{ FileNames: lst, }, nil }
go
func (s *GRPCStorage) ListFiles(ctx context.Context, _ *google_protobuf.Empty) (*StringListMsg, error) { lst := s.backend.ListFiles() logrus.Debugf("found %d keys", len(lst)) return &StringListMsg{ FileNames: lst, }, nil }
[ "func", "(", "s", "*", "GRPCStorage", ")", "ListFiles", "(", "ctx", "context", ".", "Context", ",", "_", "*", "google_protobuf", ".", "Empty", ")", "(", "*", "StringListMsg", ",", "error", ")", "{", "lst", ":=", "s", ".", "backend", ".", "ListFiles", ...
// ListFiles returns all known identifiers in the storage backend.
[ "ListFiles", "returns", "all", "known", "identifiers", "in", "the", "storage", "backend", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/server.go#L51-L57
train
theupdateframework/notary
tuf/data/types.go
MetadataRoleMapToStringMap
func MetadataRoleMapToStringMap(roles map[RoleName][]byte) map[string][]byte { metadata := make(map[string][]byte) for k, v := range roles { metadata[k.String()] = v } return metadata }
go
func MetadataRoleMapToStringMap(roles map[RoleName][]byte) map[string][]byte { metadata := make(map[string][]byte) for k, v := range roles { metadata[k.String()] = v } return metadata }
[ "func", "MetadataRoleMapToStringMap", "(", "roles", "map", "[", "RoleName", "]", "[", "]", "byte", ")", "map", "[", "string", "]", "[", "]", "byte", "{", "metadata", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "byte", ")", "\n", "for", ...
// MetadataRoleMapToStringMap generates a map string of bytes from a map RoleName of bytes
[ "MetadataRoleMapToStringMap", "generates", "a", "map", "string", "of", "bytes", "from", "a", "map", "RoleName", "of", "bytes" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L44-L50
train
theupdateframework/notary
tuf/data/types.go
NewRoleList
func NewRoleList(roles []string) []RoleName { var roleNames []RoleName for _, role := range roles { roleNames = append(roleNames, RoleName(role)) } return roleNames }
go
func NewRoleList(roles []string) []RoleName { var roleNames []RoleName for _, role := range roles { roleNames = append(roleNames, RoleName(role)) } return roleNames }
[ "func", "NewRoleList", "(", "roles", "[", "]", "string", ")", "[", "]", "RoleName", "{", "var", "roleNames", "[", "]", "RoleName", "\n", "for", "_", ",", "role", ":=", "range", "roles", "{", "roleNames", "=", "append", "(", "roleNames", ",", "RoleName"...
// NewRoleList generates an array of RoleName objects from a slice of strings
[ "NewRoleList", "generates", "an", "array", "of", "RoleName", "objects", "from", "a", "slice", "of", "strings" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L53-L59
train
theupdateframework/notary
tuf/data/types.go
RolesListToStringList
func RolesListToStringList(roles []RoleName) []string { var roleNames []string for _, role := range roles { roleNames = append(roleNames, role.String()) } return roleNames }
go
func RolesListToStringList(roles []RoleName) []string { var roleNames []string for _, role := range roles { roleNames = append(roleNames, role.String()) } return roleNames }
[ "func", "RolesListToStringList", "(", "roles", "[", "]", "RoleName", ")", "[", "]", "string", "{", "var", "roleNames", "[", "]", "string", "\n", "for", "_", ",", "role", ":=", "range", "roles", "{", "roleNames", "=", "append", "(", "roleNames", ",", "r...
// RolesListToStringList generates an array of string objects from a slice of roles
[ "RolesListToStringList", "generates", "an", "array", "of", "string", "objects", "from", "a", "slice", "of", "roles" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L62-L68
train
theupdateframework/notary
tuf/data/types.go
ValidTUFType
func ValidTUFType(typ string, role RoleName) bool { if ValidRole(role) { // All targets delegation roles must have // the valid type is for targets. if role == "" { // role is unknown and does not map to // a type return false } if strings.HasPrefix(role.String(), CanonicalTargetsRole.String()+"/") { role = CanonicalTargetsRole } } // most people will just use the defaults so have this optimal check // first. Do comparison just in case there is some unknown vulnerability // if a key and value in the map differ. if v, ok := TUFTypes[role]; ok { return typ == v } return false }
go
func ValidTUFType(typ string, role RoleName) bool { if ValidRole(role) { // All targets delegation roles must have // the valid type is for targets. if role == "" { // role is unknown and does not map to // a type return false } if strings.HasPrefix(role.String(), CanonicalTargetsRole.String()+"/") { role = CanonicalTargetsRole } } // most people will just use the defaults so have this optimal check // first. Do comparison just in case there is some unknown vulnerability // if a key and value in the map differ. if v, ok := TUFTypes[role]; ok { return typ == v } return false }
[ "func", "ValidTUFType", "(", "typ", "string", ",", "role", "RoleName", ")", "bool", "{", "if", "ValidRole", "(", "role", ")", "{", "if", "role", "==", "\"\"", "{", "return", "false", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "role", "....
// ValidTUFType checks if the given type is valid for the role
[ "ValidTUFType", "checks", "if", "the", "given", "type", "is", "valid", "for", "the", "role" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L115-L135
train
theupdateframework/notary
tuf/data/types.go
Equals
func (f FileMeta) Equals(o FileMeta) bool { if o.Length != f.Length || len(f.Hashes) != len(f.Hashes) { return false } if f.Custom == nil && o.Custom != nil || f.Custom != nil && o.Custom == nil { return false } // we don't care if these are valid hashes, just that they are equal for key, val := range f.Hashes { if !bytes.Equal(val, o.Hashes[key]) { return false } } if f.Custom == nil && o.Custom == nil { return true } fBytes, err := f.Custom.MarshalJSON() if err != nil { return false } oBytes, err := o.Custom.MarshalJSON() if err != nil { return false } return bytes.Equal(fBytes, oBytes) }
go
func (f FileMeta) Equals(o FileMeta) bool { if o.Length != f.Length || len(f.Hashes) != len(f.Hashes) { return false } if f.Custom == nil && o.Custom != nil || f.Custom != nil && o.Custom == nil { return false } // we don't care if these are valid hashes, just that they are equal for key, val := range f.Hashes { if !bytes.Equal(val, o.Hashes[key]) { return false } } if f.Custom == nil && o.Custom == nil { return true } fBytes, err := f.Custom.MarshalJSON() if err != nil { return false } oBytes, err := o.Custom.MarshalJSON() if err != nil { return false } return bytes.Equal(fBytes, oBytes) }
[ "func", "(", "f", "FileMeta", ")", "Equals", "(", "o", "FileMeta", ")", "bool", "{", "if", "o", ".", "Length", "!=", "f", ".", "Length", "||", "len", "(", "f", ".", "Hashes", ")", "!=", "len", "(", "f", ".", "Hashes", ")", "{", "return", "false...
// Equals returns true if the other FileMeta object is equivalent to this one
[ "Equals", "returns", "true", "if", "the", "other", "FileMeta", "object", "is", "equivalent", "to", "this", "one" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L188-L213
train
theupdateframework/notary
tuf/data/types.go
CheckHashes
func CheckHashes(payload []byte, name string, hashes Hashes) error { cnt := 0 // k, v indicate the hash algorithm and the corresponding value for k, v := range hashes { switch k { case notary.SHA256: checksum := sha256.Sum256(payload) if subtle.ConstantTimeCompare(checksum[:], v) == 0 { return ErrMismatchedChecksum{alg: notary.SHA256, name: name, expected: hex.EncodeToString(v)} } cnt++ case notary.SHA512: checksum := sha512.Sum512(payload) if subtle.ConstantTimeCompare(checksum[:], v) == 0 { return ErrMismatchedChecksum{alg: notary.SHA512, name: name, expected: hex.EncodeToString(v)} } cnt++ } } if cnt == 0 { return ErrMissingMeta{Role: name} } return nil }
go
func CheckHashes(payload []byte, name string, hashes Hashes) error { cnt := 0 // k, v indicate the hash algorithm and the corresponding value for k, v := range hashes { switch k { case notary.SHA256: checksum := sha256.Sum256(payload) if subtle.ConstantTimeCompare(checksum[:], v) == 0 { return ErrMismatchedChecksum{alg: notary.SHA256, name: name, expected: hex.EncodeToString(v)} } cnt++ case notary.SHA512: checksum := sha512.Sum512(payload) if subtle.ConstantTimeCompare(checksum[:], v) == 0 { return ErrMismatchedChecksum{alg: notary.SHA512, name: name, expected: hex.EncodeToString(v)} } cnt++ } } if cnt == 0 { return ErrMissingMeta{Role: name} } return nil }
[ "func", "CheckHashes", "(", "payload", "[", "]", "byte", ",", "name", "string", ",", "hashes", "Hashes", ")", "error", "{", "cnt", ":=", "0", "\n", "for", "k", ",", "v", ":=", "range", "hashes", "{", "switch", "k", "{", "case", "notary", ".", "SHA2...
// CheckHashes verifies all the checksums specified by the "hashes" of the payload.
[ "CheckHashes", "verifies", "all", "the", "checksums", "specified", "by", "the", "hashes", "of", "the", "payload", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L216-L242
train
theupdateframework/notary
tuf/data/types.go
CompareMultiHashes
func CompareMultiHashes(hashes1, hashes2 Hashes) error { // First check if the two hash structures are valid if err := CheckValidHashStructures(hashes1); err != nil { return err } if err := CheckValidHashStructures(hashes2); err != nil { return err } // Check if they have at least one matching hash, and no conflicts cnt := 0 for hashAlg, hash1 := range hashes1 { hash2, ok := hashes2[hashAlg] if !ok { continue } if subtle.ConstantTimeCompare(hash1[:], hash2[:]) == 0 { return fmt.Errorf("mismatched %s checksum", hashAlg) } // If we reached here, we had a match cnt++ } if cnt == 0 { return fmt.Errorf("at least one matching hash needed") } return nil }
go
func CompareMultiHashes(hashes1, hashes2 Hashes) error { // First check if the two hash structures are valid if err := CheckValidHashStructures(hashes1); err != nil { return err } if err := CheckValidHashStructures(hashes2); err != nil { return err } // Check if they have at least one matching hash, and no conflicts cnt := 0 for hashAlg, hash1 := range hashes1 { hash2, ok := hashes2[hashAlg] if !ok { continue } if subtle.ConstantTimeCompare(hash1[:], hash2[:]) == 0 { return fmt.Errorf("mismatched %s checksum", hashAlg) } // If we reached here, we had a match cnt++ } if cnt == 0 { return fmt.Errorf("at least one matching hash needed") } return nil }
[ "func", "CompareMultiHashes", "(", "hashes1", ",", "hashes2", "Hashes", ")", "error", "{", "if", "err", ":=", "CheckValidHashStructures", "(", "hashes1", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "CheckValidHas...
// CompareMultiHashes verifies that the two Hashes passed in can represent the same data. // This means that both maps must have at least one key defined for which they map, and no conflicts. // Note that we check the intersection of map keys, which adds support for non-default hash algorithms in notary
[ "CompareMultiHashes", "verifies", "that", "the", "two", "Hashes", "passed", "in", "can", "represent", "the", "same", "data", ".", "This", "means", "that", "both", "maps", "must", "have", "at", "least", "one", "key", "defined", "for", "which", "they", "map", ...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L247-L276
train
theupdateframework/notary
tuf/data/types.go
CheckValidHashStructures
func CheckValidHashStructures(hashes Hashes) error { cnt := 0 for k, v := range hashes { switch k { case notary.SHA256: if len(v) != sha256.Size { return ErrInvalidChecksum{alg: notary.SHA256} } cnt++ case notary.SHA512: if len(v) != sha512.Size { return ErrInvalidChecksum{alg: notary.SHA512} } cnt++ } } if cnt == 0 { return fmt.Errorf("at least one supported hash needed") } return nil }
go
func CheckValidHashStructures(hashes Hashes) error { cnt := 0 for k, v := range hashes { switch k { case notary.SHA256: if len(v) != sha256.Size { return ErrInvalidChecksum{alg: notary.SHA256} } cnt++ case notary.SHA512: if len(v) != sha512.Size { return ErrInvalidChecksum{alg: notary.SHA512} } cnt++ } } if cnt == 0 { return fmt.Errorf("at least one supported hash needed") } return nil }
[ "func", "CheckValidHashStructures", "(", "hashes", "Hashes", ")", "error", "{", "cnt", ":=", "0", "\n", "for", "k", ",", "v", ":=", "range", "hashes", "{", "switch", "k", "{", "case", "notary", ".", "SHA256", ":", "if", "len", "(", "v", ")", "!=", ...
// CheckValidHashStructures returns an error, or nil, depending on whether // the content of the hashes is valid or not.
[ "CheckValidHashStructures", "returns", "an", "error", "or", "nil", "depending", "on", "whether", "the", "content", "of", "the", "hashes", "is", "valid", "or", "not", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L280-L303
train
theupdateframework/notary
tuf/data/types.go
NewFileMeta
func NewFileMeta(r io.Reader, hashAlgorithms ...string) (FileMeta, error) { if len(hashAlgorithms) == 0 { hashAlgorithms = []string{defaultHashAlgorithm} } hashes := make(map[string]hash.Hash, len(hashAlgorithms)) for _, hashAlgorithm := range hashAlgorithms { var h hash.Hash switch hashAlgorithm { case notary.SHA256: h = sha256.New() case notary.SHA512: h = sha512.New() default: return FileMeta{}, fmt.Errorf("Unknown hash algorithm: %s", hashAlgorithm) } hashes[hashAlgorithm] = h r = io.TeeReader(r, h) } n, err := io.Copy(ioutil.Discard, r) if err != nil { return FileMeta{}, err } m := FileMeta{Length: n, Hashes: make(Hashes, len(hashes))} for hashAlgorithm, h := range hashes { m.Hashes[hashAlgorithm] = h.Sum(nil) } return m, nil }
go
func NewFileMeta(r io.Reader, hashAlgorithms ...string) (FileMeta, error) { if len(hashAlgorithms) == 0 { hashAlgorithms = []string{defaultHashAlgorithm} } hashes := make(map[string]hash.Hash, len(hashAlgorithms)) for _, hashAlgorithm := range hashAlgorithms { var h hash.Hash switch hashAlgorithm { case notary.SHA256: h = sha256.New() case notary.SHA512: h = sha512.New() default: return FileMeta{}, fmt.Errorf("Unknown hash algorithm: %s", hashAlgorithm) } hashes[hashAlgorithm] = h r = io.TeeReader(r, h) } n, err := io.Copy(ioutil.Discard, r) if err != nil { return FileMeta{}, err } m := FileMeta{Length: n, Hashes: make(Hashes, len(hashes))} for hashAlgorithm, h := range hashes { m.Hashes[hashAlgorithm] = h.Sum(nil) } return m, nil }
[ "func", "NewFileMeta", "(", "r", "io", ".", "Reader", ",", "hashAlgorithms", "...", "string", ")", "(", "FileMeta", ",", "error", ")", "{", "if", "len", "(", "hashAlgorithms", ")", "==", "0", "{", "hashAlgorithms", "=", "[", "]", "string", "{", "defaul...
// NewFileMeta generates a FileMeta object from the reader, using the // hash algorithms provided
[ "NewFileMeta", "generates", "a", "FileMeta", "object", "from", "the", "reader", "using", "the", "hash", "algorithms", "provided" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L307-L334
train
theupdateframework/notary
tuf/data/types.go
NewDelegations
func NewDelegations() *Delegations { return &Delegations{ Keys: make(map[string]PublicKey), Roles: make([]*Role, 0), } }
go
func NewDelegations() *Delegations { return &Delegations{ Keys: make(map[string]PublicKey), Roles: make([]*Role, 0), } }
[ "func", "NewDelegations", "(", ")", "*", "Delegations", "{", "return", "&", "Delegations", "{", "Keys", ":", "make", "(", "map", "[", "string", "]", "PublicKey", ")", ",", "Roles", ":", "make", "(", "[", "]", "*", "Role", ",", "0", ")", ",", "}", ...
// NewDelegations initializes an empty Delegations object
[ "NewDelegations", "initializes", "an", "empty", "Delegations", "object" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L343-L348
train
theupdateframework/notary
tuf/data/types.go
SetDefaultExpiryTimes
func SetDefaultExpiryTimes(times map[RoleName]time.Duration) { for key, value := range times { if _, ok := defaultExpiryTimes[key]; !ok { logrus.Errorf("Attempted to set default expiry for an unknown role: %s", key.String()) continue } defaultExpiryTimes[key] = value } }
go
func SetDefaultExpiryTimes(times map[RoleName]time.Duration) { for key, value := range times { if _, ok := defaultExpiryTimes[key]; !ok { logrus.Errorf("Attempted to set default expiry for an unknown role: %s", key.String()) continue } defaultExpiryTimes[key] = value } }
[ "func", "SetDefaultExpiryTimes", "(", "times", "map", "[", "RoleName", "]", "time", ".", "Duration", ")", "{", "for", "key", ",", "value", ":=", "range", "times", "{", "if", "_", ",", "ok", ":=", "defaultExpiryTimes", "[", "key", "]", ";", "!", "ok", ...
// SetDefaultExpiryTimes allows one to change the default expiries.
[ "SetDefaultExpiryTimes", "allows", "one", "to", "change", "the", "default", "expiries", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L359-L367
train
theupdateframework/notary
tuf/data/types.go
DefaultExpires
func DefaultExpires(role RoleName) time.Time { if d, ok := defaultExpiryTimes[role]; ok { return time.Now().Add(d) } var t time.Time return t.UTC().Round(time.Second) }
go
func DefaultExpires(role RoleName) time.Time { if d, ok := defaultExpiryTimes[role]; ok { return time.Now().Add(d) } var t time.Time return t.UTC().Round(time.Second) }
[ "func", "DefaultExpires", "(", "role", "RoleName", ")", "time", ".", "Time", "{", "if", "d", ",", "ok", ":=", "defaultExpiryTimes", "[", "role", "]", ";", "ok", "{", "return", "time", ".", "Now", "(", ")", ".", "Add", "(", "d", ")", "\n", "}", "\...
// DefaultExpires gets the default expiry time for the given role
[ "DefaultExpires", "gets", "the", "default", "expiry", "time", "for", "the", "given", "role" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L370-L376
train
theupdateframework/notary
tuf/data/types.go
UnmarshalJSON
func (s *Signature) UnmarshalJSON(data []byte) error { uSignature := unmarshalledSignature{} err := json.Unmarshal(data, &uSignature) if err != nil { return err } uSignature.Method = SigAlgorithm(strings.ToLower(string(uSignature.Method))) *s = Signature(uSignature) return nil }
go
func (s *Signature) UnmarshalJSON(data []byte) error { uSignature := unmarshalledSignature{} err := json.Unmarshal(data, &uSignature) if err != nil { return err } uSignature.Method = SigAlgorithm(strings.ToLower(string(uSignature.Method))) *s = Signature(uSignature) return nil }
[ "func", "(", "s", "*", "Signature", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "uSignature", ":=", "unmarshalledSignature", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "uSignature", ")", "\...
// UnmarshalJSON does a custom unmarshalling of the signature JSON
[ "UnmarshalJSON", "does", "a", "custom", "unmarshalling", "of", "the", "signature", "JSON" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L381-L390
train
theupdateframework/notary
cryptoservice/crypto_service.go
Create
func (cs *CryptoService) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) { if algorithm == data.RSAKey { return nil, fmt.Errorf("%s keys can only be imported", data.RSAKey) } privKey, err := utils.GenerateKey(algorithm) if err != nil { return nil, fmt.Errorf("failed to generate %s key: %v", algorithm, err) } logrus.Debugf("generated new %s key for role: %s and keyID: %s", algorithm, role.String(), privKey.ID()) pubKey := data.PublicKeyFromPrivate(privKey) return pubKey, cs.AddKey(role, gun, privKey) }
go
func (cs *CryptoService) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) { if algorithm == data.RSAKey { return nil, fmt.Errorf("%s keys can only be imported", data.RSAKey) } privKey, err := utils.GenerateKey(algorithm) if err != nil { return nil, fmt.Errorf("failed to generate %s key: %v", algorithm, err) } logrus.Debugf("generated new %s key for role: %s and keyID: %s", algorithm, role.String(), privKey.ID()) pubKey := data.PublicKeyFromPrivate(privKey) return pubKey, cs.AddKey(role, gun, privKey) }
[ "func", "(", "cs", "*", "CryptoService", ")", "Create", "(", "role", "data", ".", "RoleName", ",", "gun", "data", ".", "GUN", ",", "algorithm", "string", ")", "(", "data", ".", "PublicKey", ",", "error", ")", "{", "if", "algorithm", "==", "data", "."...
// Create is used to generate keys for targets, snapshots and timestamps
[ "Create", "is", "used", "to", "generate", "keys", "for", "targets", "snapshots", "and", "timestamps" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L41-L54
train
theupdateframework/notary
cryptoservice/crypto_service.go
GetPrivateKey
func (cs *CryptoService) GetPrivateKey(keyID string) (k data.PrivateKey, role data.RoleName, err error) { for _, ks := range cs.keyStores { if k, role, err = ks.GetKey(keyID); err == nil { return } switch err.(type) { case trustmanager.ErrPasswordInvalid, trustmanager.ErrAttemptsExceeded: return default: continue } } return // returns whatever the final values were }
go
func (cs *CryptoService) GetPrivateKey(keyID string) (k data.PrivateKey, role data.RoleName, err error) { for _, ks := range cs.keyStores { if k, role, err = ks.GetKey(keyID); err == nil { return } switch err.(type) { case trustmanager.ErrPasswordInvalid, trustmanager.ErrAttemptsExceeded: return default: continue } } return // returns whatever the final values were }
[ "func", "(", "cs", "*", "CryptoService", ")", "GetPrivateKey", "(", "keyID", "string", ")", "(", "k", "data", ".", "PrivateKey", ",", "role", "data", ".", "RoleName", ",", "err", "error", ")", "{", "for", "_", ",", "ks", ":=", "range", "cs", ".", "...
// GetPrivateKey returns a private key and role if present by ID.
[ "GetPrivateKey", "returns", "a", "private", "key", "and", "role", "if", "present", "by", "ID", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L57-L70
train
theupdateframework/notary
cryptoservice/crypto_service.go
GetKey
func (cs *CryptoService) GetKey(keyID string) data.PublicKey { privKey, _, err := cs.GetPrivateKey(keyID) if err != nil { return nil } return data.PublicKeyFromPrivate(privKey) }
go
func (cs *CryptoService) GetKey(keyID string) data.PublicKey { privKey, _, err := cs.GetPrivateKey(keyID) if err != nil { return nil } return data.PublicKeyFromPrivate(privKey) }
[ "func", "(", "cs", "*", "CryptoService", ")", "GetKey", "(", "keyID", "string", ")", "data", ".", "PublicKey", "{", "privKey", ",", "_", ",", "err", ":=", "cs", ".", "GetPrivateKey", "(", "keyID", ")", "\n", "if", "err", "!=", "nil", "{", "return", ...
// GetKey returns a key by ID
[ "GetKey", "returns", "a", "key", "by", "ID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L73-L79
train
theupdateframework/notary
cryptoservice/crypto_service.go
GetKeyInfo
func (cs *CryptoService) GetKeyInfo(keyID string) (trustmanager.KeyInfo, error) { for _, store := range cs.keyStores { if info, err := store.GetKeyInfo(keyID); err == nil { return info, nil } } return trustmanager.KeyInfo{}, fmt.Errorf("Could not find info for keyID %s", keyID) }
go
func (cs *CryptoService) GetKeyInfo(keyID string) (trustmanager.KeyInfo, error) { for _, store := range cs.keyStores { if info, err := store.GetKeyInfo(keyID); err == nil { return info, nil } } return trustmanager.KeyInfo{}, fmt.Errorf("Could not find info for keyID %s", keyID) }
[ "func", "(", "cs", "*", "CryptoService", ")", "GetKeyInfo", "(", "keyID", "string", ")", "(", "trustmanager", ".", "KeyInfo", ",", "error", ")", "{", "for", "_", ",", "store", ":=", "range", "cs", ".", "keyStores", "{", "if", "info", ",", "err", ":="...
// GetKeyInfo returns role and GUN info of a key by ID
[ "GetKeyInfo", "returns", "role", "and", "GUN", "info", "of", "a", "key", "by", "ID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L82-L89
train
theupdateframework/notary
cryptoservice/crypto_service.go
RemoveKey
func (cs *CryptoService) RemoveKey(keyID string) (err error) { for _, ks := range cs.keyStores { ks.RemoveKey(keyID) } return // returns whatever the final values were }
go
func (cs *CryptoService) RemoveKey(keyID string) (err error) { for _, ks := range cs.keyStores { ks.RemoveKey(keyID) } return // returns whatever the final values were }
[ "func", "(", "cs", "*", "CryptoService", ")", "RemoveKey", "(", "keyID", "string", ")", "(", "err", "error", ")", "{", "for", "_", ",", "ks", ":=", "range", "cs", ".", "keyStores", "{", "ks", ".", "RemoveKey", "(", "keyID", ")", "\n", "}", "\n", ...
// RemoveKey deletes a key by ID
[ "RemoveKey", "deletes", "a", "key", "by", "ID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L92-L97
train
theupdateframework/notary
cryptoservice/crypto_service.go
AddKey
func (cs *CryptoService) AddKey(role data.RoleName, gun data.GUN, key data.PrivateKey) (err error) { // First check if this key already exists in any of our keystores for _, ks := range cs.keyStores { if keyInfo, err := ks.GetKeyInfo(key.ID()); err == nil { if keyInfo.Role != role { return fmt.Errorf("key with same ID already exists for role: %s", keyInfo.Role.String()) } logrus.Debugf("key with same ID %s and role %s already exists", key.ID(), keyInfo.Role.String()) return nil } } // If the key didn't exist in any of our keystores, add and return on the first successful keystore for _, ks := range cs.keyStores { // Try to add to this keystore, return if successful if err = ks.AddKey(trustmanager.KeyInfo{Role: role, Gun: gun}, key); err == nil { return nil } } return // returns whatever the final values were }
go
func (cs *CryptoService) AddKey(role data.RoleName, gun data.GUN, key data.PrivateKey) (err error) { // First check if this key already exists in any of our keystores for _, ks := range cs.keyStores { if keyInfo, err := ks.GetKeyInfo(key.ID()); err == nil { if keyInfo.Role != role { return fmt.Errorf("key with same ID already exists for role: %s", keyInfo.Role.String()) } logrus.Debugf("key with same ID %s and role %s already exists", key.ID(), keyInfo.Role.String()) return nil } } // If the key didn't exist in any of our keystores, add and return on the first successful keystore for _, ks := range cs.keyStores { // Try to add to this keystore, return if successful if err = ks.AddKey(trustmanager.KeyInfo{Role: role, Gun: gun}, key); err == nil { return nil } } return // returns whatever the final values were }
[ "func", "(", "cs", "*", "CryptoService", ")", "AddKey", "(", "role", "data", ".", "RoleName", ",", "gun", "data", ".", "GUN", ",", "key", "data", ".", "PrivateKey", ")", "(", "err", "error", ")", "{", "for", "_", ",", "ks", ":=", "range", "cs", "...
// AddKey adds a private key to a specified role. // The GUN is inferred from the cryptoservice itself for non-root roles
[ "AddKey", "adds", "a", "private", "key", "to", "a", "specified", "role", ".", "The", "GUN", "is", "inferred", "from", "the", "cryptoservice", "itself", "for", "non", "-", "root", "roles" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L101-L120
train
theupdateframework/notary
cryptoservice/crypto_service.go
ListKeys
func (cs *CryptoService) ListKeys(role data.RoleName) []string { var res []string for _, ks := range cs.keyStores { for k, r := range ks.ListKeys() { if r.Role == role { res = append(res, k) } } } return res }
go
func (cs *CryptoService) ListKeys(role data.RoleName) []string { var res []string for _, ks := range cs.keyStores { for k, r := range ks.ListKeys() { if r.Role == role { res = append(res, k) } } } return res }
[ "func", "(", "cs", "*", "CryptoService", ")", "ListKeys", "(", "role", "data", ".", "RoleName", ")", "[", "]", "string", "{", "var", "res", "[", "]", "string", "\n", "for", "_", ",", "ks", ":=", "range", "cs", ".", "keyStores", "{", "for", "k", "...
// ListKeys returns a list of key IDs valid for the given role
[ "ListKeys", "returns", "a", "list", "of", "key", "IDs", "valid", "for", "the", "given", "role" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L123-L133
train
theupdateframework/notary
cryptoservice/crypto_service.go
ListAllKeys
func (cs *CryptoService) ListAllKeys() map[string]data.RoleName { res := make(map[string]data.RoleName) for _, ks := range cs.keyStores { for k, r := range ks.ListKeys() { res[k] = r.Role // keys are content addressed so don't care about overwrites } } return res }
go
func (cs *CryptoService) ListAllKeys() map[string]data.RoleName { res := make(map[string]data.RoleName) for _, ks := range cs.keyStores { for k, r := range ks.ListKeys() { res[k] = r.Role // keys are content addressed so don't care about overwrites } } return res }
[ "func", "(", "cs", "*", "CryptoService", ")", "ListAllKeys", "(", ")", "map", "[", "string", "]", "data", ".", "RoleName", "{", "res", ":=", "make", "(", "map", "[", "string", "]", "data", ".", "RoleName", ")", "\n", "for", "_", ",", "ks", ":=", ...
// ListAllKeys returns a map of key IDs to role
[ "ListAllKeys", "returns", "a", "map", "of", "key", "IDs", "to", "role" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L136-L144
train
theupdateframework/notary
cryptoservice/crypto_service.go
CheckRootKeyIsEncrypted
func CheckRootKeyIsEncrypted(pemBytes []byte) error { block, _ := pem.Decode(pemBytes) if block == nil { return ErrNoValidPrivateKey } if block.Type == "ENCRYPTED PRIVATE KEY" { return nil } if !notary.FIPSEnabled() && x509.IsEncryptedPEMBlock(block) { return nil } return ErrRootKeyNotEncrypted }
go
func CheckRootKeyIsEncrypted(pemBytes []byte) error { block, _ := pem.Decode(pemBytes) if block == nil { return ErrNoValidPrivateKey } if block.Type == "ENCRYPTED PRIVATE KEY" { return nil } if !notary.FIPSEnabled() && x509.IsEncryptedPEMBlock(block) { return nil } return ErrRootKeyNotEncrypted }
[ "func", "CheckRootKeyIsEncrypted", "(", "pemBytes", "[", "]", "byte", ")", "error", "{", "block", ",", "_", ":=", "pem", ".", "Decode", "(", "pemBytes", ")", "\n", "if", "block", "==", "nil", "{", "return", "ErrNoValidPrivateKey", "\n", "}", "\n", "if", ...
// CheckRootKeyIsEncrypted makes sure the root key is encrypted. We have // internal assumptions that depend on this.
[ "CheckRootKeyIsEncrypted", "makes", "sure", "the", "root", "key", "is", "encrypted", ".", "We", "have", "internal", "assumptions", "that", "depend", "on", "this", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L148-L162
train
theupdateframework/notary
signer/api/rpc_api.go
CreateKey
func (s *KeyManagementServer) CreateKey(ctx context.Context, req *pb.CreateKeyRequest) (*pb.PublicKey, error) { service := s.CryptoServices[req.Algorithm] logger := ctxu.GetLogger(ctx) if service == nil { logger.Error("CreateKey: unsupported algorithm: ", req.Algorithm) return nil, fmt.Errorf("algorithm %s not supported for create key", req.Algorithm) } var tufKey data.PublicKey var err error tufKey, err = service.Create(data.RoleName(req.Role), data.GUN(req.Gun), req.Algorithm) if err != nil { logger.Error("CreateKey: failed to create key: ", err) return nil, grpc.Errorf(codes.Internal, "Key creation failed") } logger.Info("CreateKey: Created KeyID ", tufKey.ID()) return &pb.PublicKey{ KeyInfo: &pb.KeyInfo{ KeyID: &pb.KeyID{ID: tufKey.ID()}, Algorithm: &pb.Algorithm{Algorithm: tufKey.Algorithm()}, }, PublicKey: tufKey.Public(), }, nil }
go
func (s *KeyManagementServer) CreateKey(ctx context.Context, req *pb.CreateKeyRequest) (*pb.PublicKey, error) { service := s.CryptoServices[req.Algorithm] logger := ctxu.GetLogger(ctx) if service == nil { logger.Error("CreateKey: unsupported algorithm: ", req.Algorithm) return nil, fmt.Errorf("algorithm %s not supported for create key", req.Algorithm) } var tufKey data.PublicKey var err error tufKey, err = service.Create(data.RoleName(req.Role), data.GUN(req.Gun), req.Algorithm) if err != nil { logger.Error("CreateKey: failed to create key: ", err) return nil, grpc.Errorf(codes.Internal, "Key creation failed") } logger.Info("CreateKey: Created KeyID ", tufKey.ID()) return &pb.PublicKey{ KeyInfo: &pb.KeyInfo{ KeyID: &pb.KeyID{ID: tufKey.ID()}, Algorithm: &pb.Algorithm{Algorithm: tufKey.Algorithm()}, }, PublicKey: tufKey.Public(), }, nil }
[ "func", "(", "s", "*", "KeyManagementServer", ")", "CreateKey", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "CreateKeyRequest", ")", "(", "*", "pb", ".", "PublicKey", ",", "error", ")", "{", "service", ":=", "s", ".", "CryptoServ...
//CreateKey returns a PublicKey created using KeyManagementServer's SigningService
[ "CreateKey", "returns", "a", "PublicKey", "created", "using", "KeyManagementServer", "s", "SigningService" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/api/rpc_api.go#L30-L57
train
theupdateframework/notary
signer/api/rpc_api.go
DeleteKey
func (s *KeyManagementServer) DeleteKey(ctx context.Context, keyID *pb.KeyID) (*pb.Void, error) { logger := ctxu.GetLogger(ctx) // delete key ID from all services for _, service := range s.CryptoServices { if err := service.RemoveKey(keyID.ID); err != nil { logger.Errorf("Failed to delete key %s", keyID.ID) return nil, grpc.Errorf(codes.Internal, "Key deletion for KeyID %s failed", keyID.ID) } } return &pb.Void{}, nil }
go
func (s *KeyManagementServer) DeleteKey(ctx context.Context, keyID *pb.KeyID) (*pb.Void, error) { logger := ctxu.GetLogger(ctx) // delete key ID from all services for _, service := range s.CryptoServices { if err := service.RemoveKey(keyID.ID); err != nil { logger.Errorf("Failed to delete key %s", keyID.ID) return nil, grpc.Errorf(codes.Internal, "Key deletion for KeyID %s failed", keyID.ID) } } return &pb.Void{}, nil }
[ "func", "(", "s", "*", "KeyManagementServer", ")", "DeleteKey", "(", "ctx", "context", ".", "Context", ",", "keyID", "*", "pb", ".", "KeyID", ")", "(", "*", "pb", ".", "Void", ",", "error", ")", "{", "logger", ":=", "ctxu", ".", "GetLogger", "(", "...
//DeleteKey deletes they key associated with a KeyID
[ "DeleteKey", "deletes", "they", "key", "associated", "with", "a", "KeyID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/api/rpc_api.go#L60-L71
train
theupdateframework/notary
signer/api/rpc_api.go
GetKeyInfo
func (s *KeyManagementServer) GetKeyInfo(ctx context.Context, keyID *pb.KeyID) (*pb.GetKeyInfoResponse, error) { privKey, role, err := findKeyByID(s.CryptoServices, keyID) logger := ctxu.GetLogger(ctx) if err != nil { logger.Errorf("GetKeyInfo: key %s not found", keyID.ID) return nil, grpc.Errorf(codes.NotFound, "key %s not found", keyID.ID) } logger.Debug("GetKeyInfo: Returning PublicKey for KeyID ", keyID.ID) return &pb.GetKeyInfoResponse{ KeyInfo: &pb.KeyInfo{ KeyID: &pb.KeyID{ID: privKey.ID()}, Algorithm: &pb.Algorithm{Algorithm: privKey.Algorithm()}, }, PublicKey: privKey.Public(), Role: role.String(), }, nil }
go
func (s *KeyManagementServer) GetKeyInfo(ctx context.Context, keyID *pb.KeyID) (*pb.GetKeyInfoResponse, error) { privKey, role, err := findKeyByID(s.CryptoServices, keyID) logger := ctxu.GetLogger(ctx) if err != nil { logger.Errorf("GetKeyInfo: key %s not found", keyID.ID) return nil, grpc.Errorf(codes.NotFound, "key %s not found", keyID.ID) } logger.Debug("GetKeyInfo: Returning PublicKey for KeyID ", keyID.ID) return &pb.GetKeyInfoResponse{ KeyInfo: &pb.KeyInfo{ KeyID: &pb.KeyID{ID: privKey.ID()}, Algorithm: &pb.Algorithm{Algorithm: privKey.Algorithm()}, }, PublicKey: privKey.Public(), Role: role.String(), }, nil }
[ "func", "(", "s", "*", "KeyManagementServer", ")", "GetKeyInfo", "(", "ctx", "context", ".", "Context", ",", "keyID", "*", "pb", ".", "KeyID", ")", "(", "*", "pb", ".", "GetKeyInfoResponse", ",", "error", ")", "{", "privKey", ",", "role", ",", "err", ...
//GetKeyInfo returns they PublicKey associated with a KeyID
[ "GetKeyInfo", "returns", "they", "PublicKey", "associated", "with", "a", "KeyID" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/api/rpc_api.go#L74-L93
train
theupdateframework/notary
signer/api/rpc_api.go
Sign
func (s *SignerServer) Sign(ctx context.Context, sr *pb.SignatureRequest) (*pb.Signature, error) { privKey, _, err := findKeyByID(s.CryptoServices, sr.KeyID) logger := ctxu.GetLogger(ctx) switch err.(type) { case trustmanager.ErrKeyNotFound: logger.Errorf("Sign: key %s not found", sr.KeyID.ID) return nil, grpc.Errorf(codes.NotFound, err.Error()) case nil: break default: logger.Errorf("Getting key %s failed: %s", sr.KeyID.ID, err.Error()) return nil, grpc.Errorf(codes.Internal, err.Error()) } sig, err := privKey.Sign(rand.Reader, sr.Content, nil) if err != nil { logger.Errorf("Sign: signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content) return nil, grpc.Errorf(codes.Internal, "Signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content) } logger.Info("Sign: Signed ", string(sr.Content), " with KeyID ", sr.KeyID.ID) signature := &pb.Signature{ KeyInfo: &pb.KeyInfo{ KeyID: &pb.KeyID{ID: privKey.ID()}, Algorithm: &pb.Algorithm{Algorithm: privKey.Algorithm()}, }, Algorithm: &pb.Algorithm{Algorithm: privKey.SignatureAlgorithm().String()}, Content: sig, } return signature, nil }
go
func (s *SignerServer) Sign(ctx context.Context, sr *pb.SignatureRequest) (*pb.Signature, error) { privKey, _, err := findKeyByID(s.CryptoServices, sr.KeyID) logger := ctxu.GetLogger(ctx) switch err.(type) { case trustmanager.ErrKeyNotFound: logger.Errorf("Sign: key %s not found", sr.KeyID.ID) return nil, grpc.Errorf(codes.NotFound, err.Error()) case nil: break default: logger.Errorf("Getting key %s failed: %s", sr.KeyID.ID, err.Error()) return nil, grpc.Errorf(codes.Internal, err.Error()) } sig, err := privKey.Sign(rand.Reader, sr.Content, nil) if err != nil { logger.Errorf("Sign: signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content) return nil, grpc.Errorf(codes.Internal, "Signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content) } logger.Info("Sign: Signed ", string(sr.Content), " with KeyID ", sr.KeyID.ID) signature := &pb.Signature{ KeyInfo: &pb.KeyInfo{ KeyID: &pb.KeyID{ID: privKey.ID()}, Algorithm: &pb.Algorithm{Algorithm: privKey.Algorithm()}, }, Algorithm: &pb.Algorithm{Algorithm: privKey.SignatureAlgorithm().String()}, Content: sig, } return signature, nil }
[ "func", "(", "s", "*", "SignerServer", ")", "Sign", "(", "ctx", "context", ".", "Context", ",", "sr", "*", "pb", ".", "SignatureRequest", ")", "(", "*", "pb", ".", "Signature", ",", "error", ")", "{", "privKey", ",", "_", ",", "err", ":=", "findKey...
//Sign signs a message and returns the signature using a private key associate with the KeyID from the SignatureRequest
[ "Sign", "signs", "a", "message", "and", "returns", "the", "signature", "using", "a", "private", "key", "associate", "with", "the", "KeyID", "from", "the", "SignatureRequest" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/api/rpc_api.go#L96-L131
train
theupdateframework/notary
cmd/notary/tuf.go
getTargetCustom
func getTargetCustom(targetCustomFilename string) (*canonicaljson.RawMessage, error) { targetCustom := new(canonicaljson.RawMessage) rawTargetCustom, err := ioutil.ReadFile(targetCustomFilename) if err != nil { return nil, err } if err := targetCustom.UnmarshalJSON(rawTargetCustom); err != nil { return nil, err } return targetCustom, nil }
go
func getTargetCustom(targetCustomFilename string) (*canonicaljson.RawMessage, error) { targetCustom := new(canonicaljson.RawMessage) rawTargetCustom, err := ioutil.ReadFile(targetCustomFilename) if err != nil { return nil, err } if err := targetCustom.UnmarshalJSON(rawTargetCustom); err != nil { return nil, err } return targetCustom, nil }
[ "func", "getTargetCustom", "(", "targetCustomFilename", "string", ")", "(", "*", "canonicaljson", ".", "RawMessage", ",", "error", ")", "{", "targetCustom", ":=", "new", "(", "canonicaljson", ".", "RawMessage", ")", "\n", "rawTargetCustom", ",", "err", ":=", "...
// Open and read a file containing the targetCustom data
[ "Open", "and", "read", "a", "file", "containing", "the", "targetCustom", "data" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/tuf.go#L256-L267
train
theupdateframework/notary
cmd/notary/tuf.go
importRootKey
func importRootKey(cmd *cobra.Command, rootKey string, nRepo notaryclient.Repository, retriever notary.PassRetriever) ([]string, error) { var rootKeyList []string if rootKey != "" { privKey, err := readKey(data.CanonicalRootRole, rootKey, retriever) if err != nil { return nil, err } // add root key to repo err = nRepo.GetCryptoService().AddKey(data.CanonicalRootRole, "", privKey) if err != nil { return nil, fmt.Errorf("Error importing key: %v", err) } rootKeyList = []string{privKey.ID()} } else { rootKeyList = nRepo.GetCryptoService().ListKeys(data.CanonicalRootRole) } if len(rootKeyList) > 0 { // Chooses the first root key available, which is initialization specific // but should return the HW one first. rootKeyID := rootKeyList[0] cmd.Printf("Root key found, using: %s\n", rootKeyID) return []string{rootKeyID}, nil } return []string{}, nil }
go
func importRootKey(cmd *cobra.Command, rootKey string, nRepo notaryclient.Repository, retriever notary.PassRetriever) ([]string, error) { var rootKeyList []string if rootKey != "" { privKey, err := readKey(data.CanonicalRootRole, rootKey, retriever) if err != nil { return nil, err } // add root key to repo err = nRepo.GetCryptoService().AddKey(data.CanonicalRootRole, "", privKey) if err != nil { return nil, fmt.Errorf("Error importing key: %v", err) } rootKeyList = []string{privKey.ID()} } else { rootKeyList = nRepo.GetCryptoService().ListKeys(data.CanonicalRootRole) } if len(rootKeyList) > 0 { // Chooses the first root key available, which is initialization specific // but should return the HW one first. rootKeyID := rootKeyList[0] cmd.Printf("Root key found, using: %s\n", rootKeyID) return []string{rootKeyID}, nil } return []string{}, nil }
[ "func", "importRootKey", "(", "cmd", "*", "cobra", ".", "Command", ",", "rootKey", "string", ",", "nRepo", "notaryclient", ".", "Repository", ",", "retriever", "notary", ".", "PassRetriever", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "...
// importRootKey imports the root key from path then adds the key to repo // returns key ids
[ "importRootKey", "imports", "the", "root", "key", "from", "path", "then", "adds", "the", "key", "to", "repo", "returns", "key", "ids" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/tuf.go#L413-L441
train
theupdateframework/notary
cmd/notary/tuf.go
importRootCert
func importRootCert(certFilePath string) ([]data.PublicKey, error) { publicKeys := make([]data.PublicKey, 0, 1) if certFilePath == "" { return publicKeys, nil } // read certificate from file certPEM, err := ioutil.ReadFile(certFilePath) if err != nil { return nil, fmt.Errorf("error reading certificate file: %v", err) } block, _ := pem.Decode([]byte(certPEM)) if block == nil { return nil, fmt.Errorf("the provided file does not contain a valid PEM certificate %v", err) } // convert the file to data.PublicKey cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, fmt.Errorf("Parsing certificate PEM bytes to x509 certificate: %v", err) } publicKeys = append(publicKeys, tufutils.CertToKey(cert)) return publicKeys, nil }
go
func importRootCert(certFilePath string) ([]data.PublicKey, error) { publicKeys := make([]data.PublicKey, 0, 1) if certFilePath == "" { return publicKeys, nil } // read certificate from file certPEM, err := ioutil.ReadFile(certFilePath) if err != nil { return nil, fmt.Errorf("error reading certificate file: %v", err) } block, _ := pem.Decode([]byte(certPEM)) if block == nil { return nil, fmt.Errorf("the provided file does not contain a valid PEM certificate %v", err) } // convert the file to data.PublicKey cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, fmt.Errorf("Parsing certificate PEM bytes to x509 certificate: %v", err) } publicKeys = append(publicKeys, tufutils.CertToKey(cert)) return publicKeys, nil }
[ "func", "importRootCert", "(", "certFilePath", "string", ")", "(", "[", "]", "data", ".", "PublicKey", ",", "error", ")", "{", "publicKeys", ":=", "make", "(", "[", "]", "data", ".", "PublicKey", ",", "0", ",", "1", ")", "\n", "if", "certFilePath", "...
// importRootCert imports the base64 encoded public certificate corresponding to the root key // returns empty slice if path is empty
[ "importRootCert", "imports", "the", "base64", "encoded", "public", "certificate", "corresponding", "to", "the", "root", "key", "returns", "empty", "slice", "if", "path", "is", "empty" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/tuf.go#L445-L470
train
theupdateframework/notary
cmd/notary/tuf.go
readKey
func readKey(role data.RoleName, keyFilename string, retriever notary.PassRetriever) (data.PrivateKey, error) { pemBytes, err := ioutil.ReadFile(keyFilename) if err != nil { return nil, fmt.Errorf("Error reading input root key file: %v", err) } isEncrypted := true if err = cryptoservice.CheckRootKeyIsEncrypted(pemBytes); err != nil { if role == data.CanonicalRootRole { return nil, err } isEncrypted = false } var privKey data.PrivateKey if isEncrypted { privKey, _, err = trustmanager.GetPasswdDecryptBytes(retriever, pemBytes, "", data.CanonicalRootRole.String()) } else { privKey, err = tufutils.ParsePEMPrivateKey(pemBytes, "") } if err != nil { return nil, err } return privKey, nil }
go
func readKey(role data.RoleName, keyFilename string, retriever notary.PassRetriever) (data.PrivateKey, error) { pemBytes, err := ioutil.ReadFile(keyFilename) if err != nil { return nil, fmt.Errorf("Error reading input root key file: %v", err) } isEncrypted := true if err = cryptoservice.CheckRootKeyIsEncrypted(pemBytes); err != nil { if role == data.CanonicalRootRole { return nil, err } isEncrypted = false } var privKey data.PrivateKey if isEncrypted { privKey, _, err = trustmanager.GetPasswdDecryptBytes(retriever, pemBytes, "", data.CanonicalRootRole.String()) } else { privKey, err = tufutils.ParsePEMPrivateKey(pemBytes, "") } if err != nil { return nil, err } return privKey, nil }
[ "func", "readKey", "(", "role", "data", ".", "RoleName", ",", "keyFilename", "string", ",", "retriever", "notary", ".", "PassRetriever", ")", "(", "data", ".", "PrivateKey", ",", "error", ")", "{", "pemBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", ...
// Attempt to read a role key from a file, and return it as a data.PrivateKey // If key is for the Root role, it must be encrypted
[ "Attempt", "to", "read", "a", "role", "key", "from", "a", "file", "and", "return", "it", "as", "a", "data", ".", "PrivateKey", "If", "key", "is", "for", "the", "Root", "role", "it", "must", "be", "encrypted" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/tuf.go#L514-L537
train
theupdateframework/notary
server/handlers/validation.go
validateUpdate
func validateUpdate(cs signed.CryptoService, gun data.GUN, updates []storage.MetaUpdate, store storage.MetaStore) ([]storage.MetaUpdate, error) { // some delegated targets role may be invalid based on other updates // that have been made by other clients. We'll rebuild the slice of // updates with only the things we should actually update updatesToApply := make([]storage.MetaUpdate, 0, len(updates)) roles := make(map[data.RoleName]storage.MetaUpdate) for _, v := range updates { roles[v.Role] = v } builder := tuf.NewRepoBuilder(gun, cs, trustpinning.TrustPinConfig{}) if err := loadFromStore(gun, data.CanonicalRootRole, builder, store); err != nil { if _, ok := err.(storage.ErrNotFound); !ok { return nil, err } } if rootUpdate, ok := roles[data.CanonicalRootRole]; ok { currentRootVersion := builder.GetLoadedVersion(data.CanonicalRootRole) if rootUpdate.Version != currentRootVersion && rootUpdate.Version != currentRootVersion+1 { msg := fmt.Sprintf("Root modifications must increment the version. Current %d, new %d", currentRootVersion, rootUpdate.Version) return nil, validation.ErrBadRoot{Msg: msg} } builder = builder.BootstrapNewBuilder() if err := builder.Load(data.CanonicalRootRole, rootUpdate.Data, currentRootVersion, false); err != nil { return nil, validation.ErrBadRoot{Msg: err.Error()} } logrus.Debug("Successfully validated root") updatesToApply = append(updatesToApply, rootUpdate) } else if !builder.IsLoaded(data.CanonicalRootRole) { return nil, validation.ErrValidation{Msg: "no pre-existing root and no root provided in update."} } targetsToUpdate, err := loadAndValidateTargets(gun, builder, roles, store) if err != nil { return nil, err } updatesToApply = append(updatesToApply, targetsToUpdate...) // there's no need to load files from the database if no targets etc... // were uploaded because that means they haven't been updated and // the snapshot will already contain the correct hashes and sizes for // those targets (incl. delegated targets) logrus.Debug("Successfully validated targets") // At this point, root and targets must have been loaded into the repo if snapshotUpdate, ok := roles[data.CanonicalSnapshotRole]; ok { if err := builder.Load(data.CanonicalSnapshotRole, snapshotUpdate.Data, 1, false); err != nil { return nil, validation.ErrBadSnapshot{Msg: err.Error()} } logrus.Debug("Successfully validated snapshot") updatesToApply = append(updatesToApply, roles[data.CanonicalSnapshotRole]) } else { // Check: // - we have a snapshot key // - it matches a snapshot key signed into the root.json // Then: // - generate a new snapshot // - add it to the updates update, err := generateSnapshot(gun, builder, store) if err != nil { return nil, err } updatesToApply = append(updatesToApply, *update) } // generate a timestamp immediately update, err := generateTimestamp(gun, builder, store) if err != nil { return nil, err } return append(updatesToApply, *update), nil }
go
func validateUpdate(cs signed.CryptoService, gun data.GUN, updates []storage.MetaUpdate, store storage.MetaStore) ([]storage.MetaUpdate, error) { // some delegated targets role may be invalid based on other updates // that have been made by other clients. We'll rebuild the slice of // updates with only the things we should actually update updatesToApply := make([]storage.MetaUpdate, 0, len(updates)) roles := make(map[data.RoleName]storage.MetaUpdate) for _, v := range updates { roles[v.Role] = v } builder := tuf.NewRepoBuilder(gun, cs, trustpinning.TrustPinConfig{}) if err := loadFromStore(gun, data.CanonicalRootRole, builder, store); err != nil { if _, ok := err.(storage.ErrNotFound); !ok { return nil, err } } if rootUpdate, ok := roles[data.CanonicalRootRole]; ok { currentRootVersion := builder.GetLoadedVersion(data.CanonicalRootRole) if rootUpdate.Version != currentRootVersion && rootUpdate.Version != currentRootVersion+1 { msg := fmt.Sprintf("Root modifications must increment the version. Current %d, new %d", currentRootVersion, rootUpdate.Version) return nil, validation.ErrBadRoot{Msg: msg} } builder = builder.BootstrapNewBuilder() if err := builder.Load(data.CanonicalRootRole, rootUpdate.Data, currentRootVersion, false); err != nil { return nil, validation.ErrBadRoot{Msg: err.Error()} } logrus.Debug("Successfully validated root") updatesToApply = append(updatesToApply, rootUpdate) } else if !builder.IsLoaded(data.CanonicalRootRole) { return nil, validation.ErrValidation{Msg: "no pre-existing root and no root provided in update."} } targetsToUpdate, err := loadAndValidateTargets(gun, builder, roles, store) if err != nil { return nil, err } updatesToApply = append(updatesToApply, targetsToUpdate...) // there's no need to load files from the database if no targets etc... // were uploaded because that means they haven't been updated and // the snapshot will already contain the correct hashes and sizes for // those targets (incl. delegated targets) logrus.Debug("Successfully validated targets") // At this point, root and targets must have been loaded into the repo if snapshotUpdate, ok := roles[data.CanonicalSnapshotRole]; ok { if err := builder.Load(data.CanonicalSnapshotRole, snapshotUpdate.Data, 1, false); err != nil { return nil, validation.ErrBadSnapshot{Msg: err.Error()} } logrus.Debug("Successfully validated snapshot") updatesToApply = append(updatesToApply, roles[data.CanonicalSnapshotRole]) } else { // Check: // - we have a snapshot key // - it matches a snapshot key signed into the root.json // Then: // - generate a new snapshot // - add it to the updates update, err := generateSnapshot(gun, builder, store) if err != nil { return nil, err } updatesToApply = append(updatesToApply, *update) } // generate a timestamp immediately update, err := generateTimestamp(gun, builder, store) if err != nil { return nil, err } return append(updatesToApply, *update), nil }
[ "func", "validateUpdate", "(", "cs", "signed", ".", "CryptoService", ",", "gun", "data", ".", "GUN", ",", "updates", "[", "]", "storage", ".", "MetaUpdate", ",", "store", "storage", ".", "MetaStore", ")", "(", "[", "]", "storage", ".", "MetaUpdate", ",",...
// validateUpload checks that the updates being pushed // are semantically correct and the signatures are correct // A list of possibly modified updates are returned if all // validation was successful. This allows the snapshot to be // created and added if snapshotting has been delegated to the // server
[ "validateUpload", "checks", "that", "the", "updates", "being", "pushed", "are", "semantically", "correct", "and", "the", "signatures", "are", "correct", "A", "list", "of", "possibly", "modified", "updates", "are", "returned", "if", "all", "validation", "was", "s...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/validation.go#L25-L99
train
theupdateframework/notary
server/handlers/validation.go
generateSnapshot
func generateSnapshot(gun data.GUN, builder tuf.RepoBuilder, store storage.MetaStore) (*storage.MetaUpdate, error) { var prev *data.SignedSnapshot _, currentJSON, err := store.GetCurrent(gun, data.CanonicalSnapshotRole) if err == nil { prev = new(data.SignedSnapshot) if err = json.Unmarshal(currentJSON, prev); err != nil { logrus.Error("Failed to unmarshal existing snapshot for GUN ", gun) return nil, err } } if _, ok := err.(storage.ErrNotFound); !ok && err != nil { return nil, err } meta, ver, err := builder.GenerateSnapshot(prev) switch err.(type) { case nil: return &storage.MetaUpdate{ Role: data.CanonicalSnapshotRole, Version: ver, Data: meta, }, nil case signed.ErrInsufficientSignatures, signed.ErrNoKeys, signed.ErrRoleThreshold: // If we cannot sign the snapshot, then we don't have keys for the snapshot, // and the client should have submitted a snapshot return nil, validation.ErrBadHierarchy{ Missing: data.CanonicalSnapshotRole.String(), Msg: "no snapshot was included in update and server does not hold current snapshot key for repository"} default: return nil, validation.ErrValidation{Msg: err.Error()} } }
go
func generateSnapshot(gun data.GUN, builder tuf.RepoBuilder, store storage.MetaStore) (*storage.MetaUpdate, error) { var prev *data.SignedSnapshot _, currentJSON, err := store.GetCurrent(gun, data.CanonicalSnapshotRole) if err == nil { prev = new(data.SignedSnapshot) if err = json.Unmarshal(currentJSON, prev); err != nil { logrus.Error("Failed to unmarshal existing snapshot for GUN ", gun) return nil, err } } if _, ok := err.(storage.ErrNotFound); !ok && err != nil { return nil, err } meta, ver, err := builder.GenerateSnapshot(prev) switch err.(type) { case nil: return &storage.MetaUpdate{ Role: data.CanonicalSnapshotRole, Version: ver, Data: meta, }, nil case signed.ErrInsufficientSignatures, signed.ErrNoKeys, signed.ErrRoleThreshold: // If we cannot sign the snapshot, then we don't have keys for the snapshot, // and the client should have submitted a snapshot return nil, validation.ErrBadHierarchy{ Missing: data.CanonicalSnapshotRole.String(), Msg: "no snapshot was included in update and server does not hold current snapshot key for repository"} default: return nil, validation.ErrValidation{Msg: err.Error()} } }
[ "func", "generateSnapshot", "(", "gun", "data", ".", "GUN", ",", "builder", "tuf", ".", "RepoBuilder", ",", "store", "storage", ".", "MetaStore", ")", "(", "*", "storage", ".", "MetaUpdate", ",", "error", ")", "{", "var", "prev", "*", "data", ".", "Sig...
// generateSnapshot generates a new snapshot from the previous one in the store - this assumes all // the other roles except timestamp have already been set on the repo, and will set the generated // snapshot on the repo as well
[ "generateSnapshot", "generates", "a", "new", "snapshot", "from", "the", "previous", "one", "in", "the", "store", "-", "this", "assumes", "all", "the", "other", "roles", "except", "timestamp", "have", "already", "been", "set", "on", "the", "repo", "and", "wil...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/validation.go#L152-L185
train
theupdateframework/notary
server/handlers/validation.go
generateTimestamp
func generateTimestamp(gun data.GUN, builder tuf.RepoBuilder, store storage.MetaStore) (*storage.MetaUpdate, error) { var prev *data.SignedTimestamp _, currentJSON, err := store.GetCurrent(gun, data.CanonicalTimestampRole) switch err.(type) { case nil: prev = new(data.SignedTimestamp) if err := json.Unmarshal(currentJSON, prev); err != nil { logrus.Error("Failed to unmarshal existing timestamp for GUN ", gun) return nil, err } case storage.ErrNotFound: break // this is the first timestamp ever for the repo default: return nil, err } meta, ver, err := builder.GenerateTimestamp(prev) switch err.(type) { case nil: return &storage.MetaUpdate{ Role: data.CanonicalTimestampRole, Version: ver, Data: meta, }, nil case signed.ErrInsufficientSignatures, signed.ErrNoKeys: // If we cannot sign the timestamp, then we don't have keys for the timestamp, // and the client screwed up their root return nil, validation.ErrBadRoot{ Msg: fmt.Sprintf("no timestamp keys exist on the server"), } default: return nil, validation.ErrValidation{Msg: err.Error()} } }
go
func generateTimestamp(gun data.GUN, builder tuf.RepoBuilder, store storage.MetaStore) (*storage.MetaUpdate, error) { var prev *data.SignedTimestamp _, currentJSON, err := store.GetCurrent(gun, data.CanonicalTimestampRole) switch err.(type) { case nil: prev = new(data.SignedTimestamp) if err := json.Unmarshal(currentJSON, prev); err != nil { logrus.Error("Failed to unmarshal existing timestamp for GUN ", gun) return nil, err } case storage.ErrNotFound: break // this is the first timestamp ever for the repo default: return nil, err } meta, ver, err := builder.GenerateTimestamp(prev) switch err.(type) { case nil: return &storage.MetaUpdate{ Role: data.CanonicalTimestampRole, Version: ver, Data: meta, }, nil case signed.ErrInsufficientSignatures, signed.ErrNoKeys: // If we cannot sign the timestamp, then we don't have keys for the timestamp, // and the client screwed up their root return nil, validation.ErrBadRoot{ Msg: fmt.Sprintf("no timestamp keys exist on the server"), } default: return nil, validation.ErrValidation{Msg: err.Error()} } }
[ "func", "generateTimestamp", "(", "gun", "data", ".", "GUN", ",", "builder", "tuf", ".", "RepoBuilder", ",", "store", "storage", ".", "MetaStore", ")", "(", "*", "storage", ".", "MetaUpdate", ",", "error", ")", "{", "var", "prev", "*", "data", ".", "Si...
// generateTimestamp generates a new timestamp from the previous one in the store - this assumes all // the other roles have already been set on the repo, and will set the generated timestamp on the repo as well
[ "generateTimestamp", "generates", "a", "new", "timestamp", "from", "the", "previous", "one", "in", "the", "store", "-", "this", "assumes", "all", "the", "other", "roles", "have", "already", "been", "set", "on", "the", "repo", "and", "will", "set", "the", "...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/validation.go#L189-L224
train
theupdateframework/notary
tuf/signed/sign.go
Sign
func Sign(service CryptoService, s *data.Signed, signingKeys []data.PublicKey, minSignatures int, otherWhitelistedKeys []data.PublicKey) error { logrus.Debugf("sign called with %d/%d required keys", minSignatures, len(signingKeys)) signatures := make([]data.Signature, 0, len(s.Signatures)+1) signingKeyIDs := make(map[string]struct{}) tufIDs := make(map[string]data.PublicKey) privKeys := make(map[string]data.PrivateKey) // Get all the private key objects related to the public keys missingKeyIDs := []string{} for _, key := range signingKeys { canonicalID, err := utils.CanonicalKeyID(key) tufIDs[key.ID()] = key if err != nil { return err } k, _, err := service.GetPrivateKey(canonicalID) if err != nil { if _, ok := err.(trustmanager.ErrKeyNotFound); ok { missingKeyIDs = append(missingKeyIDs, canonicalID) continue } return err } privKeys[key.ID()] = k } // include the list of otherWhitelistedKeys for _, key := range otherWhitelistedKeys { if _, ok := tufIDs[key.ID()]; !ok { tufIDs[key.ID()] = key } } // Check to ensure we have enough signing keys if len(privKeys) < minSignatures { return ErrInsufficientSignatures{FoundKeys: len(privKeys), NeededKeys: minSignatures, MissingKeyIDs: missingKeyIDs} } emptyStruct := struct{}{} // Do signing and generate list of signatures for keyID, pk := range privKeys { sig, err := pk.Sign(rand.Reader, *s.Signed, nil) if err != nil { logrus.Debugf("Failed to sign with key: %s. Reason: %v", keyID, err) return err } signingKeyIDs[keyID] = emptyStruct signatures = append(signatures, data.Signature{ KeyID: keyID, Method: pk.SignatureAlgorithm(), Signature: sig[:], }) } for _, sig := range s.Signatures { if _, ok := signingKeyIDs[sig.KeyID]; ok { // key is in the set of key IDs for which a signature has been created continue } var ( k data.PublicKey ok bool ) if k, ok = tufIDs[sig.KeyID]; !ok { // key is no longer a valid signing key continue } if err := VerifySignature(*s.Signed, &sig, k); err != nil { // signature is no longer valid continue } // keep any signatures that still represent valid keys and are // themselves valid signatures = append(signatures, sig) } s.Signatures = signatures return nil }
go
func Sign(service CryptoService, s *data.Signed, signingKeys []data.PublicKey, minSignatures int, otherWhitelistedKeys []data.PublicKey) error { logrus.Debugf("sign called with %d/%d required keys", minSignatures, len(signingKeys)) signatures := make([]data.Signature, 0, len(s.Signatures)+1) signingKeyIDs := make(map[string]struct{}) tufIDs := make(map[string]data.PublicKey) privKeys := make(map[string]data.PrivateKey) // Get all the private key objects related to the public keys missingKeyIDs := []string{} for _, key := range signingKeys { canonicalID, err := utils.CanonicalKeyID(key) tufIDs[key.ID()] = key if err != nil { return err } k, _, err := service.GetPrivateKey(canonicalID) if err != nil { if _, ok := err.(trustmanager.ErrKeyNotFound); ok { missingKeyIDs = append(missingKeyIDs, canonicalID) continue } return err } privKeys[key.ID()] = k } // include the list of otherWhitelistedKeys for _, key := range otherWhitelistedKeys { if _, ok := tufIDs[key.ID()]; !ok { tufIDs[key.ID()] = key } } // Check to ensure we have enough signing keys if len(privKeys) < minSignatures { return ErrInsufficientSignatures{FoundKeys: len(privKeys), NeededKeys: minSignatures, MissingKeyIDs: missingKeyIDs} } emptyStruct := struct{}{} // Do signing and generate list of signatures for keyID, pk := range privKeys { sig, err := pk.Sign(rand.Reader, *s.Signed, nil) if err != nil { logrus.Debugf("Failed to sign with key: %s. Reason: %v", keyID, err) return err } signingKeyIDs[keyID] = emptyStruct signatures = append(signatures, data.Signature{ KeyID: keyID, Method: pk.SignatureAlgorithm(), Signature: sig[:], }) } for _, sig := range s.Signatures { if _, ok := signingKeyIDs[sig.KeyID]; ok { // key is in the set of key IDs for which a signature has been created continue } var ( k data.PublicKey ok bool ) if k, ok = tufIDs[sig.KeyID]; !ok { // key is no longer a valid signing key continue } if err := VerifySignature(*s.Signed, &sig, k); err != nil { // signature is no longer valid continue } // keep any signatures that still represent valid keys and are // themselves valid signatures = append(signatures, sig) } s.Signatures = signatures return nil }
[ "func", "Sign", "(", "service", "CryptoService", ",", "s", "*", "data", ".", "Signed", ",", "signingKeys", "[", "]", "data", ".", "PublicKey", ",", "minSignatures", "int", ",", "otherWhitelistedKeys", "[", "]", "data", ".", "PublicKey", ")", "error", "{", ...
// Sign takes a data.Signed and a cryptoservice containing private keys, // calculates and adds at least minSignature signatures using signingKeys the // data.Signed. It will also clean up any signatures that are not in produced // by either a signingKey or an otherWhitelistedKey. // Note that in most cases, otherWhitelistedKeys should probably be null. They // are for keys you don't want to sign with, but you also don't want to remove // existing signatures by those keys. For instance, if you want to call Sign // multiple times with different sets of signing keys without undoing removing // signatures produced by the previous call to Sign.
[ "Sign", "takes", "a", "data", ".", "Signed", "and", "a", "cryptoservice", "containing", "private", "keys", "calculates", "and", "adds", "at", "least", "minSignature", "signatures", "using", "signingKeys", "the", "data", ".", "Signed", ".", "It", "will", "also"...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/sign.go#L32-L113
train
theupdateframework/notary
tuf/utils/role_sort.go
Swap
func (r RoleList) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
go
func (r RoleList) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
[ "func", "(", "r", "RoleList", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "r", "[", "i", "]", ",", "r", "[", "j", "]", "=", "r", "[", "j", "]", ",", "r", "[", "i", "]", "\n", "}" ]
// Swap the items at 2 locations in the list
[ "Swap", "the", "items", "at", "2", "locations", "in", "the", "list" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/role_sort.go#L29-L31
train
theupdateframework/notary
client/reader.go
GetTargetByName
func (r *reader) GetTargetByName(name string, roles ...data.RoleName) (*TargetWithRole, error) { if len(roles) == 0 { roles = append(roles, data.CanonicalTargetsRole) } var resultMeta data.FileMeta var resultRoleName data.RoleName var foundTarget bool for _, role := range roles { // Define an array of roles to skip for this walk (see IMPORTANT comment above) skipRoles := utils.RoleNameSliceRemove(roles, role) // Define a visitor function to find the specified target getTargetVisitorFunc := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { if tgt == nil { return nil } // We found the target and validated path compatibility in our walk, // so we should stop our walk and set the resultMeta and resultRoleName variables if resultMeta, foundTarget = tgt.Signed.Targets[name]; foundTarget { resultRoleName = validRole.Name return tuf.StopWalk{} } return nil } // Check that we didn't error, and that we assigned to our target if err := r.tufRepo.WalkTargets(name, role, getTargetVisitorFunc, skipRoles...); err == nil && foundTarget { return &TargetWithRole{Target: Target{Name: name, Hashes: resultMeta.Hashes, Length: resultMeta.Length, Custom: resultMeta.Custom}, Role: resultRoleName}, nil } } return nil, ErrNoSuchTarget(name) }
go
func (r *reader) GetTargetByName(name string, roles ...data.RoleName) (*TargetWithRole, error) { if len(roles) == 0 { roles = append(roles, data.CanonicalTargetsRole) } var resultMeta data.FileMeta var resultRoleName data.RoleName var foundTarget bool for _, role := range roles { // Define an array of roles to skip for this walk (see IMPORTANT comment above) skipRoles := utils.RoleNameSliceRemove(roles, role) // Define a visitor function to find the specified target getTargetVisitorFunc := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { if tgt == nil { return nil } // We found the target and validated path compatibility in our walk, // so we should stop our walk and set the resultMeta and resultRoleName variables if resultMeta, foundTarget = tgt.Signed.Targets[name]; foundTarget { resultRoleName = validRole.Name return tuf.StopWalk{} } return nil } // Check that we didn't error, and that we assigned to our target if err := r.tufRepo.WalkTargets(name, role, getTargetVisitorFunc, skipRoles...); err == nil && foundTarget { return &TargetWithRole{Target: Target{Name: name, Hashes: resultMeta.Hashes, Length: resultMeta.Length, Custom: resultMeta.Custom}, Role: resultRoleName}, nil } } return nil, ErrNoSuchTarget(name) }
[ "func", "(", "r", "*", "reader", ")", "GetTargetByName", "(", "name", "string", ",", "roles", "...", "data", ".", "RoleName", ")", "(", "*", "TargetWithRole", ",", "error", ")", "{", "if", "len", "(", "roles", ")", "==", "0", "{", "roles", "=", "ap...
// GetTargetByName returns a target by the given name. If no roles are passed // it uses the targets role and does a search of the entire delegation // graph, finding the first entry in a breadth first search of the delegations. // If roles are passed, they should be passed in descending priority and // the target entry found in the subtree of the highest priority role // will be returned. // See the IMPORTANT section on ListTargets above. Those roles also apply here.
[ "GetTargetByName", "returns", "a", "target", "by", "the", "given", "name", ".", "If", "no", "roles", "are", "passed", "it", "uses", "the", "targets", "role", "and", "does", "a", "search", "of", "the", "entire", "delegation", "graph", "finding", "the", "fir...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/reader.go#L117-L148
train
theupdateframework/notary
client/reader.go
GetAllTargetMetadataByName
func (r *reader) GetAllTargetMetadataByName(name string) ([]TargetSignedStruct, error) { var targetInfoList []TargetSignedStruct // Define a visitor function to find the specified target getAllTargetInfoByNameVisitorFunc := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { if tgt == nil { return nil } // We found a target and validated path compatibility in our walk, // so add it to our list if we have a match // if we have an empty name, add all targets, else check if we have it var targetMetaToAdd data.Files if name == "" { targetMetaToAdd = tgt.Signed.Targets } else { if meta, ok := tgt.Signed.Targets[name]; ok { targetMetaToAdd = data.Files{name: meta} } } for targetName, resultMeta := range targetMetaToAdd { targetInfo := TargetSignedStruct{ Role: validRole, Target: Target{Name: targetName, Hashes: resultMeta.Hashes, Length: resultMeta.Length, Custom: resultMeta.Custom}, Signatures: tgt.Signatures, } targetInfoList = append(targetInfoList, targetInfo) } // continue walking to all child roles return nil } // Check that we didn't error, and that we found the target at least once if err := r.tufRepo.WalkTargets(name, "", getAllTargetInfoByNameVisitorFunc); err != nil { return nil, err } if len(targetInfoList) == 0 { return nil, ErrNoSuchTarget(name) } return targetInfoList, nil }
go
func (r *reader) GetAllTargetMetadataByName(name string) ([]TargetSignedStruct, error) { var targetInfoList []TargetSignedStruct // Define a visitor function to find the specified target getAllTargetInfoByNameVisitorFunc := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { if tgt == nil { return nil } // We found a target and validated path compatibility in our walk, // so add it to our list if we have a match // if we have an empty name, add all targets, else check if we have it var targetMetaToAdd data.Files if name == "" { targetMetaToAdd = tgt.Signed.Targets } else { if meta, ok := tgt.Signed.Targets[name]; ok { targetMetaToAdd = data.Files{name: meta} } } for targetName, resultMeta := range targetMetaToAdd { targetInfo := TargetSignedStruct{ Role: validRole, Target: Target{Name: targetName, Hashes: resultMeta.Hashes, Length: resultMeta.Length, Custom: resultMeta.Custom}, Signatures: tgt.Signatures, } targetInfoList = append(targetInfoList, targetInfo) } // continue walking to all child roles return nil } // Check that we didn't error, and that we found the target at least once if err := r.tufRepo.WalkTargets(name, "", getAllTargetInfoByNameVisitorFunc); err != nil { return nil, err } if len(targetInfoList) == 0 { return nil, ErrNoSuchTarget(name) } return targetInfoList, nil }
[ "func", "(", "r", "*", "reader", ")", "GetAllTargetMetadataByName", "(", "name", "string", ")", "(", "[", "]", "TargetSignedStruct", ",", "error", ")", "{", "var", "targetInfoList", "[", "]", "TargetSignedStruct", "\n", "getAllTargetInfoByNameVisitorFunc", ":=", ...
// GetAllTargetMetadataByName searches the entire delegation role tree to find the specified target by name for all // roles, and returns a list of TargetSignedStructs for each time it finds the specified target. // If given an empty string for a target name, it will return back all targets signed into the repository in every role
[ "GetAllTargetMetadataByName", "searches", "the", "entire", "delegation", "role", "tree", "to", "find", "the", "specified", "target", "by", "name", "for", "all", "roles", "and", "returns", "a", "list", "of", "TargetSignedStructs", "for", "each", "time", "it", "fi...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/reader.go#L153-L193
train
theupdateframework/notary
client/reader.go
ListRoles
func (r *reader) ListRoles() ([]RoleWithSignatures, error) { // Get all role info from our updated keysDB, can be empty roles := r.tufRepo.GetAllLoadedRoles() var roleWithSigs []RoleWithSignatures // Populate RoleWithSignatures with Role from keysDB and signatures from TUF metadata for _, role := range roles { roleWithSig := RoleWithSignatures{Role: *role, Signatures: nil} switch role.Name { case data.CanonicalRootRole: roleWithSig.Signatures = r.tufRepo.Root.Signatures case data.CanonicalTargetsRole: roleWithSig.Signatures = r.tufRepo.Targets[data.CanonicalTargetsRole].Signatures case data.CanonicalSnapshotRole: roleWithSig.Signatures = r.tufRepo.Snapshot.Signatures case data.CanonicalTimestampRole: roleWithSig.Signatures = r.tufRepo.Timestamp.Signatures default: if !data.IsDelegation(role.Name) { continue } if _, ok := r.tufRepo.Targets[role.Name]; ok { // We'll only find a signature if we've published any targets with this delegation roleWithSig.Signatures = r.tufRepo.Targets[role.Name].Signatures } } roleWithSigs = append(roleWithSigs, roleWithSig) } return roleWithSigs, nil }
go
func (r *reader) ListRoles() ([]RoleWithSignatures, error) { // Get all role info from our updated keysDB, can be empty roles := r.tufRepo.GetAllLoadedRoles() var roleWithSigs []RoleWithSignatures // Populate RoleWithSignatures with Role from keysDB and signatures from TUF metadata for _, role := range roles { roleWithSig := RoleWithSignatures{Role: *role, Signatures: nil} switch role.Name { case data.CanonicalRootRole: roleWithSig.Signatures = r.tufRepo.Root.Signatures case data.CanonicalTargetsRole: roleWithSig.Signatures = r.tufRepo.Targets[data.CanonicalTargetsRole].Signatures case data.CanonicalSnapshotRole: roleWithSig.Signatures = r.tufRepo.Snapshot.Signatures case data.CanonicalTimestampRole: roleWithSig.Signatures = r.tufRepo.Timestamp.Signatures default: if !data.IsDelegation(role.Name) { continue } if _, ok := r.tufRepo.Targets[role.Name]; ok { // We'll only find a signature if we've published any targets with this delegation roleWithSig.Signatures = r.tufRepo.Targets[role.Name].Signatures } } roleWithSigs = append(roleWithSigs, roleWithSig) } return roleWithSigs, nil }
[ "func", "(", "r", "*", "reader", ")", "ListRoles", "(", ")", "(", "[", "]", "RoleWithSignatures", ",", "error", ")", "{", "roles", ":=", "r", ".", "tufRepo", ".", "GetAllLoadedRoles", "(", ")", "\n", "var", "roleWithSigs", "[", "]", "RoleWithSignatures",...
// ListRoles returns a list of RoleWithSignatures objects for this repo // This represents the latest metadata for each role in this repo
[ "ListRoles", "returns", "a", "list", "of", "RoleWithSignatures", "objects", "for", "this", "repo", "This", "represents", "the", "latest", "metadata", "for", "each", "role", "in", "this", "repo" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/reader.go#L197-L227
train
theupdateframework/notary
client/reader.go
GetDelegationRoles
func (r *reader) GetDelegationRoles() ([]data.Role, error) { // All top level delegations (ex: targets/level1) are stored exclusively in targets.json _, ok := r.tufRepo.Targets[data.CanonicalTargetsRole] if !ok { return nil, store.ErrMetaNotFound{Resource: data.CanonicalTargetsRole.String()} } // make a copy for traversing nested delegations allDelegations := []data.Role{} // Define a visitor function to populate the delegations list and translate their key IDs to canonical IDs delegationCanonicalListVisitor := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { // For the return list, update with a copy that includes canonicalKeyIDs // These aren't validated by the validRole canonicalDelegations, err := translateDelegationsToCanonicalIDs(tgt.Signed.Delegations) if err != nil { return err } allDelegations = append(allDelegations, canonicalDelegations...) return nil } err := r.tufRepo.WalkTargets("", "", delegationCanonicalListVisitor) if err != nil { return nil, err } return allDelegations, nil }
go
func (r *reader) GetDelegationRoles() ([]data.Role, error) { // All top level delegations (ex: targets/level1) are stored exclusively in targets.json _, ok := r.tufRepo.Targets[data.CanonicalTargetsRole] if !ok { return nil, store.ErrMetaNotFound{Resource: data.CanonicalTargetsRole.String()} } // make a copy for traversing nested delegations allDelegations := []data.Role{} // Define a visitor function to populate the delegations list and translate their key IDs to canonical IDs delegationCanonicalListVisitor := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} { // For the return list, update with a copy that includes canonicalKeyIDs // These aren't validated by the validRole canonicalDelegations, err := translateDelegationsToCanonicalIDs(tgt.Signed.Delegations) if err != nil { return err } allDelegations = append(allDelegations, canonicalDelegations...) return nil } err := r.tufRepo.WalkTargets("", "", delegationCanonicalListVisitor) if err != nil { return nil, err } return allDelegations, nil }
[ "func", "(", "r", "*", "reader", ")", "GetDelegationRoles", "(", ")", "(", "[", "]", "data", ".", "Role", ",", "error", ")", "{", "_", ",", "ok", ":=", "r", ".", "tufRepo", ".", "Targets", "[", "data", ".", "CanonicalTargetsRole", "]", "\n", "if", ...
// GetDelegationRoles returns the keys and roles of the repository's delegations // Also converts key IDs to canonical key IDs to keep consistent with signing prompts
[ "GetDelegationRoles", "returns", "the", "keys", "and", "roles", "of", "the", "repository", "s", "delegations", "Also", "converts", "key", "IDs", "to", "canonical", "key", "IDs", "to", "keep", "consistent", "with", "signing", "prompts" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/reader.go#L231-L257
train
theupdateframework/notary
cmd/notary-server/config.go
getRequiredGunPrefixes
func getRequiredGunPrefixes(configuration *viper.Viper) ([]string, error) { prefixes := configuration.GetStringSlice("repositories.gun_prefixes") for _, prefix := range prefixes { p := path.Clean(strings.TrimSpace(prefix)) if p+"/" != prefix || strings.HasPrefix(p, "/") || strings.HasPrefix(p, "..") { return nil, fmt.Errorf("invalid GUN prefix %s", prefix) } } return prefixes, nil }
go
func getRequiredGunPrefixes(configuration *viper.Viper) ([]string, error) { prefixes := configuration.GetStringSlice("repositories.gun_prefixes") for _, prefix := range prefixes { p := path.Clean(strings.TrimSpace(prefix)) if p+"/" != prefix || strings.HasPrefix(p, "/") || strings.HasPrefix(p, "..") { return nil, fmt.Errorf("invalid GUN prefix %s", prefix) } } return prefixes, nil }
[ "func", "getRequiredGunPrefixes", "(", "configuration", "*", "viper", ".", "Viper", ")", "(", "[", "]", "string", ",", "error", ")", "{", "prefixes", ":=", "configuration", ".", "GetStringSlice", "(", "\"repositories.gun_prefixes\"", ")", "\n", "for", "_", ","...
// gets the required gun prefixes accepted by this server
[ "gets", "the", "required", "gun", "prefixes", "accepted", "by", "this", "server" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-server/config.go#L32-L41
train
theupdateframework/notary
cmd/notary-server/config.go
getAddrAndTLSConfig
func getAddrAndTLSConfig(configuration *viper.Viper) (string, *tls.Config, error) { httpAddr := configuration.GetString("server.http_addr") if httpAddr == "" { return "", nil, fmt.Errorf("http listen address required for server") } tlsConfig, err := utils.ParseServerTLS(configuration, false) if err != nil { return "", nil, fmt.Errorf(err.Error()) } return httpAddr, tlsConfig, nil }
go
func getAddrAndTLSConfig(configuration *viper.Viper) (string, *tls.Config, error) { httpAddr := configuration.GetString("server.http_addr") if httpAddr == "" { return "", nil, fmt.Errorf("http listen address required for server") } tlsConfig, err := utils.ParseServerTLS(configuration, false) if err != nil { return "", nil, fmt.Errorf(err.Error()) } return httpAddr, tlsConfig, nil }
[ "func", "getAddrAndTLSConfig", "(", "configuration", "*", "viper", ".", "Viper", ")", "(", "string", ",", "*", "tls", ".", "Config", ",", "error", ")", "{", "httpAddr", ":=", "configuration", ".", "GetString", "(", "\"server.http_addr\"", ")", "\n", "if", ...
// get the address for the HTTP server, and parses the optional TLS // configuration for the server - if no TLS configuration is specified, // TLS is not enabled.
[ "get", "the", "address", "for", "the", "HTTP", "server", "and", "parses", "the", "optional", "TLS", "configuration", "for", "the", "server", "-", "if", "no", "TLS", "configuration", "is", "specified", "TLS", "is", "not", "enabled", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-server/config.go#L46-L57
train
theupdateframework/notary
cmd/notary-server/config.go
grpcTLS
func grpcTLS(configuration *viper.Viper) (*tls.Config, error) { rootCA := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_ca_file") clientCert := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_client_cert") clientKey := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_client_key") if clientCert == "" && clientKey != "" || clientCert != "" && clientKey == "" { return nil, fmt.Errorf("either pass both client key and cert, or neither") } tlsConfig, err := tlsconfig.Client(tlsconfig.Options{ CAFile: rootCA, CertFile: clientCert, KeyFile: clientKey, ExclusiveRootPools: true, }) if err != nil { return nil, fmt.Errorf( "Unable to configure TLS to the trust service: %s", err.Error()) } return tlsConfig, nil }
go
func grpcTLS(configuration *viper.Viper) (*tls.Config, error) { rootCA := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_ca_file") clientCert := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_client_cert") clientKey := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_client_key") if clientCert == "" && clientKey != "" || clientCert != "" && clientKey == "" { return nil, fmt.Errorf("either pass both client key and cert, or neither") } tlsConfig, err := tlsconfig.Client(tlsconfig.Options{ CAFile: rootCA, CertFile: clientCert, KeyFile: clientKey, ExclusiveRootPools: true, }) if err != nil { return nil, fmt.Errorf( "Unable to configure TLS to the trust service: %s", err.Error()) } return tlsConfig, nil }
[ "func", "grpcTLS", "(", "configuration", "*", "viper", ".", "Viper", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "rootCA", ":=", "utils", ".", "GetPathRelativeToConfig", "(", "configuration", ",", "\"trust_service.tls_ca_file\"", ")", "\n", ...
// sets up TLS for the GRPC connection to notary-signer
[ "sets", "up", "TLS", "for", "the", "GRPC", "connection", "to", "notary", "-", "signer" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-server/config.go#L60-L80
train
theupdateframework/notary
cmd/notary-server/config.go
getStore
func getStore(configuration *viper.Viper, hRegister healthRegister, doBootstrap bool) ( storage.MetaStore, error) { var store storage.MetaStore backend := configuration.GetString("storage.backend") logrus.Infof("Using %s backend", backend) switch backend { case notary.MemoryBackend: return storage.NewMemStorage(), nil case notary.MySQLBackend, notary.SQLiteBackend, notary.PostgresBackend: storeConfig, err := utils.ParseSQLStorage(configuration) if err != nil { return nil, err } s, err := storage.NewSQLStorage(storeConfig.Backend, storeConfig.Source) if err != nil { return nil, fmt.Errorf("Error starting %s driver: %s", backend, err.Error()) } store = *storage.NewTUFMetaStorage(s) hRegister("DB operational", 10*time.Second, s.CheckHealth) case notary.RethinkDBBackend: var sess *gorethink.Session storeConfig, err := utils.ParseRethinkDBStorage(configuration) if err != nil { return nil, err } tlsOpts := tlsconfig.Options{ CAFile: storeConfig.CA, CertFile: storeConfig.Cert, KeyFile: storeConfig.Key, ExclusiveRootPools: true, } if doBootstrap { sess, err = rethinkdb.AdminConnection(tlsOpts, storeConfig.Source) } else { sess, err = rethinkdb.UserConnection(tlsOpts, storeConfig.Source, storeConfig.Username, storeConfig.Password) } if err != nil { return nil, fmt.Errorf("Error starting %s driver: %s", backend, err.Error()) } s := storage.NewRethinkDBStorage(storeConfig.DBName, storeConfig.Username, storeConfig.Password, sess) store = *storage.NewTUFMetaStorage(s) hRegister("DB operational", 10*time.Second, s.CheckHealth) default: return nil, fmt.Errorf("%s is not a supported storage backend", backend) } return store, nil }
go
func getStore(configuration *viper.Viper, hRegister healthRegister, doBootstrap bool) ( storage.MetaStore, error) { var store storage.MetaStore backend := configuration.GetString("storage.backend") logrus.Infof("Using %s backend", backend) switch backend { case notary.MemoryBackend: return storage.NewMemStorage(), nil case notary.MySQLBackend, notary.SQLiteBackend, notary.PostgresBackend: storeConfig, err := utils.ParseSQLStorage(configuration) if err != nil { return nil, err } s, err := storage.NewSQLStorage(storeConfig.Backend, storeConfig.Source) if err != nil { return nil, fmt.Errorf("Error starting %s driver: %s", backend, err.Error()) } store = *storage.NewTUFMetaStorage(s) hRegister("DB operational", 10*time.Second, s.CheckHealth) case notary.RethinkDBBackend: var sess *gorethink.Session storeConfig, err := utils.ParseRethinkDBStorage(configuration) if err != nil { return nil, err } tlsOpts := tlsconfig.Options{ CAFile: storeConfig.CA, CertFile: storeConfig.Cert, KeyFile: storeConfig.Key, ExclusiveRootPools: true, } if doBootstrap { sess, err = rethinkdb.AdminConnection(tlsOpts, storeConfig.Source) } else { sess, err = rethinkdb.UserConnection(tlsOpts, storeConfig.Source, storeConfig.Username, storeConfig.Password) } if err != nil { return nil, fmt.Errorf("Error starting %s driver: %s", backend, err.Error()) } s := storage.NewRethinkDBStorage(storeConfig.DBName, storeConfig.Username, storeConfig.Password, sess) store = *storage.NewTUFMetaStorage(s) hRegister("DB operational", 10*time.Second, s.CheckHealth) default: return nil, fmt.Errorf("%s is not a supported storage backend", backend) } return store, nil }
[ "func", "getStore", "(", "configuration", "*", "viper", ".", "Viper", ",", "hRegister", "healthRegister", ",", "doBootstrap", "bool", ")", "(", "storage", ".", "MetaStore", ",", "error", ")", "{", "var", "store", "storage", ".", "MetaStore", "\n", "backend",...
// parses the configuration and returns a backing store for the TUF files
[ "parses", "the", "configuration", "and", "returns", "a", "backing", "store", "for", "the", "TUF", "files" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-server/config.go#L83-L130
train
theupdateframework/notary
cmd/notary-server/config.go
getTrustService
func getTrustService(configuration *viper.Viper, sFactory signerFactory, hRegister healthRegister) (signed.CryptoService, string, error) { switch configuration.GetString("trust_service.type") { case "local": logrus.Info("Using local signing service, which requires ED25519. " + "Ignoring all other trust_service parameters, including keyAlgorithm") return signed.NewEd25519(), data.ED25519Key, nil case "remote": default: return nil, "", fmt.Errorf( "must specify either a \"local\" or \"remote\" type for trust_service") } keyAlgo := configuration.GetString("trust_service.key_algorithm") if keyAlgo != data.ED25519Key && keyAlgo != data.ECDSAKey && keyAlgo != data.RSAKey { return nil, "", fmt.Errorf("invalid key algorithm configured: %s", keyAlgo) } clientTLS, err := grpcTLS(configuration) if err != nil { return nil, "", err } logrus.Info("Using remote signing service") notarySigner, err := sFactory( configuration.GetString("trust_service.hostname"), configuration.GetString("trust_service.port"), clientTLS, ) if err != nil { return nil, "", err } duration := 10 * time.Second hRegister( "Trust operational", duration, func() error { err := notarySigner.CheckHealth(duration, notary.HealthCheckOverall) if err != nil { logrus.Error("Trust not fully operational: ", err.Error()) } return err }, ) return notarySigner, keyAlgo, nil }
go
func getTrustService(configuration *viper.Viper, sFactory signerFactory, hRegister healthRegister) (signed.CryptoService, string, error) { switch configuration.GetString("trust_service.type") { case "local": logrus.Info("Using local signing service, which requires ED25519. " + "Ignoring all other trust_service parameters, including keyAlgorithm") return signed.NewEd25519(), data.ED25519Key, nil case "remote": default: return nil, "", fmt.Errorf( "must specify either a \"local\" or \"remote\" type for trust_service") } keyAlgo := configuration.GetString("trust_service.key_algorithm") if keyAlgo != data.ED25519Key && keyAlgo != data.ECDSAKey && keyAlgo != data.RSAKey { return nil, "", fmt.Errorf("invalid key algorithm configured: %s", keyAlgo) } clientTLS, err := grpcTLS(configuration) if err != nil { return nil, "", err } logrus.Info("Using remote signing service") notarySigner, err := sFactory( configuration.GetString("trust_service.hostname"), configuration.GetString("trust_service.port"), clientTLS, ) if err != nil { return nil, "", err } duration := 10 * time.Second hRegister( "Trust operational", duration, func() error { err := notarySigner.CheckHealth(duration, notary.HealthCheckOverall) if err != nil { logrus.Error("Trust not fully operational: ", err.Error()) } return err }, ) return notarySigner, keyAlgo, nil }
[ "func", "getTrustService", "(", "configuration", "*", "viper", ".", "Viper", ",", "sFactory", "signerFactory", ",", "hRegister", "healthRegister", ")", "(", "signed", ".", "CryptoService", ",", "string", ",", "error", ")", "{", "switch", "configuration", ".", ...
// parses the configuration and determines which trust service and key algorithm // to return
[ "parses", "the", "configuration", "and", "determines", "which", "trust", "service", "and", "key", "algorithm", "to", "return" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-server/config.go#L145-L194
train
theupdateframework/notary
trustmanager/remoteks/client.go
NewRemoteStore
func NewRemoteStore(server string, tlsConfig *tls.Config, timeout time.Duration) (*RemoteStore, error) { cc, err := grpc.Dial( server, grpc.WithTransportCredentials( credentials.NewTLS(tlsConfig), ), grpc.WithBlock(), ) if err != nil { return nil, err } if timeout == 0 { timeout = DefaultTimeout } return &RemoteStore{ client: NewStoreClient(cc), location: server, timeout: timeout, }, nil }
go
func NewRemoteStore(server string, tlsConfig *tls.Config, timeout time.Duration) (*RemoteStore, error) { cc, err := grpc.Dial( server, grpc.WithTransportCredentials( credentials.NewTLS(tlsConfig), ), grpc.WithBlock(), ) if err != nil { return nil, err } if timeout == 0 { timeout = DefaultTimeout } return &RemoteStore{ client: NewStoreClient(cc), location: server, timeout: timeout, }, nil }
[ "func", "NewRemoteStore", "(", "server", "string", ",", "tlsConfig", "*", "tls", ".", "Config", ",", "timeout", "time", ".", "Duration", ")", "(", "*", "RemoteStore", ",", "error", ")", "{", "cc", ",", "err", ":=", "grpc", ".", "Dial", "(", "server", ...
// NewRemoteStore instantiates a RemoteStore.
[ "NewRemoteStore", "instantiates", "a", "RemoteStore", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L32-L51
train
theupdateframework/notary
trustmanager/remoteks/client.go
getContext
func (s *RemoteStore) getContext() (context.Context, context.CancelFunc) { return context.WithTimeout(context.Background(), s.timeout) }
go
func (s *RemoteStore) getContext() (context.Context, context.CancelFunc) { return context.WithTimeout(context.Background(), s.timeout) }
[ "func", "(", "s", "*", "RemoteStore", ")", "getContext", "(", ")", "(", "context", ".", "Context", ",", "context", ".", "CancelFunc", ")", "{", "return", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "s", ".", "timeou...
// getContext returns a context with the timeout configured at initialization // time of the RemoteStore.
[ "getContext", "returns", "a", "context", "with", "the", "timeout", "configured", "at", "initialization", "time", "of", "the", "RemoteStore", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L55-L57
train
theupdateframework/notary
trustmanager/remoteks/client.go
Set
func (s *RemoteStore) Set(fileName string, data []byte) error { sm := &SetMsg{ FileName: fileName, Data: data, } ctx, cancel := s.getContext() defer cancel() _, err := s.client.Set(ctx, sm) return err }
go
func (s *RemoteStore) Set(fileName string, data []byte) error { sm := &SetMsg{ FileName: fileName, Data: data, } ctx, cancel := s.getContext() defer cancel() _, err := s.client.Set(ctx, sm) return err }
[ "func", "(", "s", "*", "RemoteStore", ")", "Set", "(", "fileName", "string", ",", "data", "[", "]", "byte", ")", "error", "{", "sm", ":=", "&", "SetMsg", "{", "FileName", ":", "fileName", ",", "Data", ":", "data", ",", "}", "\n", "ctx", ",", "can...
// Set stores the data using the provided fileName
[ "Set", "stores", "the", "data", "using", "the", "provided", "fileName" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L60-L69
train
theupdateframework/notary
trustmanager/remoteks/client.go
Remove
func (s *RemoteStore) Remove(fileName string) error { fm := &FileNameMsg{ FileName: fileName, } ctx, cancel := s.getContext() defer cancel() _, err := s.client.Remove(ctx, fm) return err }
go
func (s *RemoteStore) Remove(fileName string) error { fm := &FileNameMsg{ FileName: fileName, } ctx, cancel := s.getContext() defer cancel() _, err := s.client.Remove(ctx, fm) return err }
[ "func", "(", "s", "*", "RemoteStore", ")", "Remove", "(", "fileName", "string", ")", "error", "{", "fm", ":=", "&", "FileNameMsg", "{", "FileName", ":", "fileName", ",", "}", "\n", "ctx", ",", "cancel", ":=", "s", ".", "getContext", "(", ")", "\n", ...
// Remove deletes a file from the store relative to the store's base directory. // Paths are expected to be cleaned server side.
[ "Remove", "deletes", "a", "file", "from", "the", "store", "relative", "to", "the", "store", "s", "base", "directory", ".", "Paths", "are", "expected", "to", "be", "cleaned", "server", "side", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L73-L81
train
theupdateframework/notary
trustmanager/remoteks/client.go
Get
func (s *RemoteStore) Get(fileName string) ([]byte, error) { fm := &FileNameMsg{ FileName: fileName, } ctx, cancel := s.getContext() defer cancel() bm, err := s.client.Get(ctx, fm) if err != nil { return nil, err } return bm.Data, nil }
go
func (s *RemoteStore) Get(fileName string) ([]byte, error) { fm := &FileNameMsg{ FileName: fileName, } ctx, cancel := s.getContext() defer cancel() bm, err := s.client.Get(ctx, fm) if err != nil { return nil, err } return bm.Data, nil }
[ "func", "(", "s", "*", "RemoteStore", ")", "Get", "(", "fileName", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "fm", ":=", "&", "FileNameMsg", "{", "FileName", ":", "fileName", ",", "}", "\n", "ctx", ",", "cancel", ":=", "s", "....
// Get returns the file content found at fileName relative to the base directory // of the file store. Paths are expected to be cleaned server side.
[ "Get", "returns", "the", "file", "content", "found", "at", "fileName", "relative", "to", "the", "base", "directory", "of", "the", "file", "store", ".", "Paths", "are", "expected", "to", "be", "cleaned", "server", "side", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L85-L96
train
theupdateframework/notary
trustmanager/remoteks/client.go
ListFiles
func (s *RemoteStore) ListFiles() []string { logrus.Infof("listing files from %s", s.location) ctx, cancel := s.getContext() defer cancel() fl, err := s.client.ListFiles(ctx, &google_protobuf.Empty{}) if err != nil { logrus.Errorf("error listing files from %s: %s", s.location, err.Error()) return nil } return fl.FileNames }
go
func (s *RemoteStore) ListFiles() []string { logrus.Infof("listing files from %s", s.location) ctx, cancel := s.getContext() defer cancel() fl, err := s.client.ListFiles(ctx, &google_protobuf.Empty{}) if err != nil { logrus.Errorf("error listing files from %s: %s", s.location, err.Error()) return nil } return fl.FileNames }
[ "func", "(", "s", "*", "RemoteStore", ")", "ListFiles", "(", ")", "[", "]", "string", "{", "logrus", ".", "Infof", "(", "\"listing files from %s\"", ",", "s", ".", "location", ")", "\n", "ctx", ",", "cancel", ":=", "s", ".", "getContext", "(", ")", "...
// ListFiles returns a list of paths relative to the base directory of the // filestore. Any of these paths must be retrievable via the // Storage.Get method.
[ "ListFiles", "returns", "a", "list", "of", "paths", "relative", "to", "the", "base", "directory", "of", "the", "filestore", ".", "Any", "of", "these", "paths", "must", "be", "retrievable", "via", "the", "Storage", ".", "Get", "method", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L101-L111
train
theupdateframework/notary
client/client.go
NewRepository
func NewRepository(gun data.GUN, baseURL string, remoteStore store.RemoteStore, cache store.MetadataStore, trustPinning trustpinning.TrustPinConfig, cryptoService signed.CryptoService, cl changelist.Changelist) (Repository, error) { // Repo's remote store is either a valid remote store or an OfflineStore if remoteStore == nil { remoteStore = store.OfflineStore{} } if cache == nil { return nil, fmt.Errorf("got an invalid cache (nil metadata store)") } nRepo := &repository{ gun: gun, baseURL: baseURL, changelist: cl, cache: cache, remoteStore: remoteStore, cryptoService: cryptoService, trustPinning: trustPinning, LegacyVersions: 0, // By default, don't sign with legacy roles } return nRepo, nil }
go
func NewRepository(gun data.GUN, baseURL string, remoteStore store.RemoteStore, cache store.MetadataStore, trustPinning trustpinning.TrustPinConfig, cryptoService signed.CryptoService, cl changelist.Changelist) (Repository, error) { // Repo's remote store is either a valid remote store or an OfflineStore if remoteStore == nil { remoteStore = store.OfflineStore{} } if cache == nil { return nil, fmt.Errorf("got an invalid cache (nil metadata store)") } nRepo := &repository{ gun: gun, baseURL: baseURL, changelist: cl, cache: cache, remoteStore: remoteStore, cryptoService: cryptoService, trustPinning: trustPinning, LegacyVersions: 0, // By default, don't sign with legacy roles } return nRepo, nil }
[ "func", "NewRepository", "(", "gun", "data", ".", "GUN", ",", "baseURL", "string", ",", "remoteStore", "store", ".", "RemoteStore", ",", "cache", "store", ".", "MetadataStore", ",", "trustPinning", "trustpinning", ".", "TrustPinConfig", ",", "cryptoService", "si...
// NewRepository is the base method that returns a new notary repository. // It expects an initialized cache. In case of a nil remote store, a default // offline store is used.
[ "NewRepository", "is", "the", "base", "method", "that", "returns", "a", "new", "notary", "repository", ".", "It", "expects", "an", "initialized", "cache", ".", "In", "case", "of", "a", "nil", "remote", "store", "a", "default", "offline", "store", "is", "us...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L97-L121
train
theupdateframework/notary
client/client.go
ListTargets
func (r *repository) ListTargets(roles ...data.RoleName) ([]*TargetWithRole, error) { if err := r.updateTUF(false); err != nil { return nil, err } return NewReadOnly(r.tufRepo).ListTargets(roles...) }
go
func (r *repository) ListTargets(roles ...data.RoleName) ([]*TargetWithRole, error) { if err := r.updateTUF(false); err != nil { return nil, err } return NewReadOnly(r.tufRepo).ListTargets(roles...) }
[ "func", "(", "r", "*", "repository", ")", "ListTargets", "(", "roles", "...", "data", ".", "RoleName", ")", "(", "[", "]", "*", "TargetWithRole", ",", "error", ")", "{", "if", "err", ":=", "r", ".", "updateTUF", "(", "false", ")", ";", "err", "!=",...
// ListTargets calls update first before listing targets
[ "ListTargets", "calls", "update", "first", "before", "listing", "targets" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L146-L151
train
theupdateframework/notary
client/client.go
GetTargetByName
func (r *repository) GetTargetByName(name string, roles ...data.RoleName) (*TargetWithRole, error) { if err := r.updateTUF(false); err != nil { return nil, err } return NewReadOnly(r.tufRepo).GetTargetByName(name, roles...) }
go
func (r *repository) GetTargetByName(name string, roles ...data.RoleName) (*TargetWithRole, error) { if err := r.updateTUF(false); err != nil { return nil, err } return NewReadOnly(r.tufRepo).GetTargetByName(name, roles...) }
[ "func", "(", "r", "*", "repository", ")", "GetTargetByName", "(", "name", "string", ",", "roles", "...", "data", ".", "RoleName", ")", "(", "*", "TargetWithRole", ",", "error", ")", "{", "if", "err", ":=", "r", ".", "updateTUF", "(", "false", ")", ";...
// GetTargetByName calls update first before getting target by name
[ "GetTargetByName", "calls", "update", "first", "before", "getting", "target", "by", "name" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L154-L159
train
theupdateframework/notary
client/client.go
GetAllTargetMetadataByName
func (r *repository) GetAllTargetMetadataByName(name string) ([]TargetSignedStruct, error) { if err := r.updateTUF(false); err != nil { return nil, err } return NewReadOnly(r.tufRepo).GetAllTargetMetadataByName(name) }
go
func (r *repository) GetAllTargetMetadataByName(name string) ([]TargetSignedStruct, error) { if err := r.updateTUF(false); err != nil { return nil, err } return NewReadOnly(r.tufRepo).GetAllTargetMetadataByName(name) }
[ "func", "(", "r", "*", "repository", ")", "GetAllTargetMetadataByName", "(", "name", "string", ")", "(", "[", "]", "TargetSignedStruct", ",", "error", ")", "{", "if", "err", ":=", "r", ".", "updateTUF", "(", "false", ")", ";", "err", "!=", "nil", "{", ...
// GetAllTargetMetadataByName calls update first before getting targets by name
[ "GetAllTargetMetadataByName", "calls", "update", "first", "before", "getting", "targets", "by", "name" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L162-L168
train
theupdateframework/notary
client/client.go
ListRoles
func (r *repository) ListRoles() ([]RoleWithSignatures, error) { if err := r.updateTUF(false); err != nil { return nil, err } return NewReadOnly(r.tufRepo).ListRoles() }
go
func (r *repository) ListRoles() ([]RoleWithSignatures, error) { if err := r.updateTUF(false); err != nil { return nil, err } return NewReadOnly(r.tufRepo).ListRoles() }
[ "func", "(", "r", "*", "repository", ")", "ListRoles", "(", ")", "(", "[", "]", "RoleWithSignatures", ",", "error", ")", "{", "if", "err", ":=", "r", ".", "updateTUF", "(", "false", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", ...
// ListRoles calls update first before getting roles
[ "ListRoles", "calls", "update", "first", "before", "getting", "roles" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L171-L176
train
theupdateframework/notary
client/client.go
GetDelegationRoles
func (r *repository) GetDelegationRoles() ([]data.Role, error) { if err := r.updateTUF(false); err != nil { return nil, err } return NewReadOnly(r.tufRepo).GetDelegationRoles() }
go
func (r *repository) GetDelegationRoles() ([]data.Role, error) { if err := r.updateTUF(false); err != nil { return nil, err } return NewReadOnly(r.tufRepo).GetDelegationRoles() }
[ "func", "(", "r", "*", "repository", ")", "GetDelegationRoles", "(", ")", "(", "[", "]", "data", ".", "Role", ",", "error", ")", "{", "if", "err", ":=", "r", ".", "updateTUF", "(", "false", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",",...
// GetDelegationRoles calls update first before getting all delegation roles
[ "GetDelegationRoles", "calls", "update", "first", "before", "getting", "all", "delegation", "roles" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L179-L184
train
theupdateframework/notary
client/client.go
NewTarget
func NewTarget(targetName, targetPath string, targetCustom *canonicaljson.RawMessage) (*Target, error) { b, err := ioutil.ReadFile(targetPath) if err != nil { return nil, err } meta, err := data.NewFileMeta(bytes.NewBuffer(b), data.NotaryDefaultHashes...) if err != nil { return nil, err } return &Target{Name: targetName, Hashes: meta.Hashes, Length: meta.Length, Custom: targetCustom}, nil }
go
func NewTarget(targetName, targetPath string, targetCustom *canonicaljson.RawMessage) (*Target, error) { b, err := ioutil.ReadFile(targetPath) if err != nil { return nil, err } meta, err := data.NewFileMeta(bytes.NewBuffer(b), data.NotaryDefaultHashes...) if err != nil { return nil, err } return &Target{Name: targetName, Hashes: meta.Hashes, Length: meta.Length, Custom: targetCustom}, nil }
[ "func", "NewTarget", "(", "targetName", ",", "targetPath", "string", ",", "targetCustom", "*", "canonicaljson", ".", "RawMessage", ")", "(", "*", "Target", ",", "error", ")", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "targetPath", ")", ...
// NewTarget is a helper method that returns a Target
[ "NewTarget", "is", "a", "helper", "method", "that", "returns", "a", "Target" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L187-L199
train
theupdateframework/notary
client/client.go
rootCertKey
func rootCertKey(gun data.GUN, privKey data.PrivateKey) (data.PublicKey, error) { // Hard-coded policy: the generated certificate expires in 10 years. startTime := time.Now() cert, err := cryptoservice.GenerateCertificate( privKey, gun, startTime, startTime.Add(notary.Year*10)) if err != nil { return nil, err } x509PublicKey := utils.CertToKey(cert) if x509PublicKey == nil { return nil, fmt.Errorf("cannot generate public key from private key with id: %v and algorithm: %v", privKey.ID(), privKey.Algorithm()) } return x509PublicKey, nil }
go
func rootCertKey(gun data.GUN, privKey data.PrivateKey) (data.PublicKey, error) { // Hard-coded policy: the generated certificate expires in 10 years. startTime := time.Now() cert, err := cryptoservice.GenerateCertificate( privKey, gun, startTime, startTime.Add(notary.Year*10)) if err != nil { return nil, err } x509PublicKey := utils.CertToKey(cert) if x509PublicKey == nil { return nil, fmt.Errorf("cannot generate public key from private key with id: %v and algorithm: %v", privKey.ID(), privKey.Algorithm()) } return x509PublicKey, nil }
[ "func", "rootCertKey", "(", "gun", "data", ".", "GUN", ",", "privKey", "data", ".", "PrivateKey", ")", "(", "data", ".", "PublicKey", ",", "error", ")", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "cert", ",", "err", ":=", "cryptoserv...
// rootCertKey generates the corresponding certificate for the private key given the privKey and repo's GUN
[ "rootCertKey", "generates", "the", "corresponding", "certificate", "for", "the", "private", "key", "given", "the", "privKey", "and", "repo", "s", "GUN" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L202-L217
train
theupdateframework/notary
client/client.go
initialize
func (r *repository) initialize(rootKeyIDs []string, rootCerts []data.PublicKey, serverManagedRoles ...data.RoleName) error { // currently we only support server managing timestamps and snapshots, and // nothing else - timestamps are always managed by the server, and implicit // (do not have to be passed in as part of `serverManagedRoles`, so that // the API of Initialize doesn't change). var serverManagesSnapshot bool locallyManagedKeys := []data.RoleName{ data.CanonicalTargetsRole, data.CanonicalSnapshotRole, // root is also locally managed, but that should have been created // already } remotelyManagedKeys := []data.RoleName{data.CanonicalTimestampRole} for _, role := range serverManagedRoles { switch role { case data.CanonicalTimestampRole: continue // timestamp is already in the right place case data.CanonicalSnapshotRole: // because we put Snapshot last locallyManagedKeys = []data.RoleName{data.CanonicalTargetsRole} remotelyManagedKeys = append( remotelyManagedKeys, data.CanonicalSnapshotRole) serverManagesSnapshot = true default: return ErrInvalidRemoteRole{Role: role} } } // gets valid public keys corresponding to the rootKeyIDs or generate if necessary var publicKeys []data.PublicKey var err error if len(rootCerts) == 0 { publicKeys, err = r.createNewPublicKeyFromKeyIDs(rootKeyIDs) } else { publicKeys, err = r.publicKeysOfKeyIDs(rootKeyIDs, rootCerts) } if err != nil { return err } //initialize repo with public keys rootRole, targetsRole, snapshotRole, timestampRole, err := r.initializeRoles( publicKeys, locallyManagedKeys, remotelyManagedKeys, ) if err != nil { return err } r.tufRepo = tuf.NewRepo(r.GetCryptoService()) if err := r.tufRepo.InitRoot( rootRole, timestampRole, snapshotRole, targetsRole, false, ); err != nil { logrus.Debug("Error on InitRoot: ", err.Error()) return err } if _, err := r.tufRepo.InitTargets(data.CanonicalTargetsRole); err != nil { logrus.Debug("Error on InitTargets: ", err.Error()) return err } if err := r.tufRepo.InitSnapshot(); err != nil { logrus.Debug("Error on InitSnapshot: ", err.Error()) return err } return r.saveMetadata(serverManagesSnapshot) }
go
func (r *repository) initialize(rootKeyIDs []string, rootCerts []data.PublicKey, serverManagedRoles ...data.RoleName) error { // currently we only support server managing timestamps and snapshots, and // nothing else - timestamps are always managed by the server, and implicit // (do not have to be passed in as part of `serverManagedRoles`, so that // the API of Initialize doesn't change). var serverManagesSnapshot bool locallyManagedKeys := []data.RoleName{ data.CanonicalTargetsRole, data.CanonicalSnapshotRole, // root is also locally managed, but that should have been created // already } remotelyManagedKeys := []data.RoleName{data.CanonicalTimestampRole} for _, role := range serverManagedRoles { switch role { case data.CanonicalTimestampRole: continue // timestamp is already in the right place case data.CanonicalSnapshotRole: // because we put Snapshot last locallyManagedKeys = []data.RoleName{data.CanonicalTargetsRole} remotelyManagedKeys = append( remotelyManagedKeys, data.CanonicalSnapshotRole) serverManagesSnapshot = true default: return ErrInvalidRemoteRole{Role: role} } } // gets valid public keys corresponding to the rootKeyIDs or generate if necessary var publicKeys []data.PublicKey var err error if len(rootCerts) == 0 { publicKeys, err = r.createNewPublicKeyFromKeyIDs(rootKeyIDs) } else { publicKeys, err = r.publicKeysOfKeyIDs(rootKeyIDs, rootCerts) } if err != nil { return err } //initialize repo with public keys rootRole, targetsRole, snapshotRole, timestampRole, err := r.initializeRoles( publicKeys, locallyManagedKeys, remotelyManagedKeys, ) if err != nil { return err } r.tufRepo = tuf.NewRepo(r.GetCryptoService()) if err := r.tufRepo.InitRoot( rootRole, timestampRole, snapshotRole, targetsRole, false, ); err != nil { logrus.Debug("Error on InitRoot: ", err.Error()) return err } if _, err := r.tufRepo.InitTargets(data.CanonicalTargetsRole); err != nil { logrus.Debug("Error on InitTargets: ", err.Error()) return err } if err := r.tufRepo.InitSnapshot(); err != nil { logrus.Debug("Error on InitSnapshot: ", err.Error()) return err } return r.saveMetadata(serverManagesSnapshot) }
[ "func", "(", "r", "*", "repository", ")", "initialize", "(", "rootKeyIDs", "[", "]", "string", ",", "rootCerts", "[", "]", "data", ".", "PublicKey", ",", "serverManagedRoles", "...", "data", ".", "RoleName", ")", "error", "{", "var", "serverManagesSnapshot",...
// initialize initializes the notary repository with a set of rootkeys, root certificates and roles.
[ "initialize", "initializes", "the", "notary", "repository", "with", "a", "set", "of", "rootkeys", "root", "certificates", "and", "roles", "." ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L225-L298
train
theupdateframework/notary
client/client.go
createNewPublicKeyFromKeyIDs
func (r *repository) createNewPublicKeyFromKeyIDs(keyIDs []string) ([]data.PublicKey, error) { publicKeys := []data.PublicKey{} privKeys, err := getAllPrivKeys(keyIDs, r.GetCryptoService()) if err != nil { return nil, err } for _, privKey := range privKeys { rootKey, err := rootCertKey(r.gun, privKey) if err != nil { return nil, err } publicKeys = append(publicKeys, rootKey) } return publicKeys, nil }
go
func (r *repository) createNewPublicKeyFromKeyIDs(keyIDs []string) ([]data.PublicKey, error) { publicKeys := []data.PublicKey{} privKeys, err := getAllPrivKeys(keyIDs, r.GetCryptoService()) if err != nil { return nil, err } for _, privKey := range privKeys { rootKey, err := rootCertKey(r.gun, privKey) if err != nil { return nil, err } publicKeys = append(publicKeys, rootKey) } return publicKeys, nil }
[ "func", "(", "r", "*", "repository", ")", "createNewPublicKeyFromKeyIDs", "(", "keyIDs", "[", "]", "string", ")", "(", "[", "]", "data", ".", "PublicKey", ",", "error", ")", "{", "publicKeys", ":=", "[", "]", "data", ".", "PublicKey", "{", "}", "\n", ...
// createNewPublicKeyFromKeyIDs generates a set of public keys corresponding to the given list of // key IDs existing in the repository's CryptoService. // the public keys returned are ordered to correspond to the keyIDs
[ "createNewPublicKeyFromKeyIDs", "generates", "a", "set", "of", "public", "keys", "corresponding", "to", "the", "given", "list", "of", "key", "IDs", "existing", "in", "the", "repository", "s", "CryptoService", ".", "the", "public", "keys", "returned", "are", "ord...
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L303-L319
train
theupdateframework/notary
client/client.go
keyExistsInList
func keyExistsInList(cert data.PublicKey, ids map[string]bool) error { pubKeyID, err := utils.CanonicalKeyID(cert) if err != nil { return fmt.Errorf("failed to obtain the public key id from the given certificate: %v", err) } if _, ok := ids[pubKeyID]; ok { return nil } return errKeyNotFound{} }
go
func keyExistsInList(cert data.PublicKey, ids map[string]bool) error { pubKeyID, err := utils.CanonicalKeyID(cert) if err != nil { return fmt.Errorf("failed to obtain the public key id from the given certificate: %v", err) } if _, ok := ids[pubKeyID]; ok { return nil } return errKeyNotFound{} }
[ "func", "keyExistsInList", "(", "cert", "data", ".", "PublicKey", ",", "ids", "map", "[", "string", "]", "bool", ")", "error", "{", "pubKeyID", ",", "err", ":=", "utils", ".", "CanonicalKeyID", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "...
// keyExistsInList returns the id of the private key in ids that matches the public key // otherwise return empty string
[ "keyExistsInList", "returns", "the", "id", "of", "the", "private", "key", "in", "ids", "that", "matches", "the", "public", "key", "otherwise", "return", "empty", "string" ]
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L371-L380
train