repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
theupdateframework/notary | tuf/data/keys.go | NewRSAPublicKey | func NewRSAPublicKey(public []byte) *RSAPublicKey {
return &RSAPublicKey{
TUFKey: TUFKey{
Type: RSAKey,
Value: KeyPair{
Public: public,
Private: nil,
},
},
}
} | go | func NewRSAPublicKey(public []byte) *RSAPublicKey {
return &RSAPublicKey{
TUFKey: TUFKey{
Type: RSAKey,
Value: KeyPair{
Public: public,
Private: nil,
},
},
}
} | [
"func",
"NewRSAPublicKey",
"(",
"public",
"[",
"]",
"byte",
")",
"*",
"RSAPublicKey",
"{",
"return",
"&",
"RSAPublicKey",
"{",
"TUFKey",
":",
"TUFKey",
"{",
"Type",
":",
"RSAKey",
",",
"Value",
":",
"KeyPair",
"{",
"Public",
":",
"public",
",",
"Private",
":",
"nil",
",",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] | // NewRSAPublicKey initializes a new public key with the RSA type | [
"NewRSAPublicKey",
"initializes",
"a",
"new",
"public",
"key",
"with",
"the",
"RSA",
"type"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/keys.go#L301-L311 | train |
theupdateframework/notary | tuf/data/keys.go | NewRSAx509PublicKey | func NewRSAx509PublicKey(public []byte) *RSAx509PublicKey {
return &RSAx509PublicKey{
TUFKey: TUFKey{
Type: RSAx509Key,
Value: KeyPair{
Public: public,
Private: nil,
},
},
}
} | go | func NewRSAx509PublicKey(public []byte) *RSAx509PublicKey {
return &RSAx509PublicKey{
TUFKey: TUFKey{
Type: RSAx509Key,
Value: KeyPair{
Public: public,
Private: nil,
},
},
}
} | [
"func",
"NewRSAx509PublicKey",
"(",
"public",
"[",
"]",
"byte",
")",
"*",
"RSAx509PublicKey",
"{",
"return",
"&",
"RSAx509PublicKey",
"{",
"TUFKey",
":",
"TUFKey",
"{",
"Type",
":",
"RSAx509Key",
",",
"Value",
":",
"KeyPair",
"{",
"Public",
":",
"public",
",",
"Private",
":",
"nil",
",",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] | // NewRSAx509PublicKey initializes a new public key with the RSAx509Key type | [
"NewRSAx509PublicKey",
"initializes",
"a",
"new",
"public",
"key",
"with",
"the",
"RSAx509Key",
"type"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/keys.go#L314-L324 | train |
theupdateframework/notary | tuf/data/keys.go | NewED25519PublicKey | func NewED25519PublicKey(public []byte) *ED25519PublicKey {
return &ED25519PublicKey{
TUFKey: TUFKey{
Type: ED25519Key,
Value: KeyPair{
Public: public,
Private: nil,
},
},
}
} | go | func NewED25519PublicKey(public []byte) *ED25519PublicKey {
return &ED25519PublicKey{
TUFKey: TUFKey{
Type: ED25519Key,
Value: KeyPair{
Public: public,
Private: nil,
},
},
}
} | [
"func",
"NewED25519PublicKey",
"(",
"public",
"[",
"]",
"byte",
")",
"*",
"ED25519PublicKey",
"{",
"return",
"&",
"ED25519PublicKey",
"{",
"TUFKey",
":",
"TUFKey",
"{",
"Type",
":",
"ED25519Key",
",",
"Value",
":",
"KeyPair",
"{",
"Public",
":",
"public",
",",
"Private",
":",
"nil",
",",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] | // NewED25519PublicKey initializes a new public key with the ED25519Key type | [
"NewED25519PublicKey",
"initializes",
"a",
"new",
"public",
"key",
"with",
"the",
"ED25519Key",
"type"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/keys.go#L327-L337 | train |
theupdateframework/notary | tuf/data/keys.go | NewECDSAPrivateKey | func NewECDSAPrivateKey(public PublicKey, private []byte) (*ECDSAPrivateKey, error) {
switch public.(type) {
case *ECDSAPublicKey, *ECDSAx509PublicKey:
default:
return nil, errors.New("invalid public key type provided to NewECDSAPrivateKey")
}
ecdsaPrivKey, err := x509.ParseECPrivateKey(private)
if err != nil {
return nil, err
}
return &ECDSAPrivateKey{
PublicKey: public,
privateKey: privateKey{private: private},
signer: signer{signer: ecdsaPrivKey},
}, nil
} | go | func NewECDSAPrivateKey(public PublicKey, private []byte) (*ECDSAPrivateKey, error) {
switch public.(type) {
case *ECDSAPublicKey, *ECDSAx509PublicKey:
default:
return nil, errors.New("invalid public key type provided to NewECDSAPrivateKey")
}
ecdsaPrivKey, err := x509.ParseECPrivateKey(private)
if err != nil {
return nil, err
}
return &ECDSAPrivateKey{
PublicKey: public,
privateKey: privateKey{private: private},
signer: signer{signer: ecdsaPrivKey},
}, nil
} | [
"func",
"NewECDSAPrivateKey",
"(",
"public",
"PublicKey",
",",
"private",
"[",
"]",
"byte",
")",
"(",
"*",
"ECDSAPrivateKey",
",",
"error",
")",
"{",
"switch",
"public",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ECDSAPublicKey",
",",
"*",
"ECDSAx509PublicKey",
":",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ecdsaPrivKey",
",",
"err",
":=",
"x509",
".",
"ParseECPrivateKey",
"(",
"private",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"ECDSAPrivateKey",
"{",
"PublicKey",
":",
"public",
",",
"privateKey",
":",
"privateKey",
"{",
"private",
":",
"private",
"}",
",",
"signer",
":",
"signer",
"{",
"signer",
":",
"ecdsaPrivKey",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewECDSAPrivateKey initializes a new ECDSA private key | [
"NewECDSAPrivateKey",
"initializes",
"a",
"new",
"ECDSA",
"private",
"key"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/keys.go#L375-L390 | train |
theupdateframework/notary | tuf/data/keys.go | NewRSAPrivateKey | func NewRSAPrivateKey(public PublicKey, private []byte) (*RSAPrivateKey, error) {
switch public.(type) {
case *RSAPublicKey, *RSAx509PublicKey:
default:
return nil, errors.New("invalid public key type provided to NewRSAPrivateKey")
}
rsaPrivKey, err := x509.ParsePKCS1PrivateKey(private)
if err != nil {
return nil, err
}
return &RSAPrivateKey{
PublicKey: public,
privateKey: privateKey{private: private},
signer: signer{signer: rsaPrivKey},
}, nil
} | go | func NewRSAPrivateKey(public PublicKey, private []byte) (*RSAPrivateKey, error) {
switch public.(type) {
case *RSAPublicKey, *RSAx509PublicKey:
default:
return nil, errors.New("invalid public key type provided to NewRSAPrivateKey")
}
rsaPrivKey, err := x509.ParsePKCS1PrivateKey(private)
if err != nil {
return nil, err
}
return &RSAPrivateKey{
PublicKey: public,
privateKey: privateKey{private: private},
signer: signer{signer: rsaPrivKey},
}, nil
} | [
"func",
"NewRSAPrivateKey",
"(",
"public",
"PublicKey",
",",
"private",
"[",
"]",
"byte",
")",
"(",
"*",
"RSAPrivateKey",
",",
"error",
")",
"{",
"switch",
"public",
".",
"(",
"type",
")",
"{",
"case",
"*",
"RSAPublicKey",
",",
"*",
"RSAx509PublicKey",
":",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"rsaPrivKey",
",",
"err",
":=",
"x509",
".",
"ParsePKCS1PrivateKey",
"(",
"private",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"RSAPrivateKey",
"{",
"PublicKey",
":",
"public",
",",
"privateKey",
":",
"privateKey",
"{",
"private",
":",
"private",
"}",
",",
"signer",
":",
"signer",
"{",
"signer",
":",
"rsaPrivKey",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewRSAPrivateKey initialized a new RSA private key | [
"NewRSAPrivateKey",
"initialized",
"a",
"new",
"RSA",
"private",
"key"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/keys.go#L393-L408 | train |
theupdateframework/notary | tuf/data/keys.go | NewED25519PrivateKey | func NewED25519PrivateKey(public ED25519PublicKey, private []byte) (*ED25519PrivateKey, error) {
return &ED25519PrivateKey{
ED25519PublicKey: public,
privateKey: privateKey{private: private},
}, nil
} | go | func NewED25519PrivateKey(public ED25519PublicKey, private []byte) (*ED25519PrivateKey, error) {
return &ED25519PrivateKey{
ED25519PublicKey: public,
privateKey: privateKey{private: private},
}, nil
} | [
"func",
"NewED25519PrivateKey",
"(",
"public",
"ED25519PublicKey",
",",
"private",
"[",
"]",
"byte",
")",
"(",
"*",
"ED25519PrivateKey",
",",
"error",
")",
"{",
"return",
"&",
"ED25519PrivateKey",
"{",
"ED25519PublicKey",
":",
"public",
",",
"privateKey",
":",
"privateKey",
"{",
"private",
":",
"private",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewED25519PrivateKey initialized a new ED25519 private key | [
"NewED25519PrivateKey",
"initialized",
"a",
"new",
"ED25519",
"private",
"key"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/keys.go#L411-L416 | train |
theupdateframework/notary | tuf/data/keys.go | Sign | func (k ECDSAPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
ecdsaPrivKey, ok := k.CryptoSigner().(*ecdsa.PrivateKey)
if !ok {
return nil, errors.New("signer was based on the wrong key type")
}
hashed := sha256.Sum256(msg)
sigASN1, err := ecdsaPrivKey.Sign(rand, hashed[:], opts)
if err != nil {
return nil, err
}
sig := ecdsaSig{}
_, err = asn1.Unmarshal(sigASN1, &sig)
if err != nil {
return nil, err
}
rBytes, sBytes := sig.R.Bytes(), sig.S.Bytes()
octetLength := (ecdsaPrivKey.Params().BitSize + 7) >> 3
// MUST include leading zeros in the output
rBuf := make([]byte, octetLength-len(rBytes), octetLength)
sBuf := make([]byte, octetLength-len(sBytes), octetLength)
rBuf = append(rBuf, rBytes...)
sBuf = append(sBuf, sBytes...)
return append(rBuf, sBuf...), nil
} | go | func (k ECDSAPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
ecdsaPrivKey, ok := k.CryptoSigner().(*ecdsa.PrivateKey)
if !ok {
return nil, errors.New("signer was based on the wrong key type")
}
hashed := sha256.Sum256(msg)
sigASN1, err := ecdsaPrivKey.Sign(rand, hashed[:], opts)
if err != nil {
return nil, err
}
sig := ecdsaSig{}
_, err = asn1.Unmarshal(sigASN1, &sig)
if err != nil {
return nil, err
}
rBytes, sBytes := sig.R.Bytes(), sig.S.Bytes()
octetLength := (ecdsaPrivKey.Params().BitSize + 7) >> 3
// MUST include leading zeros in the output
rBuf := make([]byte, octetLength-len(rBytes), octetLength)
sBuf := make([]byte, octetLength-len(sBytes), octetLength)
rBuf = append(rBuf, rBytes...)
sBuf = append(sBuf, sBytes...)
return append(rBuf, sBuf...), nil
} | [
"func",
"(",
"k",
"ECDSAPrivateKey",
")",
"Sign",
"(",
"rand",
"io",
".",
"Reader",
",",
"msg",
"[",
"]",
"byte",
",",
"opts",
"crypto",
".",
"SignerOpts",
")",
"(",
"signature",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"ecdsaPrivKey",
",",
"ok",
":=",
"k",
".",
"CryptoSigner",
"(",
")",
".",
"(",
"*",
"ecdsa",
".",
"PrivateKey",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"hashed",
":=",
"sha256",
".",
"Sum256",
"(",
"msg",
")",
"\n",
"sigASN1",
",",
"err",
":=",
"ecdsaPrivKey",
".",
"Sign",
"(",
"rand",
",",
"hashed",
"[",
":",
"]",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"sig",
":=",
"ecdsaSig",
"{",
"}",
"\n",
"_",
",",
"err",
"=",
"asn1",
".",
"Unmarshal",
"(",
"sigASN1",
",",
"&",
"sig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"rBytes",
",",
"sBytes",
":=",
"sig",
".",
"R",
".",
"Bytes",
"(",
")",
",",
"sig",
".",
"S",
".",
"Bytes",
"(",
")",
"\n",
"octetLength",
":=",
"(",
"ecdsaPrivKey",
".",
"Params",
"(",
")",
".",
"BitSize",
"+",
"7",
")",
">>",
"3",
"\n\n",
"// MUST include leading zeros in the output",
"rBuf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"octetLength",
"-",
"len",
"(",
"rBytes",
")",
",",
"octetLength",
")",
"\n",
"sBuf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"octetLength",
"-",
"len",
"(",
"sBytes",
")",
",",
"octetLength",
")",
"\n\n",
"rBuf",
"=",
"append",
"(",
"rBuf",
",",
"rBytes",
"...",
")",
"\n",
"sBuf",
"=",
"append",
"(",
"sBuf",
",",
"sBytes",
"...",
")",
"\n",
"return",
"append",
"(",
"rBuf",
",",
"sBuf",
"...",
")",
",",
"nil",
"\n",
"}"
] | // Sign creates an ecdsa signature | [
"Sign",
"creates",
"an",
"ecdsa",
"signature"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/keys.go#L445-L471 | train |
theupdateframework/notary | tuf/data/keys.go | Sign | func (k RSAPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
hashed := sha256.Sum256(msg)
if opts == nil {
opts = &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthEqualsHash,
Hash: crypto.SHA256,
}
}
return k.CryptoSigner().Sign(rand, hashed[:], opts)
} | go | func (k RSAPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
hashed := sha256.Sum256(msg)
if opts == nil {
opts = &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthEqualsHash,
Hash: crypto.SHA256,
}
}
return k.CryptoSigner().Sign(rand, hashed[:], opts)
} | [
"func",
"(",
"k",
"RSAPrivateKey",
")",
"Sign",
"(",
"rand",
"io",
".",
"Reader",
",",
"msg",
"[",
"]",
"byte",
",",
"opts",
"crypto",
".",
"SignerOpts",
")",
"(",
"signature",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"hashed",
":=",
"sha256",
".",
"Sum256",
"(",
"msg",
")",
"\n",
"if",
"opts",
"==",
"nil",
"{",
"opts",
"=",
"&",
"rsa",
".",
"PSSOptions",
"{",
"SaltLength",
":",
"rsa",
".",
"PSSSaltLengthEqualsHash",
",",
"Hash",
":",
"crypto",
".",
"SHA256",
",",
"}",
"\n",
"}",
"\n",
"return",
"k",
".",
"CryptoSigner",
"(",
")",
".",
"Sign",
"(",
"rand",
",",
"hashed",
"[",
":",
"]",
",",
"opts",
")",
"\n",
"}"
] | // Sign creates an rsa signature | [
"Sign",
"creates",
"an",
"rsa",
"signature"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/keys.go#L474-L483 | train |
theupdateframework/notary | tuf/data/keys.go | Sign | func (k ED25519PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
priv := make([]byte, ed25519.PrivateKeySize)
// The ed25519 key is serialized as public key then private key, so just use private key here.
copy(priv, k.private[ed25519.PublicKeySize:])
return ed25519.Sign(ed25519.PrivateKey(priv), msg)[:], nil
} | go | func (k ED25519PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
priv := make([]byte, ed25519.PrivateKeySize)
// The ed25519 key is serialized as public key then private key, so just use private key here.
copy(priv, k.private[ed25519.PublicKeySize:])
return ed25519.Sign(ed25519.PrivateKey(priv), msg)[:], nil
} | [
"func",
"(",
"k",
"ED25519PrivateKey",
")",
"Sign",
"(",
"rand",
"io",
".",
"Reader",
",",
"msg",
"[",
"]",
"byte",
",",
"opts",
"crypto",
".",
"SignerOpts",
")",
"(",
"signature",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"priv",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"ed25519",
".",
"PrivateKeySize",
")",
"\n",
"// The ed25519 key is serialized as public key then private key, so just use private key here.",
"copy",
"(",
"priv",
",",
"k",
".",
"private",
"[",
"ed25519",
".",
"PublicKeySize",
":",
"]",
")",
"\n",
"return",
"ed25519",
".",
"Sign",
"(",
"ed25519",
".",
"PrivateKey",
"(",
"priv",
")",
",",
"msg",
")",
"[",
":",
"]",
",",
"nil",
"\n",
"}"
] | // Sign creates an ed25519 signature | [
"Sign",
"creates",
"an",
"ed25519",
"signature"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/keys.go#L486-L491 | train |
theupdateframework/notary | tuf/data/keys.go | Sign | func (k UnknownPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
return nil, errors.New("unknown key type, cannot sign")
} | go | func (k UnknownPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
return nil, errors.New("unknown key type, cannot sign")
} | [
"func",
"(",
"k",
"UnknownPrivateKey",
")",
"Sign",
"(",
"rand",
"io",
".",
"Reader",
",",
"msg",
"[",
"]",
"byte",
",",
"opts",
"crypto",
".",
"SignerOpts",
")",
"(",
"signature",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Sign on an UnknownPrivateKey raises an error because the client does not
// know how to sign with this key type. | [
"Sign",
"on",
"an",
"UnknownPrivateKey",
"raises",
"an",
"error",
"because",
"the",
"client",
"does",
"not",
"know",
"how",
"to",
"sign",
"with",
"this",
"key",
"type",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/keys.go#L495-L497 | train |
theupdateframework/notary | tuf/data/keys.go | PublicKeyFromPrivate | func PublicKeyFromPrivate(pk PrivateKey) PublicKey {
return typedPublicKey(TUFKey{
Type: pk.Algorithm(),
Value: KeyPair{
Public: pk.Public(),
Private: nil,
},
})
} | go | func PublicKeyFromPrivate(pk PrivateKey) PublicKey {
return typedPublicKey(TUFKey{
Type: pk.Algorithm(),
Value: KeyPair{
Public: pk.Public(),
Private: nil,
},
})
} | [
"func",
"PublicKeyFromPrivate",
"(",
"pk",
"PrivateKey",
")",
"PublicKey",
"{",
"return",
"typedPublicKey",
"(",
"TUFKey",
"{",
"Type",
":",
"pk",
".",
"Algorithm",
"(",
")",
",",
"Value",
":",
"KeyPair",
"{",
"Public",
":",
"pk",
".",
"Public",
"(",
")",
",",
"Private",
":",
"nil",
",",
"}",
",",
"}",
")",
"\n",
"}"
] | // PublicKeyFromPrivate returns a new TUFKey based on a private key, with
// the private key bytes guaranteed to be nil. | [
"PublicKeyFromPrivate",
"returns",
"a",
"new",
"TUFKey",
"based",
"on",
"a",
"private",
"key",
"with",
"the",
"private",
"key",
"bytes",
"guaranteed",
"to",
"be",
"nil",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/keys.go#L521-L529 | train |
theupdateframework/notary | cmd/notary/prettyprint.go | prettyPrintKeys | func prettyPrintKeys(keyStores []trustmanager.KeyStore, writer io.Writer) {
var info []keyInfo
for _, store := range keyStores {
for keyID, keyIDInfo := range store.ListKeys() {
info = append(info, keyInfo{
role: keyIDInfo.Role,
location: store.Name(),
gun: keyIDInfo.Gun,
keyID: keyID,
})
}
}
if len(info) == 0 {
writer.Write([]byte("No signing keys found.\n"))
return
}
sort.Stable(keyInfoSorter(info))
tw := initTabWriter([]string{"ROLE", "GUN", "KEY ID", "LOCATION"}, writer)
for _, oneKeyInfo := range info {
fmt.Fprintf(
tw,
fourItemRow,
oneKeyInfo.role,
truncateWithEllipsis(oneKeyInfo.gun.String(), maxGUNWidth, true),
oneKeyInfo.keyID,
truncateWithEllipsis(oneKeyInfo.location, maxLocWidth, true),
)
}
tw.Flush()
} | go | func prettyPrintKeys(keyStores []trustmanager.KeyStore, writer io.Writer) {
var info []keyInfo
for _, store := range keyStores {
for keyID, keyIDInfo := range store.ListKeys() {
info = append(info, keyInfo{
role: keyIDInfo.Role,
location: store.Name(),
gun: keyIDInfo.Gun,
keyID: keyID,
})
}
}
if len(info) == 0 {
writer.Write([]byte("No signing keys found.\n"))
return
}
sort.Stable(keyInfoSorter(info))
tw := initTabWriter([]string{"ROLE", "GUN", "KEY ID", "LOCATION"}, writer)
for _, oneKeyInfo := range info {
fmt.Fprintf(
tw,
fourItemRow,
oneKeyInfo.role,
truncateWithEllipsis(oneKeyInfo.gun.String(), maxGUNWidth, true),
oneKeyInfo.keyID,
truncateWithEllipsis(oneKeyInfo.location, maxLocWidth, true),
)
}
tw.Flush()
} | [
"func",
"prettyPrintKeys",
"(",
"keyStores",
"[",
"]",
"trustmanager",
".",
"KeyStore",
",",
"writer",
"io",
".",
"Writer",
")",
"{",
"var",
"info",
"[",
"]",
"keyInfo",
"\n\n",
"for",
"_",
",",
"store",
":=",
"range",
"keyStores",
"{",
"for",
"keyID",
",",
"keyIDInfo",
":=",
"range",
"store",
".",
"ListKeys",
"(",
")",
"{",
"info",
"=",
"append",
"(",
"info",
",",
"keyInfo",
"{",
"role",
":",
"keyIDInfo",
".",
"Role",
",",
"location",
":",
"store",
".",
"Name",
"(",
")",
",",
"gun",
":",
"keyIDInfo",
".",
"Gun",
",",
"keyID",
":",
"keyID",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"info",
")",
"==",
"0",
"{",
"writer",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\\n",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"sort",
".",
"Stable",
"(",
"keyInfoSorter",
"(",
"info",
")",
")",
"\n\n",
"tw",
":=",
"initTabWriter",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"writer",
")",
"\n\n",
"for",
"_",
",",
"oneKeyInfo",
":=",
"range",
"info",
"{",
"fmt",
".",
"Fprintf",
"(",
"tw",
",",
"fourItemRow",
",",
"oneKeyInfo",
".",
"role",
",",
"truncateWithEllipsis",
"(",
"oneKeyInfo",
".",
"gun",
".",
"String",
"(",
")",
",",
"maxGUNWidth",
",",
"true",
")",
",",
"oneKeyInfo",
".",
"keyID",
",",
"truncateWithEllipsis",
"(",
"oneKeyInfo",
".",
"location",
",",
"maxLocWidth",
",",
"true",
")",
",",
")",
"\n",
"}",
"\n",
"tw",
".",
"Flush",
"(",
")",
"\n",
"}"
] | // Given a list of KeyStores in order of listing preference, pretty-prints the
// root keys and then the signing keys. | [
"Given",
"a",
"list",
"of",
"KeyStores",
"in",
"order",
"of",
"listing",
"preference",
"pretty",
"-",
"prints",
"the",
"root",
"keys",
"and",
"then",
"the",
"signing",
"keys",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/prettyprint.go#L98-L132 | train |
theupdateframework/notary | cmd/notary/prettyprint.go | prettyPrintTargets | func prettyPrintTargets(ts []*client.TargetWithRole, writer io.Writer) {
if len(ts) == 0 {
writer.Write([]byte("\nNo targets present in this repository.\n\n"))
return
}
sort.Stable(targetsSorter(ts))
tw := initTabWriter([]string{"NAME", "DIGEST", "SIZE (BYTES)", "ROLE"}, writer)
for _, t := range ts {
fmt.Fprintf(
tw,
fourItemRow,
t.Name,
hex.EncodeToString(t.Hashes["sha256"]),
fmt.Sprintf("%d", t.Length),
t.Role,
)
}
tw.Flush()
} | go | func prettyPrintTargets(ts []*client.TargetWithRole, writer io.Writer) {
if len(ts) == 0 {
writer.Write([]byte("\nNo targets present in this repository.\n\n"))
return
}
sort.Stable(targetsSorter(ts))
tw := initTabWriter([]string{"NAME", "DIGEST", "SIZE (BYTES)", "ROLE"}, writer)
for _, t := range ts {
fmt.Fprintf(
tw,
fourItemRow,
t.Name,
hex.EncodeToString(t.Hashes["sha256"]),
fmt.Sprintf("%d", t.Length),
t.Role,
)
}
tw.Flush()
} | [
"func",
"prettyPrintTargets",
"(",
"ts",
"[",
"]",
"*",
"client",
".",
"TargetWithRole",
",",
"writer",
"io",
".",
"Writer",
")",
"{",
"if",
"len",
"(",
"ts",
")",
"==",
"0",
"{",
"writer",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\\n",
"\\n",
"\\n",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"sort",
".",
"Stable",
"(",
"targetsSorter",
"(",
"ts",
")",
")",
"\n\n",
"tw",
":=",
"initTabWriter",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"writer",
")",
"\n\n",
"for",
"_",
",",
"t",
":=",
"range",
"ts",
"{",
"fmt",
".",
"Fprintf",
"(",
"tw",
",",
"fourItemRow",
",",
"t",
".",
"Name",
",",
"hex",
".",
"EncodeToString",
"(",
"t",
".",
"Hashes",
"[",
"\"",
"\"",
"]",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Length",
")",
",",
"t",
".",
"Role",
",",
")",
"\n",
"}",
"\n",
"tw",
".",
"Flush",
"(",
")",
"\n",
"}"
] | // Pretty-prints the sorted list of TargetWithRoles. | [
"Pretty",
"-",
"prints",
"the",
"sorted",
"list",
"of",
"TargetWithRoles",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/prettyprint.go#L155-L176 | train |
theupdateframework/notary | cmd/notary/prettyprint.go | prettyPrintRoles | func prettyPrintRoles(rs []data.Role, writer io.Writer, roleType string) {
if len(rs) == 0 {
writer.Write([]byte(fmt.Sprintf("\nNo %s present in this repository.\n\n", roleType)))
return
}
// this sorter works for Role types
sort.Stable(roleSorter(rs))
tw := initTabWriter([]string{"ROLE", "PATHS", "KEY IDS", "THRESHOLD"}, writer)
for _, r := range rs {
var path, kid string
pp := prettyPaths(r.Paths)
if len(pp) > 0 {
path = pp[0]
}
if len(r.KeyIDs) > 0 {
kid = r.KeyIDs[0]
}
fmt.Fprintf(
tw,
fourItemRow,
r.Name,
path,
kid,
fmt.Sprintf("%v", r.Threshold),
)
printExtraRoleRows(tw, pp, r.KeyIDs)
}
tw.Flush()
} | go | func prettyPrintRoles(rs []data.Role, writer io.Writer, roleType string) {
if len(rs) == 0 {
writer.Write([]byte(fmt.Sprintf("\nNo %s present in this repository.\n\n", roleType)))
return
}
// this sorter works for Role types
sort.Stable(roleSorter(rs))
tw := initTabWriter([]string{"ROLE", "PATHS", "KEY IDS", "THRESHOLD"}, writer)
for _, r := range rs {
var path, kid string
pp := prettyPaths(r.Paths)
if len(pp) > 0 {
path = pp[0]
}
if len(r.KeyIDs) > 0 {
kid = r.KeyIDs[0]
}
fmt.Fprintf(
tw,
fourItemRow,
r.Name,
path,
kid,
fmt.Sprintf("%v", r.Threshold),
)
printExtraRoleRows(tw, pp, r.KeyIDs)
}
tw.Flush()
} | [
"func",
"prettyPrintRoles",
"(",
"rs",
"[",
"]",
"data",
".",
"Role",
",",
"writer",
"io",
".",
"Writer",
",",
"roleType",
"string",
")",
"{",
"if",
"len",
"(",
"rs",
")",
"==",
"0",
"{",
"writer",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\\n",
"\\n",
"\"",
",",
"roleType",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// this sorter works for Role types",
"sort",
".",
"Stable",
"(",
"roleSorter",
"(",
"rs",
")",
")",
"\n\n",
"tw",
":=",
"initTabWriter",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"writer",
")",
"\n\n",
"for",
"_",
",",
"r",
":=",
"range",
"rs",
"{",
"var",
"path",
",",
"kid",
"string",
"\n",
"pp",
":=",
"prettyPaths",
"(",
"r",
".",
"Paths",
")",
"\n",
"if",
"len",
"(",
"pp",
")",
">",
"0",
"{",
"path",
"=",
"pp",
"[",
"0",
"]",
"\n",
"}",
"\n",
"if",
"len",
"(",
"r",
".",
"KeyIDs",
")",
">",
"0",
"{",
"kid",
"=",
"r",
".",
"KeyIDs",
"[",
"0",
"]",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"tw",
",",
"fourItemRow",
",",
"r",
".",
"Name",
",",
"path",
",",
"kid",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"Threshold",
")",
",",
")",
"\n",
"printExtraRoleRows",
"(",
"tw",
",",
"pp",
",",
"r",
".",
"KeyIDs",
")",
"\n",
"}",
"\n",
"tw",
".",
"Flush",
"(",
")",
"\n",
"}"
] | // Pretty-prints the list of provided Roles | [
"Pretty",
"-",
"prints",
"the",
"list",
"of",
"provided",
"Roles"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/prettyprint.go#L179-L210 | train |
theupdateframework/notary | cmd/notary/prettyprint.go | prettyPaths | func prettyPaths(paths []string) []string {
// sort paths first
sort.Strings(paths)
pp := make([]string, 0, len(paths))
for _, path := range paths {
// manually escape "" and designate that it is all paths with an extra print <all paths>
if path == "" {
path = "\"\" <all paths>"
}
pp = append(pp, path)
}
return pp
} | go | func prettyPaths(paths []string) []string {
// sort paths first
sort.Strings(paths)
pp := make([]string, 0, len(paths))
for _, path := range paths {
// manually escape "" and designate that it is all paths with an extra print <all paths>
if path == "" {
path = "\"\" <all paths>"
}
pp = append(pp, path)
}
return pp
} | [
"func",
"prettyPaths",
"(",
"paths",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"// sort paths first",
"sort",
".",
"Strings",
"(",
"paths",
")",
"\n",
"pp",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"paths",
")",
")",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"paths",
"{",
"// manually escape \"\" and designate that it is all paths with an extra print <all paths>",
"if",
"path",
"==",
"\"",
"\"",
"{",
"path",
"=",
"\"",
"\\\"",
"\\\"",
"\"",
"\n",
"}",
"\n",
"pp",
"=",
"append",
"(",
"pp",
",",
"path",
")",
"\n",
"}",
"\n",
"return",
"pp",
"\n",
"}"
] | // Pretty-formats a list of delegation paths, and ensures the empty string is printed as "" in the console | [
"Pretty",
"-",
"formats",
"a",
"list",
"of",
"delegation",
"paths",
"and",
"ensures",
"the",
"empty",
"string",
"is",
"printed",
"as",
"in",
"the",
"console"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/prettyprint.go#L239-L251 | train |
theupdateframework/notary | client/helpers.go | getRemoteStore | func getRemoteStore(baseURL string, gun data.GUN, rt http.RoundTripper) (store.RemoteStore, error) {
s, err := store.NewHTTPStore(
baseURL+"/v2/"+gun.String()+"/_trust/tuf/",
"",
"json",
"key",
rt,
)
if err != nil {
return store.OfflineStore{}, err
}
return s, nil
} | go | func getRemoteStore(baseURL string, gun data.GUN, rt http.RoundTripper) (store.RemoteStore, error) {
s, err := store.NewHTTPStore(
baseURL+"/v2/"+gun.String()+"/_trust/tuf/",
"",
"json",
"key",
rt,
)
if err != nil {
return store.OfflineStore{}, err
}
return s, nil
} | [
"func",
"getRemoteStore",
"(",
"baseURL",
"string",
",",
"gun",
"data",
".",
"GUN",
",",
"rt",
"http",
".",
"RoundTripper",
")",
"(",
"store",
".",
"RemoteStore",
",",
"error",
")",
"{",
"s",
",",
"err",
":=",
"store",
".",
"NewHTTPStore",
"(",
"baseURL",
"+",
"\"",
"\"",
"+",
"gun",
".",
"String",
"(",
")",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"rt",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"store",
".",
"OfflineStore",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // Use this to initialize remote HTTPStores from the config settings | [
"Use",
"this",
"to",
"initialize",
"remote",
"HTTPStores",
"from",
"the",
"config",
"settings"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/helpers.go#L19-L31 | train |
theupdateframework/notary | client/helpers.go | getRemoteKey | func getRemoteKey(role data.RoleName, remote store.RemoteStore) (data.PublicKey, error) {
rawPubKey, err := remote.GetKey(role)
if err != nil {
return nil, err
}
pubKey, err := data.UnmarshalPublicKey(rawPubKey)
if err != nil {
return nil, err
}
return pubKey, nil
} | go | func getRemoteKey(role data.RoleName, remote store.RemoteStore) (data.PublicKey, error) {
rawPubKey, err := remote.GetKey(role)
if err != nil {
return nil, err
}
pubKey, err := data.UnmarshalPublicKey(rawPubKey)
if err != nil {
return nil, err
}
return pubKey, nil
} | [
"func",
"getRemoteKey",
"(",
"role",
"data",
".",
"RoleName",
",",
"remote",
"store",
".",
"RemoteStore",
")",
"(",
"data",
".",
"PublicKey",
",",
"error",
")",
"{",
"rawPubKey",
",",
"err",
":=",
"remote",
".",
"GetKey",
"(",
"role",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"pubKey",
",",
"err",
":=",
"data",
".",
"UnmarshalPublicKey",
"(",
"rawPubKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"pubKey",
",",
"nil",
"\n",
"}"
] | // Fetches a public key from a remote store, given a gun and role | [
"Fetches",
"a",
"public",
"key",
"from",
"a",
"remote",
"store",
"given",
"a",
"gun",
"and",
"role"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/helpers.go#L222-L234 | train |
theupdateframework/notary | client/helpers.go | rotateRemoteKey | func rotateRemoteKey(role data.RoleName, remote store.RemoteStore) (data.PublicKey, error) {
rawPubKey, err := remote.RotateKey(role)
if err != nil {
return nil, err
}
pubKey, err := data.UnmarshalPublicKey(rawPubKey)
if err != nil {
return nil, err
}
return pubKey, nil
} | go | func rotateRemoteKey(role data.RoleName, remote store.RemoteStore) (data.PublicKey, error) {
rawPubKey, err := remote.RotateKey(role)
if err != nil {
return nil, err
}
pubKey, err := data.UnmarshalPublicKey(rawPubKey)
if err != nil {
return nil, err
}
return pubKey, nil
} | [
"func",
"rotateRemoteKey",
"(",
"role",
"data",
".",
"RoleName",
",",
"remote",
"store",
".",
"RemoteStore",
")",
"(",
"data",
".",
"PublicKey",
",",
"error",
")",
"{",
"rawPubKey",
",",
"err",
":=",
"remote",
".",
"RotateKey",
"(",
"role",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"pubKey",
",",
"err",
":=",
"data",
".",
"UnmarshalPublicKey",
"(",
"rawPubKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"pubKey",
",",
"nil",
"\n",
"}"
] | // Rotates a private key in a remote store and returns the public key component | [
"Rotates",
"a",
"private",
"key",
"in",
"a",
"remote",
"store",
"and",
"returns",
"the",
"public",
"key",
"component"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/helpers.go#L237-L249 | train |
theupdateframework/notary | client/helpers.go | serializeCanonicalRole | func serializeCanonicalRole(tufRepo *tuf.Repo, role data.RoleName, extraSigningKeys data.KeyList) (out []byte, err error) {
var s *data.Signed
switch {
case role == data.CanonicalRootRole:
s, err = tufRepo.SignRoot(data.DefaultExpires(role), extraSigningKeys)
case role == data.CanonicalSnapshotRole:
s, err = tufRepo.SignSnapshot(data.DefaultExpires(role))
case tufRepo.Targets[role] != nil:
s, err = tufRepo.SignTargets(
role, data.DefaultExpires(data.CanonicalTargetsRole))
default:
err = fmt.Errorf("%s not supported role to sign on the client", role)
}
if err != nil {
return
}
return json.Marshal(s)
} | go | func serializeCanonicalRole(tufRepo *tuf.Repo, role data.RoleName, extraSigningKeys data.KeyList) (out []byte, err error) {
var s *data.Signed
switch {
case role == data.CanonicalRootRole:
s, err = tufRepo.SignRoot(data.DefaultExpires(role), extraSigningKeys)
case role == data.CanonicalSnapshotRole:
s, err = tufRepo.SignSnapshot(data.DefaultExpires(role))
case tufRepo.Targets[role] != nil:
s, err = tufRepo.SignTargets(
role, data.DefaultExpires(data.CanonicalTargetsRole))
default:
err = fmt.Errorf("%s not supported role to sign on the client", role)
}
if err != nil {
return
}
return json.Marshal(s)
} | [
"func",
"serializeCanonicalRole",
"(",
"tufRepo",
"*",
"tuf",
".",
"Repo",
",",
"role",
"data",
".",
"RoleName",
",",
"extraSigningKeys",
"data",
".",
"KeyList",
")",
"(",
"out",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"var",
"s",
"*",
"data",
".",
"Signed",
"\n",
"switch",
"{",
"case",
"role",
"==",
"data",
".",
"CanonicalRootRole",
":",
"s",
",",
"err",
"=",
"tufRepo",
".",
"SignRoot",
"(",
"data",
".",
"DefaultExpires",
"(",
"role",
")",
",",
"extraSigningKeys",
")",
"\n",
"case",
"role",
"==",
"data",
".",
"CanonicalSnapshotRole",
":",
"s",
",",
"err",
"=",
"tufRepo",
".",
"SignSnapshot",
"(",
"data",
".",
"DefaultExpires",
"(",
"role",
")",
")",
"\n",
"case",
"tufRepo",
".",
"Targets",
"[",
"role",
"]",
"!=",
"nil",
":",
"s",
",",
"err",
"=",
"tufRepo",
".",
"SignTargets",
"(",
"role",
",",
"data",
".",
"DefaultExpires",
"(",
"data",
".",
"CanonicalTargetsRole",
")",
")",
"\n",
"default",
":",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"role",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"Marshal",
"(",
"s",
")",
"\n",
"}"
] | // signs and serializes the metadata for a canonical role in a TUF repo to JSON | [
"signs",
"and",
"serializes",
"the",
"metadata",
"for",
"a",
"canonical",
"role",
"in",
"a",
"TUF",
"repo",
"to",
"JSON"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/helpers.go#L252-L271 | train |
theupdateframework/notary | server/handlers/changefeed.go | Changefeed | func Changefeed(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
var (
vars = mux.Vars(r)
logger = ctxu.GetLogger(ctx)
qs = r.URL.Query()
gun = vars["gun"]
changeID = qs.Get("change_id")
store, records, err = checkChangefeedInputs(logger, ctx.Value(notary.CtxKeyMetaStore), qs.Get("records"))
)
if err != nil {
// err already logged and in correct format.
return err
}
out, err := changefeed(logger, store, gun, changeID, records)
if err == nil {
w.Write(out)
}
return err
} | go | func Changefeed(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
var (
vars = mux.Vars(r)
logger = ctxu.GetLogger(ctx)
qs = r.URL.Query()
gun = vars["gun"]
changeID = qs.Get("change_id")
store, records, err = checkChangefeedInputs(logger, ctx.Value(notary.CtxKeyMetaStore), qs.Get("records"))
)
if err != nil {
// err already logged and in correct format.
return err
}
out, err := changefeed(logger, store, gun, changeID, records)
if err == nil {
w.Write(out)
}
return err
} | [
"func",
"Changefeed",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"var",
"(",
"vars",
"=",
"mux",
".",
"Vars",
"(",
"r",
")",
"\n",
"logger",
"=",
"ctxu",
".",
"GetLogger",
"(",
"ctx",
")",
"\n",
"qs",
"=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
"\n",
"gun",
"=",
"vars",
"[",
"\"",
"\"",
"]",
"\n",
"changeID",
"=",
"qs",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"store",
",",
"records",
",",
"err",
"=",
"checkChangefeedInputs",
"(",
"logger",
",",
"ctx",
".",
"Value",
"(",
"notary",
".",
"CtxKeyMetaStore",
")",
",",
"qs",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// err already logged and in correct format.",
"return",
"err",
"\n",
"}",
"\n",
"out",
",",
"err",
":=",
"changefeed",
"(",
"logger",
",",
"store",
",",
"gun",
",",
"changeID",
",",
"records",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"w",
".",
"Write",
"(",
"out",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Changefeed returns a list of changes according to the provided filters | [
"Changefeed",
"returns",
"a",
"list",
"of",
"changes",
"according",
"to",
"the",
"provided",
"filters"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/changefeed.go#L24-L42 | train |
theupdateframework/notary | storage/rethinkdb/bootstrap.go | SetupDB | func SetupDB(session *gorethink.Session, dbName string, tables []Table) error {
if err := makeDB(session, dbName); err != nil {
return fmt.Errorf("unable to create database: %s", err)
}
cursor, err := gorethink.DB("rethinkdb").Table("server_config").Count().Run(session)
if err != nil {
return fmt.Errorf("unable to query db server config: %s", err)
}
var replicaCount uint
if err := cursor.One(&replicaCount); err != nil {
return fmt.Errorf("unable to scan db server config count: %s", err)
}
for _, table := range tables {
if err = table.create(session, dbName, replicaCount); err != nil {
return fmt.Errorf("unable to create table %q: %s", table.Name, err)
}
}
return nil
} | go | func SetupDB(session *gorethink.Session, dbName string, tables []Table) error {
if err := makeDB(session, dbName); err != nil {
return fmt.Errorf("unable to create database: %s", err)
}
cursor, err := gorethink.DB("rethinkdb").Table("server_config").Count().Run(session)
if err != nil {
return fmt.Errorf("unable to query db server config: %s", err)
}
var replicaCount uint
if err := cursor.One(&replicaCount); err != nil {
return fmt.Errorf("unable to scan db server config count: %s", err)
}
for _, table := range tables {
if err = table.create(session, dbName, replicaCount); err != nil {
return fmt.Errorf("unable to create table %q: %s", table.Name, err)
}
}
return nil
} | [
"func",
"SetupDB",
"(",
"session",
"*",
"gorethink",
".",
"Session",
",",
"dbName",
"string",
",",
"tables",
"[",
"]",
"Table",
")",
"error",
"{",
"if",
"err",
":=",
"makeDB",
"(",
"session",
",",
"dbName",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"cursor",
",",
"err",
":=",
"gorethink",
".",
"DB",
"(",
"\"",
"\"",
")",
".",
"Table",
"(",
"\"",
"\"",
")",
".",
"Count",
"(",
")",
".",
"Run",
"(",
"session",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"replicaCount",
"uint",
"\n",
"if",
"err",
":=",
"cursor",
".",
"One",
"(",
"&",
"replicaCount",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"table",
":=",
"range",
"tables",
"{",
"if",
"err",
"=",
"table",
".",
"create",
"(",
"session",
",",
"dbName",
",",
"replicaCount",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"table",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // SetupDB handles creating the database and creating all tables and indexes. | [
"SetupDB",
"handles",
"creating",
"the",
"database",
"and",
"creating",
"all",
"tables",
"and",
"indexes",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/rethinkdb/bootstrap.go#L146-L168 | train |
theupdateframework/notary | storage/rethinkdb/bootstrap.go | CreateAndGrantDBUser | func CreateAndGrantDBUser(session *gorethink.Session, dbName, username, password string) error {
var err error
logrus.Debugf("creating user %s for db %s", username, dbName)
// If the password is empty, pass false to the password parameter
if password == "" {
err = gorethink.DB("rethinkdb").Table("users").Insert(map[string]interface{}{
"id": username,
"password": false,
}).Exec(session)
} else {
err = gorethink.DB("rethinkdb").Table("users").Insert(map[string]string{
"id": username,
"password": password,
}).Exec(session)
}
if err != nil {
return fmt.Errorf("unable to add user %s to rethinkdb users table: %s", username, err)
}
// Grant read and write permission
return gorethink.DB(dbName).Grant(username, map[string]bool{
"read": true,
"write": true,
}).Exec(session)
} | go | func CreateAndGrantDBUser(session *gorethink.Session, dbName, username, password string) error {
var err error
logrus.Debugf("creating user %s for db %s", username, dbName)
// If the password is empty, pass false to the password parameter
if password == "" {
err = gorethink.DB("rethinkdb").Table("users").Insert(map[string]interface{}{
"id": username,
"password": false,
}).Exec(session)
} else {
err = gorethink.DB("rethinkdb").Table("users").Insert(map[string]string{
"id": username,
"password": password,
}).Exec(session)
}
if err != nil {
return fmt.Errorf("unable to add user %s to rethinkdb users table: %s", username, err)
}
// Grant read and write permission
return gorethink.DB(dbName).Grant(username, map[string]bool{
"read": true,
"write": true,
}).Exec(session)
} | [
"func",
"CreateAndGrantDBUser",
"(",
"session",
"*",
"gorethink",
".",
"Session",
",",
"dbName",
",",
"username",
",",
"password",
"string",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"username",
",",
"dbName",
")",
"\n",
"// If the password is empty, pass false to the password parameter",
"if",
"password",
"==",
"\"",
"\"",
"{",
"err",
"=",
"gorethink",
".",
"DB",
"(",
"\"",
"\"",
")",
".",
"Table",
"(",
"\"",
"\"",
")",
".",
"Insert",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"username",
",",
"\"",
"\"",
":",
"false",
",",
"}",
")",
".",
"Exec",
"(",
"session",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"gorethink",
".",
"DB",
"(",
"\"",
"\"",
")",
".",
"Table",
"(",
"\"",
"\"",
")",
".",
"Insert",
"(",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"username",
",",
"\"",
"\"",
":",
"password",
",",
"}",
")",
".",
"Exec",
"(",
"session",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"username",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Grant read and write permission",
"return",
"gorethink",
".",
"DB",
"(",
"dbName",
")",
".",
"Grant",
"(",
"username",
",",
"map",
"[",
"string",
"]",
"bool",
"{",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"}",
")",
".",
"Exec",
"(",
"session",
")",
"\n",
"}"
] | // CreateAndGrantDBUser handles creating a rethink user and granting it permissions to the provided db. | [
"CreateAndGrantDBUser",
"handles",
"creating",
"a",
"rethink",
"user",
"and",
"granting",
"it",
"permissions",
"to",
"the",
"provided",
"db",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/rethinkdb/bootstrap.go#L171-L196 | train |
theupdateframework/notary | utils/configuration.go | GetPathRelativeToConfig | func GetPathRelativeToConfig(configuration *viper.Viper, key string) string {
configFile := configuration.ConfigFileUsed()
p := configuration.GetString(key)
if p == "" || filepath.IsAbs(p) {
return p
}
return filepath.Clean(filepath.Join(filepath.Dir(configFile), p))
} | go | func GetPathRelativeToConfig(configuration *viper.Viper, key string) string {
configFile := configuration.ConfigFileUsed()
p := configuration.GetString(key)
if p == "" || filepath.IsAbs(p) {
return p
}
return filepath.Clean(filepath.Join(filepath.Dir(configFile), p))
} | [
"func",
"GetPathRelativeToConfig",
"(",
"configuration",
"*",
"viper",
".",
"Viper",
",",
"key",
"string",
")",
"string",
"{",
"configFile",
":=",
"configuration",
".",
"ConfigFileUsed",
"(",
")",
"\n",
"p",
":=",
"configuration",
".",
"GetString",
"(",
"key",
")",
"\n",
"if",
"p",
"==",
"\"",
"\"",
"||",
"filepath",
".",
"IsAbs",
"(",
"p",
")",
"{",
"return",
"p",
"\n",
"}",
"\n",
"return",
"filepath",
".",
"Clean",
"(",
"filepath",
".",
"Join",
"(",
"filepath",
".",
"Dir",
"(",
"configFile",
")",
",",
"p",
")",
")",
"\n",
"}"
] | // GetPathRelativeToConfig gets a configuration key which is a path, and if
// it is not empty or an absolute path, returns the absolute path relative
// to the configuration file | [
"GetPathRelativeToConfig",
"gets",
"a",
"configuration",
"key",
"which",
"is",
"a",
"path",
"and",
"if",
"it",
"is",
"not",
"empty",
"or",
"an",
"absolute",
"path",
"returns",
"the",
"absolute",
"path",
"relative",
"to",
"the",
"configuration",
"file"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/configuration.go#L43-L50 | train |
theupdateframework/notary | utils/configuration.go | ParseLogLevel | func ParseLogLevel(configuration *viper.Viper, defaultLevel logrus.Level) (
logrus.Level, error) {
logStr := configuration.GetString("logging.level")
if logStr == "" {
return defaultLevel, nil
}
return logrus.ParseLevel(logStr)
} | go | func ParseLogLevel(configuration *viper.Viper, defaultLevel logrus.Level) (
logrus.Level, error) {
logStr := configuration.GetString("logging.level")
if logStr == "" {
return defaultLevel, nil
}
return logrus.ParseLevel(logStr)
} | [
"func",
"ParseLogLevel",
"(",
"configuration",
"*",
"viper",
".",
"Viper",
",",
"defaultLevel",
"logrus",
".",
"Level",
")",
"(",
"logrus",
".",
"Level",
",",
"error",
")",
"{",
"logStr",
":=",
"configuration",
".",
"GetString",
"(",
"\"",
"\"",
")",
"\n",
"if",
"logStr",
"==",
"\"",
"\"",
"{",
"return",
"defaultLevel",
",",
"nil",
"\n",
"}",
"\n",
"return",
"logrus",
".",
"ParseLevel",
"(",
"logStr",
")",
"\n",
"}"
] | // ParseLogLevel tries to parse out a log level from a Viper. If there is no
// configuration, defaults to the provided error level | [
"ParseLogLevel",
"tries",
"to",
"parse",
"out",
"a",
"log",
"level",
"from",
"a",
"Viper",
".",
"If",
"there",
"is",
"no",
"configuration",
"defaults",
"to",
"the",
"provided",
"error",
"level"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/configuration.go#L84-L92 | train |
theupdateframework/notary | utils/configuration.go | ParseBugsnag | func ParseBugsnag(configuration *viper.Viper) (*bugsnag.Configuration, error) {
// can't unmarshal because we can't add tags to the bugsnag.Configuration
// struct
bugconf := bugsnag.Configuration{
APIKey: configuration.GetString("reporting.bugsnag.api_key"),
ReleaseStage: configuration.GetString("reporting.bugsnag.release_stage"),
Endpoint: configuration.GetString("reporting.bugsnag.endpoint"),
}
if bugconf.APIKey == "" && bugconf.ReleaseStage == "" && bugconf.Endpoint == "" {
return nil, nil
}
if bugconf.APIKey == "" {
return nil, fmt.Errorf("must provide an API key for bugsnag")
}
return &bugconf, nil
} | go | func ParseBugsnag(configuration *viper.Viper) (*bugsnag.Configuration, error) {
// can't unmarshal because we can't add tags to the bugsnag.Configuration
// struct
bugconf := bugsnag.Configuration{
APIKey: configuration.GetString("reporting.bugsnag.api_key"),
ReleaseStage: configuration.GetString("reporting.bugsnag.release_stage"),
Endpoint: configuration.GetString("reporting.bugsnag.endpoint"),
}
if bugconf.APIKey == "" && bugconf.ReleaseStage == "" && bugconf.Endpoint == "" {
return nil, nil
}
if bugconf.APIKey == "" {
return nil, fmt.Errorf("must provide an API key for bugsnag")
}
return &bugconf, nil
} | [
"func",
"ParseBugsnag",
"(",
"configuration",
"*",
"viper",
".",
"Viper",
")",
"(",
"*",
"bugsnag",
".",
"Configuration",
",",
"error",
")",
"{",
"// can't unmarshal because we can't add tags to the bugsnag.Configuration",
"// struct",
"bugconf",
":=",
"bugsnag",
".",
"Configuration",
"{",
"APIKey",
":",
"configuration",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"ReleaseStage",
":",
"configuration",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"Endpoint",
":",
"configuration",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"}",
"\n",
"if",
"bugconf",
".",
"APIKey",
"==",
"\"",
"\"",
"&&",
"bugconf",
".",
"ReleaseStage",
"==",
"\"",
"\"",
"&&",
"bugconf",
".",
"Endpoint",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"if",
"bugconf",
".",
"APIKey",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"bugconf",
",",
"nil",
"\n",
"}"
] | // ParseBugsnag tries to parse out a Bugsnag Configuration from a Viper.
// If no values are provided, returns a nil pointer. | [
"ParseBugsnag",
"tries",
"to",
"parse",
"out",
"a",
"Bugsnag",
"Configuration",
"from",
"a",
"Viper",
".",
"If",
"no",
"values",
"are",
"provided",
"returns",
"a",
"nil",
"pointer",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/configuration.go#L183-L198 | train |
theupdateframework/notary | utils/configuration.go | SetUpBugsnag | func SetUpBugsnag(config *bugsnag.Configuration) error {
if config != nil {
bugsnag.Configure(*config)
hook, err := bugsnag_hook.NewBugsnagHook()
if err != nil {
return err
}
logrus.AddHook(hook)
logrus.Debug("Adding logrus hook for Bugsnag")
}
return nil
} | go | func SetUpBugsnag(config *bugsnag.Configuration) error {
if config != nil {
bugsnag.Configure(*config)
hook, err := bugsnag_hook.NewBugsnagHook()
if err != nil {
return err
}
logrus.AddHook(hook)
logrus.Debug("Adding logrus hook for Bugsnag")
}
return nil
} | [
"func",
"SetUpBugsnag",
"(",
"config",
"*",
"bugsnag",
".",
"Configuration",
")",
"error",
"{",
"if",
"config",
"!=",
"nil",
"{",
"bugsnag",
".",
"Configure",
"(",
"*",
"config",
")",
"\n",
"hook",
",",
"err",
":=",
"bugsnag_hook",
".",
"NewBugsnagHook",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"logrus",
".",
"AddHook",
"(",
"hook",
")",
"\n",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetUpBugsnag configures bugsnag and sets up a logrus hook | [
"SetUpBugsnag",
"configures",
"bugsnag",
"and",
"sets",
"up",
"a",
"logrus",
"hook"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/configuration.go#L211-L222 | train |
theupdateframework/notary | utils/configuration.go | ParseViper | func ParseViper(v *viper.Viper, configFile string) error {
filename := filepath.Base(configFile)
ext := filepath.Ext(configFile)
configPath := filepath.Dir(configFile)
v.SetConfigType(strings.TrimPrefix(ext, "."))
v.SetConfigName(strings.TrimSuffix(filename, ext))
v.AddConfigPath(configPath)
if err := v.ReadInConfig(); err != nil {
return fmt.Errorf("Could not read config at :%s, viper error: %v", configFile, err)
}
return nil
} | go | func ParseViper(v *viper.Viper, configFile string) error {
filename := filepath.Base(configFile)
ext := filepath.Ext(configFile)
configPath := filepath.Dir(configFile)
v.SetConfigType(strings.TrimPrefix(ext, "."))
v.SetConfigName(strings.TrimSuffix(filename, ext))
v.AddConfigPath(configPath)
if err := v.ReadInConfig(); err != nil {
return fmt.Errorf("Could not read config at :%s, viper error: %v", configFile, err)
}
return nil
} | [
"func",
"ParseViper",
"(",
"v",
"*",
"viper",
".",
"Viper",
",",
"configFile",
"string",
")",
"error",
"{",
"filename",
":=",
"filepath",
".",
"Base",
"(",
"configFile",
")",
"\n",
"ext",
":=",
"filepath",
".",
"Ext",
"(",
"configFile",
")",
"\n",
"configPath",
":=",
"filepath",
".",
"Dir",
"(",
"configFile",
")",
"\n\n",
"v",
".",
"SetConfigType",
"(",
"strings",
".",
"TrimPrefix",
"(",
"ext",
",",
"\"",
"\"",
")",
")",
"\n",
"v",
".",
"SetConfigName",
"(",
"strings",
".",
"TrimSuffix",
"(",
"filename",
",",
"ext",
")",
")",
"\n",
"v",
".",
"AddConfigPath",
"(",
"configPath",
")",
"\n\n",
"if",
"err",
":=",
"v",
".",
"ReadInConfig",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"configFile",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ParseViper tries to parse out a Viper from a configuration file. | [
"ParseViper",
"tries",
"to",
"parse",
"out",
"a",
"Viper",
"from",
"a",
"configuration",
"file",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/utils/configuration.go#L225-L238 | train |
theupdateframework/notary | tuf/data/root.go | isValidRootStructure | func isValidRootStructure(r Root) error {
expectedType := TUFTypes[CanonicalRootRole]
if r.Type != expectedType {
return ErrInvalidMetadata{
role: CanonicalRootRole, msg: fmt.Sprintf("expected type %s, not %s", expectedType, r.Type)}
}
if r.Version < 1 {
return ErrInvalidMetadata{
role: CanonicalRootRole, msg: "version cannot be less than 1"}
}
// all the base roles MUST appear in the root.json - other roles are allowed,
// but other than the mirror role (not currently supported) are out of spec
for _, roleName := range BaseRoles {
roleObj, ok := r.Roles[roleName]
if !ok || roleObj == nil {
return ErrInvalidMetadata{
role: CanonicalRootRole, msg: fmt.Sprintf("missing %s role specification", roleName)}
}
if err := isValidRootRoleStructure(CanonicalRootRole, roleName, *roleObj, r.Keys); err != nil {
return err
}
}
return nil
} | go | func isValidRootStructure(r Root) error {
expectedType := TUFTypes[CanonicalRootRole]
if r.Type != expectedType {
return ErrInvalidMetadata{
role: CanonicalRootRole, msg: fmt.Sprintf("expected type %s, not %s", expectedType, r.Type)}
}
if r.Version < 1 {
return ErrInvalidMetadata{
role: CanonicalRootRole, msg: "version cannot be less than 1"}
}
// all the base roles MUST appear in the root.json - other roles are allowed,
// but other than the mirror role (not currently supported) are out of spec
for _, roleName := range BaseRoles {
roleObj, ok := r.Roles[roleName]
if !ok || roleObj == nil {
return ErrInvalidMetadata{
role: CanonicalRootRole, msg: fmt.Sprintf("missing %s role specification", roleName)}
}
if err := isValidRootRoleStructure(CanonicalRootRole, roleName, *roleObj, r.Keys); err != nil {
return err
}
}
return nil
} | [
"func",
"isValidRootStructure",
"(",
"r",
"Root",
")",
"error",
"{",
"expectedType",
":=",
"TUFTypes",
"[",
"CanonicalRootRole",
"]",
"\n",
"if",
"r",
".",
"Type",
"!=",
"expectedType",
"{",
"return",
"ErrInvalidMetadata",
"{",
"role",
":",
"CanonicalRootRole",
",",
"msg",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"expectedType",
",",
"r",
".",
"Type",
")",
"}",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"Version",
"<",
"1",
"{",
"return",
"ErrInvalidMetadata",
"{",
"role",
":",
"CanonicalRootRole",
",",
"msg",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n\n",
"// all the base roles MUST appear in the root.json - other roles are allowed,",
"// but other than the mirror role (not currently supported) are out of spec",
"for",
"_",
",",
"roleName",
":=",
"range",
"BaseRoles",
"{",
"roleObj",
",",
"ok",
":=",
"r",
".",
"Roles",
"[",
"roleName",
"]",
"\n",
"if",
"!",
"ok",
"||",
"roleObj",
"==",
"nil",
"{",
"return",
"ErrInvalidMetadata",
"{",
"role",
":",
"CanonicalRootRole",
",",
"msg",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"roleName",
")",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"isValidRootRoleStructure",
"(",
"CanonicalRootRole",
",",
"roleName",
",",
"*",
"roleObj",
",",
"r",
".",
"Keys",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // isValidRootStructure returns an error, or nil, depending on whether the content of the struct
// is valid for root metadata. This does not check signatures or expiry, just that
// the metadata content is valid. | [
"isValidRootStructure",
"returns",
"an",
"error",
"or",
"nil",
"depending",
"on",
"whether",
"the",
"content",
"of",
"the",
"struct",
"is",
"valid",
"for",
"root",
"metadata",
".",
"This",
"does",
"not",
"check",
"signatures",
"or",
"expiry",
"just",
"that",
"the",
"metadata",
"content",
"is",
"valid",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/root.go#L27-L52 | train |
theupdateframework/notary | tuf/data/root.go | NewRoot | func NewRoot(keys map[string]PublicKey, roles map[RoleName]*RootRole, consistent bool) (*SignedRoot, error) {
signedRoot := &SignedRoot{
Signatures: make([]Signature, 0),
Signed: Root{
SignedCommon: SignedCommon{
Type: TUFTypes[CanonicalRootRole],
Version: 0,
Expires: DefaultExpires(CanonicalRootRole),
},
Keys: keys,
Roles: roles,
ConsistentSnapshot: consistent,
},
Dirty: true,
}
return signedRoot, nil
} | go | func NewRoot(keys map[string]PublicKey, roles map[RoleName]*RootRole, consistent bool) (*SignedRoot, error) {
signedRoot := &SignedRoot{
Signatures: make([]Signature, 0),
Signed: Root{
SignedCommon: SignedCommon{
Type: TUFTypes[CanonicalRootRole],
Version: 0,
Expires: DefaultExpires(CanonicalRootRole),
},
Keys: keys,
Roles: roles,
ConsistentSnapshot: consistent,
},
Dirty: true,
}
return signedRoot, nil
} | [
"func",
"NewRoot",
"(",
"keys",
"map",
"[",
"string",
"]",
"PublicKey",
",",
"roles",
"map",
"[",
"RoleName",
"]",
"*",
"RootRole",
",",
"consistent",
"bool",
")",
"(",
"*",
"SignedRoot",
",",
"error",
")",
"{",
"signedRoot",
":=",
"&",
"SignedRoot",
"{",
"Signatures",
":",
"make",
"(",
"[",
"]",
"Signature",
",",
"0",
")",
",",
"Signed",
":",
"Root",
"{",
"SignedCommon",
":",
"SignedCommon",
"{",
"Type",
":",
"TUFTypes",
"[",
"CanonicalRootRole",
"]",
",",
"Version",
":",
"0",
",",
"Expires",
":",
"DefaultExpires",
"(",
"CanonicalRootRole",
")",
",",
"}",
",",
"Keys",
":",
"keys",
",",
"Roles",
":",
"roles",
",",
"ConsistentSnapshot",
":",
"consistent",
",",
"}",
",",
"Dirty",
":",
"true",
",",
"}",
"\n\n",
"return",
"signedRoot",
",",
"nil",
"\n",
"}"
] | // NewRoot initializes a new SignedRoot with a set of keys, roles, and the consistent flag | [
"NewRoot",
"initializes",
"a",
"new",
"SignedRoot",
"with",
"a",
"set",
"of",
"keys",
"roles",
"and",
"the",
"consistent",
"flag"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/root.go#L73-L90 | train |
theupdateframework/notary | tuf/data/root.go | BuildBaseRole | func (r SignedRoot) BuildBaseRole(roleName RoleName) (BaseRole, error) {
roleData, ok := r.Signed.Roles[roleName]
if !ok {
return BaseRole{}, ErrInvalidRole{Role: roleName, Reason: "role not found in root file"}
}
// Get all public keys for the base role from TUF metadata
keyIDs := roleData.KeyIDs
pubKeys := make(map[string]PublicKey)
for _, keyID := range keyIDs {
pubKey, ok := r.Signed.Keys[keyID]
if !ok {
return BaseRole{}, ErrInvalidRole{
Role: roleName,
Reason: fmt.Sprintf("key with ID %s was not found in root metadata", keyID),
}
}
pubKeys[keyID] = pubKey
}
return BaseRole{
Name: roleName,
Keys: pubKeys,
Threshold: roleData.Threshold,
}, nil
} | go | func (r SignedRoot) BuildBaseRole(roleName RoleName) (BaseRole, error) {
roleData, ok := r.Signed.Roles[roleName]
if !ok {
return BaseRole{}, ErrInvalidRole{Role: roleName, Reason: "role not found in root file"}
}
// Get all public keys for the base role from TUF metadata
keyIDs := roleData.KeyIDs
pubKeys := make(map[string]PublicKey)
for _, keyID := range keyIDs {
pubKey, ok := r.Signed.Keys[keyID]
if !ok {
return BaseRole{}, ErrInvalidRole{
Role: roleName,
Reason: fmt.Sprintf("key with ID %s was not found in root metadata", keyID),
}
}
pubKeys[keyID] = pubKey
}
return BaseRole{
Name: roleName,
Keys: pubKeys,
Threshold: roleData.Threshold,
}, nil
} | [
"func",
"(",
"r",
"SignedRoot",
")",
"BuildBaseRole",
"(",
"roleName",
"RoleName",
")",
"(",
"BaseRole",
",",
"error",
")",
"{",
"roleData",
",",
"ok",
":=",
"r",
".",
"Signed",
".",
"Roles",
"[",
"roleName",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"BaseRole",
"{",
"}",
",",
"ErrInvalidRole",
"{",
"Role",
":",
"roleName",
",",
"Reason",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"// Get all public keys for the base role from TUF metadata",
"keyIDs",
":=",
"roleData",
".",
"KeyIDs",
"\n",
"pubKeys",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"PublicKey",
")",
"\n",
"for",
"_",
",",
"keyID",
":=",
"range",
"keyIDs",
"{",
"pubKey",
",",
"ok",
":=",
"r",
".",
"Signed",
".",
"Keys",
"[",
"keyID",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"BaseRole",
"{",
"}",
",",
"ErrInvalidRole",
"{",
"Role",
":",
"roleName",
",",
"Reason",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"keyID",
")",
",",
"}",
"\n",
"}",
"\n",
"pubKeys",
"[",
"keyID",
"]",
"=",
"pubKey",
"\n",
"}",
"\n\n",
"return",
"BaseRole",
"{",
"Name",
":",
"roleName",
",",
"Keys",
":",
"pubKeys",
",",
"Threshold",
":",
"roleData",
".",
"Threshold",
",",
"}",
",",
"nil",
"\n",
"}"
] | // BuildBaseRole returns a copy of a BaseRole using the information in this SignedRoot for the specified role name.
// Will error for invalid role name or key metadata within this SignedRoot | [
"BuildBaseRole",
"returns",
"a",
"copy",
"of",
"a",
"BaseRole",
"using",
"the",
"information",
"in",
"this",
"SignedRoot",
"for",
"the",
"specified",
"role",
"name",
".",
"Will",
"error",
"for",
"invalid",
"role",
"name",
"or",
"key",
"metadata",
"within",
"this",
"SignedRoot"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/root.go#L94-L118 | train |
theupdateframework/notary | tuf/data/root.go | MarshalJSON | func (r SignedRoot) MarshalJSON() ([]byte, error) {
signed, err := r.ToSigned()
if err != nil {
return nil, err
}
return defaultSerializer.Marshal(signed)
} | go | func (r SignedRoot) MarshalJSON() ([]byte, error) {
signed, err := r.ToSigned()
if err != nil {
return nil, err
}
return defaultSerializer.Marshal(signed)
} | [
"func",
"(",
"r",
"SignedRoot",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"signed",
",",
"err",
":=",
"r",
".",
"ToSigned",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"defaultSerializer",
".",
"Marshal",
"(",
"signed",
")",
"\n",
"}"
] | // MarshalJSON returns the serialized form of SignedRoot as bytes | [
"MarshalJSON",
"returns",
"the",
"serialized",
"form",
"of",
"SignedRoot",
"as",
"bytes"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/root.go#L141-L147 | train |
theupdateframework/notary | tuf/data/root.go | RootFromSigned | func RootFromSigned(s *Signed) (*SignedRoot, error) {
r := Root{}
if s.Signed == nil {
return nil, ErrInvalidMetadata{
role: CanonicalRootRole,
msg: "root file contained an empty payload",
}
}
if err := defaultSerializer.Unmarshal(*s.Signed, &r); err != nil {
return nil, err
}
if err := isValidRootStructure(r); err != nil {
return nil, err
}
sigs := make([]Signature, len(s.Signatures))
copy(sigs, s.Signatures)
return &SignedRoot{
Signatures: sigs,
Signed: r,
}, nil
} | go | func RootFromSigned(s *Signed) (*SignedRoot, error) {
r := Root{}
if s.Signed == nil {
return nil, ErrInvalidMetadata{
role: CanonicalRootRole,
msg: "root file contained an empty payload",
}
}
if err := defaultSerializer.Unmarshal(*s.Signed, &r); err != nil {
return nil, err
}
if err := isValidRootStructure(r); err != nil {
return nil, err
}
sigs := make([]Signature, len(s.Signatures))
copy(sigs, s.Signatures)
return &SignedRoot{
Signatures: sigs,
Signed: r,
}, nil
} | [
"func",
"RootFromSigned",
"(",
"s",
"*",
"Signed",
")",
"(",
"*",
"SignedRoot",
",",
"error",
")",
"{",
"r",
":=",
"Root",
"{",
"}",
"\n",
"if",
"s",
".",
"Signed",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrInvalidMetadata",
"{",
"role",
":",
"CanonicalRootRole",
",",
"msg",
":",
"\"",
"\"",
",",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"defaultSerializer",
".",
"Unmarshal",
"(",
"*",
"s",
".",
"Signed",
",",
"&",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"isValidRootStructure",
"(",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"sigs",
":=",
"make",
"(",
"[",
"]",
"Signature",
",",
"len",
"(",
"s",
".",
"Signatures",
")",
")",
"\n",
"copy",
"(",
"sigs",
",",
"s",
".",
"Signatures",
")",
"\n",
"return",
"&",
"SignedRoot",
"{",
"Signatures",
":",
"sigs",
",",
"Signed",
":",
"r",
",",
"}",
",",
"nil",
"\n",
"}"
] | // RootFromSigned fully unpacks a Signed object into a SignedRoot and ensures
// that it is a valid SignedRoot | [
"RootFromSigned",
"fully",
"unpacks",
"a",
"Signed",
"object",
"into",
"a",
"SignedRoot",
"and",
"ensures",
"that",
"it",
"is",
"a",
"valid",
"SignedRoot"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/root.go#L151-L171 | train |
theupdateframework/notary | signer/api/find_key.go | findKeyByID | func findKeyByID(cryptoServices signer.CryptoServiceIndex, keyID *pb.KeyID) (data.PrivateKey, data.RoleName, error) {
for _, service := range cryptoServices {
key, role, err := service.GetPrivateKey(keyID.ID)
if err == nil {
return key, role, nil
}
}
return nil, "", trustmanager.ErrKeyNotFound{KeyID: keyID.ID}
} | go | func findKeyByID(cryptoServices signer.CryptoServiceIndex, keyID *pb.KeyID) (data.PrivateKey, data.RoleName, error) {
for _, service := range cryptoServices {
key, role, err := service.GetPrivateKey(keyID.ID)
if err == nil {
return key, role, nil
}
}
return nil, "", trustmanager.ErrKeyNotFound{KeyID: keyID.ID}
} | [
"func",
"findKeyByID",
"(",
"cryptoServices",
"signer",
".",
"CryptoServiceIndex",
",",
"keyID",
"*",
"pb",
".",
"KeyID",
")",
"(",
"data",
".",
"PrivateKey",
",",
"data",
".",
"RoleName",
",",
"error",
")",
"{",
"for",
"_",
",",
"service",
":=",
"range",
"cryptoServices",
"{",
"key",
",",
"role",
",",
"err",
":=",
"service",
".",
"GetPrivateKey",
"(",
"keyID",
".",
"ID",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"key",
",",
"role",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"\"",
"\"",
",",
"trustmanager",
".",
"ErrKeyNotFound",
"{",
"KeyID",
":",
"keyID",
".",
"ID",
"}",
"\n",
"}"
] | // findKeyByID looks for the key with the given ID in each of the
// signing services in sigServices. It returns the first matching key it finds,
// or ErrInvalidKeyID if the key is not found in any of the signing services. | [
"findKeyByID",
"looks",
"for",
"the",
"key",
"with",
"the",
"given",
"ID",
"in",
"each",
"of",
"the",
"signing",
"services",
"in",
"sigServices",
".",
"It",
"returns",
"the",
"first",
"matching",
"key",
"it",
"finds",
"or",
"ErrInvalidKeyID",
"if",
"the",
"key",
"is",
"not",
"found",
"in",
"any",
"of",
"the",
"signing",
"services",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/api/find_key.go#L14-L23 | train |
theupdateframework/notary | tuf/data/snapshot.go | IsValidSnapshotStructure | func IsValidSnapshotStructure(s Snapshot) error {
expectedType := TUFTypes[CanonicalSnapshotRole]
if s.Type != expectedType {
return ErrInvalidMetadata{
role: CanonicalSnapshotRole, msg: fmt.Sprintf("expected type %s, not %s", expectedType, s.Type)}
}
if s.Version < 1 {
return ErrInvalidMetadata{
role: CanonicalSnapshotRole, msg: "version cannot be less than one"}
}
for _, file := range []RoleName{CanonicalRootRole, CanonicalTargetsRole} {
// Meta is a map of FileMeta, so if the role isn't in the map it returns
// an empty FileMeta, which has an empty map, and you can check on keys
// from an empty map.
//
// For now sha256 is required and sha512 is not.
if _, ok := s.Meta[file.String()].Hashes[notary.SHA256]; !ok {
return ErrInvalidMetadata{
role: CanonicalSnapshotRole,
msg: fmt.Sprintf("missing %s sha256 checksum information", file.String()),
}
}
if err := CheckValidHashStructures(s.Meta[file.String()].Hashes); err != nil {
return ErrInvalidMetadata{
role: CanonicalSnapshotRole,
msg: fmt.Sprintf("invalid %s checksum information, %v", file.String(), err),
}
}
}
return nil
} | go | func IsValidSnapshotStructure(s Snapshot) error {
expectedType := TUFTypes[CanonicalSnapshotRole]
if s.Type != expectedType {
return ErrInvalidMetadata{
role: CanonicalSnapshotRole, msg: fmt.Sprintf("expected type %s, not %s", expectedType, s.Type)}
}
if s.Version < 1 {
return ErrInvalidMetadata{
role: CanonicalSnapshotRole, msg: "version cannot be less than one"}
}
for _, file := range []RoleName{CanonicalRootRole, CanonicalTargetsRole} {
// Meta is a map of FileMeta, so if the role isn't in the map it returns
// an empty FileMeta, which has an empty map, and you can check on keys
// from an empty map.
//
// For now sha256 is required and sha512 is not.
if _, ok := s.Meta[file.String()].Hashes[notary.SHA256]; !ok {
return ErrInvalidMetadata{
role: CanonicalSnapshotRole,
msg: fmt.Sprintf("missing %s sha256 checksum information", file.String()),
}
}
if err := CheckValidHashStructures(s.Meta[file.String()].Hashes); err != nil {
return ErrInvalidMetadata{
role: CanonicalSnapshotRole,
msg: fmt.Sprintf("invalid %s checksum information, %v", file.String(), err),
}
}
}
return nil
} | [
"func",
"IsValidSnapshotStructure",
"(",
"s",
"Snapshot",
")",
"error",
"{",
"expectedType",
":=",
"TUFTypes",
"[",
"CanonicalSnapshotRole",
"]",
"\n",
"if",
"s",
".",
"Type",
"!=",
"expectedType",
"{",
"return",
"ErrInvalidMetadata",
"{",
"role",
":",
"CanonicalSnapshotRole",
",",
"msg",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"expectedType",
",",
"s",
".",
"Type",
")",
"}",
"\n",
"}",
"\n\n",
"if",
"s",
".",
"Version",
"<",
"1",
"{",
"return",
"ErrInvalidMetadata",
"{",
"role",
":",
"CanonicalSnapshotRole",
",",
"msg",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"file",
":=",
"range",
"[",
"]",
"RoleName",
"{",
"CanonicalRootRole",
",",
"CanonicalTargetsRole",
"}",
"{",
"// Meta is a map of FileMeta, so if the role isn't in the map it returns",
"// an empty FileMeta, which has an empty map, and you can check on keys",
"// from an empty map.",
"//",
"// For now sha256 is required and sha512 is not.",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"Meta",
"[",
"file",
".",
"String",
"(",
")",
"]",
".",
"Hashes",
"[",
"notary",
".",
"SHA256",
"]",
";",
"!",
"ok",
"{",
"return",
"ErrInvalidMetadata",
"{",
"role",
":",
"CanonicalSnapshotRole",
",",
"msg",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"file",
".",
"String",
"(",
")",
")",
",",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"CheckValidHashStructures",
"(",
"s",
".",
"Meta",
"[",
"file",
".",
"String",
"(",
")",
"]",
".",
"Hashes",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"ErrInvalidMetadata",
"{",
"role",
":",
"CanonicalSnapshotRole",
",",
"msg",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"file",
".",
"String",
"(",
")",
",",
"err",
")",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // IsValidSnapshotStructure returns an error, or nil, depending on whether the content of the
// struct is valid for snapshot metadata. This does not check signatures or expiry, just that
// the metadata content is valid. | [
"IsValidSnapshotStructure",
"returns",
"an",
"error",
"or",
"nil",
"depending",
"on",
"whether",
"the",
"content",
"of",
"the",
"struct",
"is",
"valid",
"for",
"snapshot",
"metadata",
".",
"This",
"does",
"not",
"check",
"signatures",
"or",
"expiry",
"just",
"that",
"the",
"metadata",
"content",
"is",
"valid",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/snapshot.go#L28-L60 | train |
theupdateframework/notary | tuf/data/snapshot.go | NewSnapshot | func NewSnapshot(root *Signed, targets *Signed) (*SignedSnapshot, error) {
logrus.Debug("generating new snapshot...")
targetsJSON, err := json.Marshal(targets)
if err != nil {
logrus.Debug("Error Marshalling Targets")
return nil, err
}
rootJSON, err := json.Marshal(root)
if err != nil {
logrus.Debug("Error Marshalling Root")
return nil, err
}
rootMeta, err := NewFileMeta(bytes.NewReader(rootJSON), NotaryDefaultHashes...)
if err != nil {
return nil, err
}
targetsMeta, err := NewFileMeta(bytes.NewReader(targetsJSON), NotaryDefaultHashes...)
if err != nil {
return nil, err
}
return &SignedSnapshot{
Signatures: make([]Signature, 0),
Signed: Snapshot{
SignedCommon: SignedCommon{
Type: TUFTypes[CanonicalSnapshotRole],
Version: 0,
Expires: DefaultExpires(CanonicalSnapshotRole),
},
Meta: Files{
CanonicalRootRole.String(): rootMeta,
CanonicalTargetsRole.String(): targetsMeta,
},
},
}, nil
} | go | func NewSnapshot(root *Signed, targets *Signed) (*SignedSnapshot, error) {
logrus.Debug("generating new snapshot...")
targetsJSON, err := json.Marshal(targets)
if err != nil {
logrus.Debug("Error Marshalling Targets")
return nil, err
}
rootJSON, err := json.Marshal(root)
if err != nil {
logrus.Debug("Error Marshalling Root")
return nil, err
}
rootMeta, err := NewFileMeta(bytes.NewReader(rootJSON), NotaryDefaultHashes...)
if err != nil {
return nil, err
}
targetsMeta, err := NewFileMeta(bytes.NewReader(targetsJSON), NotaryDefaultHashes...)
if err != nil {
return nil, err
}
return &SignedSnapshot{
Signatures: make([]Signature, 0),
Signed: Snapshot{
SignedCommon: SignedCommon{
Type: TUFTypes[CanonicalSnapshotRole],
Version: 0,
Expires: DefaultExpires(CanonicalSnapshotRole),
},
Meta: Files{
CanonicalRootRole.String(): rootMeta,
CanonicalTargetsRole.String(): targetsMeta,
},
},
}, nil
} | [
"func",
"NewSnapshot",
"(",
"root",
"*",
"Signed",
",",
"targets",
"*",
"Signed",
")",
"(",
"*",
"SignedSnapshot",
",",
"error",
")",
"{",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"targetsJSON",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"targets",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"rootJSON",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"rootMeta",
",",
"err",
":=",
"NewFileMeta",
"(",
"bytes",
".",
"NewReader",
"(",
"rootJSON",
")",
",",
"NotaryDefaultHashes",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"targetsMeta",
",",
"err",
":=",
"NewFileMeta",
"(",
"bytes",
".",
"NewReader",
"(",
"targetsJSON",
")",
",",
"NotaryDefaultHashes",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"SignedSnapshot",
"{",
"Signatures",
":",
"make",
"(",
"[",
"]",
"Signature",
",",
"0",
")",
",",
"Signed",
":",
"Snapshot",
"{",
"SignedCommon",
":",
"SignedCommon",
"{",
"Type",
":",
"TUFTypes",
"[",
"CanonicalSnapshotRole",
"]",
",",
"Version",
":",
"0",
",",
"Expires",
":",
"DefaultExpires",
"(",
"CanonicalSnapshotRole",
")",
",",
"}",
",",
"Meta",
":",
"Files",
"{",
"CanonicalRootRole",
".",
"String",
"(",
")",
":",
"rootMeta",
",",
"CanonicalTargetsRole",
".",
"String",
"(",
")",
":",
"targetsMeta",
",",
"}",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewSnapshot initializes a SignedSnapshot with a given top level root
// and targets objects | [
"NewSnapshot",
"initializes",
"a",
"SignedSnapshot",
"with",
"a",
"given",
"top",
"level",
"root",
"and",
"targets",
"objects"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/snapshot.go#L64-L98 | train |
theupdateframework/notary | tuf/data/snapshot.go | AddMeta | func (sp *SignedSnapshot) AddMeta(role RoleName, meta FileMeta) {
sp.Signed.Meta[role.String()] = meta
sp.Dirty = true
} | go | func (sp *SignedSnapshot) AddMeta(role RoleName, meta FileMeta) {
sp.Signed.Meta[role.String()] = meta
sp.Dirty = true
} | [
"func",
"(",
"sp",
"*",
"SignedSnapshot",
")",
"AddMeta",
"(",
"role",
"RoleName",
",",
"meta",
"FileMeta",
")",
"{",
"sp",
".",
"Signed",
".",
"Meta",
"[",
"role",
".",
"String",
"(",
")",
"]",
"=",
"meta",
"\n",
"sp",
".",
"Dirty",
"=",
"true",
"\n",
"}"
] | // AddMeta updates a role in the snapshot with new meta | [
"AddMeta",
"updates",
"a",
"role",
"in",
"the",
"snapshot",
"with",
"new",
"meta"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/snapshot.go#L120-L123 | train |
theupdateframework/notary | tuf/data/snapshot.go | GetMeta | func (sp *SignedSnapshot) GetMeta(role RoleName) (*FileMeta, error) {
if meta, ok := sp.Signed.Meta[role.String()]; ok {
if _, ok := meta.Hashes["sha256"]; ok {
return &meta, nil
}
}
return nil, ErrMissingMeta{Role: role.String()}
} | go | func (sp *SignedSnapshot) GetMeta(role RoleName) (*FileMeta, error) {
if meta, ok := sp.Signed.Meta[role.String()]; ok {
if _, ok := meta.Hashes["sha256"]; ok {
return &meta, nil
}
}
return nil, ErrMissingMeta{Role: role.String()}
} | [
"func",
"(",
"sp",
"*",
"SignedSnapshot",
")",
"GetMeta",
"(",
"role",
"RoleName",
")",
"(",
"*",
"FileMeta",
",",
"error",
")",
"{",
"if",
"meta",
",",
"ok",
":=",
"sp",
".",
"Signed",
".",
"Meta",
"[",
"role",
".",
"String",
"(",
")",
"]",
";",
"ok",
"{",
"if",
"_",
",",
"ok",
":=",
"meta",
".",
"Hashes",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"return",
"&",
"meta",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"ErrMissingMeta",
"{",
"Role",
":",
"role",
".",
"String",
"(",
")",
"}",
"\n",
"}"
] | // GetMeta gets the metadata for a particular role, returning an error if it's
// not found | [
"GetMeta",
"gets",
"the",
"metadata",
"for",
"a",
"particular",
"role",
"returning",
"an",
"error",
"if",
"it",
"s",
"not",
"found"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/snapshot.go#L127-L134 | train |
theupdateframework/notary | tuf/data/snapshot.go | DeleteMeta | func (sp *SignedSnapshot) DeleteMeta(role RoleName) {
if _, ok := sp.Signed.Meta[role.String()]; ok {
delete(sp.Signed.Meta, role.String())
sp.Dirty = true
}
} | go | func (sp *SignedSnapshot) DeleteMeta(role RoleName) {
if _, ok := sp.Signed.Meta[role.String()]; ok {
delete(sp.Signed.Meta, role.String())
sp.Dirty = true
}
} | [
"func",
"(",
"sp",
"*",
"SignedSnapshot",
")",
"DeleteMeta",
"(",
"role",
"RoleName",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"sp",
".",
"Signed",
".",
"Meta",
"[",
"role",
".",
"String",
"(",
")",
"]",
";",
"ok",
"{",
"delete",
"(",
"sp",
".",
"Signed",
".",
"Meta",
",",
"role",
".",
"String",
"(",
")",
")",
"\n",
"sp",
".",
"Dirty",
"=",
"true",
"\n",
"}",
"\n",
"}"
] | // DeleteMeta removes a role from the snapshot. If the role doesn't
// exist in the snapshot, it's a noop. | [
"DeleteMeta",
"removes",
"a",
"role",
"from",
"the",
"snapshot",
".",
"If",
"the",
"role",
"doesn",
"t",
"exist",
"in",
"the",
"snapshot",
"it",
"s",
"a",
"noop",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/snapshot.go#L138-L143 | train |
theupdateframework/notary | tuf/data/snapshot.go | MarshalJSON | func (sp *SignedSnapshot) MarshalJSON() ([]byte, error) {
signed, err := sp.ToSigned()
if err != nil {
return nil, err
}
return defaultSerializer.Marshal(signed)
} | go | func (sp *SignedSnapshot) MarshalJSON() ([]byte, error) {
signed, err := sp.ToSigned()
if err != nil {
return nil, err
}
return defaultSerializer.Marshal(signed)
} | [
"func",
"(",
"sp",
"*",
"SignedSnapshot",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"signed",
",",
"err",
":=",
"sp",
".",
"ToSigned",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"defaultSerializer",
".",
"Marshal",
"(",
"signed",
")",
"\n",
"}"
] | // MarshalJSON returns the serialized form of SignedSnapshot as bytes | [
"MarshalJSON",
"returns",
"the",
"serialized",
"form",
"of",
"SignedSnapshot",
"as",
"bytes"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/snapshot.go#L146-L152 | train |
theupdateframework/notary | tuf/data/snapshot.go | SnapshotFromSigned | func SnapshotFromSigned(s *Signed) (*SignedSnapshot, error) {
sp := Snapshot{}
if err := defaultSerializer.Unmarshal(*s.Signed, &sp); err != nil {
return nil, err
}
if err := IsValidSnapshotStructure(sp); err != nil {
return nil, err
}
sigs := make([]Signature, len(s.Signatures))
copy(sigs, s.Signatures)
return &SignedSnapshot{
Signatures: sigs,
Signed: sp,
}, nil
} | go | func SnapshotFromSigned(s *Signed) (*SignedSnapshot, error) {
sp := Snapshot{}
if err := defaultSerializer.Unmarshal(*s.Signed, &sp); err != nil {
return nil, err
}
if err := IsValidSnapshotStructure(sp); err != nil {
return nil, err
}
sigs := make([]Signature, len(s.Signatures))
copy(sigs, s.Signatures)
return &SignedSnapshot{
Signatures: sigs,
Signed: sp,
}, nil
} | [
"func",
"SnapshotFromSigned",
"(",
"s",
"*",
"Signed",
")",
"(",
"*",
"SignedSnapshot",
",",
"error",
")",
"{",
"sp",
":=",
"Snapshot",
"{",
"}",
"\n",
"if",
"err",
":=",
"defaultSerializer",
".",
"Unmarshal",
"(",
"*",
"s",
".",
"Signed",
",",
"&",
"sp",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"IsValidSnapshotStructure",
"(",
"sp",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"sigs",
":=",
"make",
"(",
"[",
"]",
"Signature",
",",
"len",
"(",
"s",
".",
"Signatures",
")",
")",
"\n",
"copy",
"(",
"sigs",
",",
"s",
".",
"Signatures",
")",
"\n",
"return",
"&",
"SignedSnapshot",
"{",
"Signatures",
":",
"sigs",
",",
"Signed",
":",
"sp",
",",
"}",
",",
"nil",
"\n",
"}"
] | // SnapshotFromSigned fully unpacks a Signed object into a SignedSnapshot | [
"SnapshotFromSigned",
"fully",
"unpacks",
"a",
"Signed",
"object",
"into",
"a",
"SignedSnapshot"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/snapshot.go#L155-L169 | train |
theupdateframework/notary | tuf/data/roles.go | ValidRole | func ValidRole(name RoleName) bool {
if IsDelegation(name) {
return true
}
for _, v := range BaseRoles {
if name == v {
return true
}
}
return false
} | go | func ValidRole(name RoleName) bool {
if IsDelegation(name) {
return true
}
for _, v := range BaseRoles {
if name == v {
return true
}
}
return false
} | [
"func",
"ValidRole",
"(",
"name",
"RoleName",
")",
"bool",
"{",
"if",
"IsDelegation",
"(",
"name",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"v",
":=",
"range",
"BaseRoles",
"{",
"if",
"name",
"==",
"v",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // ValidRole only determines the name is semantically
// correct. For target delegated roles, it does NOT check
// the the appropriate parent roles exist. | [
"ValidRole",
"only",
"determines",
"the",
"name",
"is",
"semantically",
"correct",
".",
"For",
"target",
"delegated",
"roles",
"it",
"does",
"NOT",
"check",
"the",
"the",
"appropriate",
"parent",
"roles",
"exist",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L59-L70 | train |
theupdateframework/notary | tuf/data/roles.go | IsDelegation | func IsDelegation(role RoleName) bool {
strRole := role.String()
targetsBase := CanonicalTargetsRole + "/"
whitelistedChars := delegationRegexp.MatchString(strRole)
// Limit size of full role string to 255 chars for db column size limit
correctLength := len(role) < 256
// Removes ., .., extra slashes, and trailing slash
isClean := path.Clean(strRole) == strRole
return strings.HasPrefix(strRole, targetsBase.String()) &&
whitelistedChars &&
correctLength &&
isClean
} | go | func IsDelegation(role RoleName) bool {
strRole := role.String()
targetsBase := CanonicalTargetsRole + "/"
whitelistedChars := delegationRegexp.MatchString(strRole)
// Limit size of full role string to 255 chars for db column size limit
correctLength := len(role) < 256
// Removes ., .., extra slashes, and trailing slash
isClean := path.Clean(strRole) == strRole
return strings.HasPrefix(strRole, targetsBase.String()) &&
whitelistedChars &&
correctLength &&
isClean
} | [
"func",
"IsDelegation",
"(",
"role",
"RoleName",
")",
"bool",
"{",
"strRole",
":=",
"role",
".",
"String",
"(",
")",
"\n",
"targetsBase",
":=",
"CanonicalTargetsRole",
"+",
"\"",
"\"",
"\n\n",
"whitelistedChars",
":=",
"delegationRegexp",
".",
"MatchString",
"(",
"strRole",
")",
"\n\n",
"// Limit size of full role string to 255 chars for db column size limit",
"correctLength",
":=",
"len",
"(",
"role",
")",
"<",
"256",
"\n\n",
"// Removes ., .., extra slashes, and trailing slash",
"isClean",
":=",
"path",
".",
"Clean",
"(",
"strRole",
")",
"==",
"strRole",
"\n",
"return",
"strings",
".",
"HasPrefix",
"(",
"strRole",
",",
"targetsBase",
".",
"String",
"(",
")",
")",
"&&",
"whitelistedChars",
"&&",
"correctLength",
"&&",
"isClean",
"\n",
"}"
] | // IsDelegation checks if the role is a delegation or a root role | [
"IsDelegation",
"checks",
"if",
"the",
"role",
"is",
"a",
"delegation",
"or",
"a",
"root",
"role"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L73-L88 | train |
theupdateframework/notary | tuf/data/roles.go | IsBaseRole | func IsBaseRole(role RoleName) bool {
for _, baseRole := range BaseRoles {
if role == baseRole {
return true
}
}
return false
} | go | func IsBaseRole(role RoleName) bool {
for _, baseRole := range BaseRoles {
if role == baseRole {
return true
}
}
return false
} | [
"func",
"IsBaseRole",
"(",
"role",
"RoleName",
")",
"bool",
"{",
"for",
"_",
",",
"baseRole",
":=",
"range",
"BaseRoles",
"{",
"if",
"role",
"==",
"baseRole",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsBaseRole checks if the role is a base role | [
"IsBaseRole",
"checks",
"if",
"the",
"role",
"is",
"a",
"base",
"role"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L91-L98 | train |
theupdateframework/notary | tuf/data/roles.go | NewBaseRole | func NewBaseRole(name RoleName, threshold int, keys ...PublicKey) BaseRole {
r := BaseRole{
Name: name,
Threshold: threshold,
Keys: make(map[string]PublicKey),
}
for _, k := range keys {
r.Keys[k.ID()] = k
}
return r
} | go | func NewBaseRole(name RoleName, threshold int, keys ...PublicKey) BaseRole {
r := BaseRole{
Name: name,
Threshold: threshold,
Keys: make(map[string]PublicKey),
}
for _, k := range keys {
r.Keys[k.ID()] = k
}
return r
} | [
"func",
"NewBaseRole",
"(",
"name",
"RoleName",
",",
"threshold",
"int",
",",
"keys",
"...",
"PublicKey",
")",
"BaseRole",
"{",
"r",
":=",
"BaseRole",
"{",
"Name",
":",
"name",
",",
"Threshold",
":",
"threshold",
",",
"Keys",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"PublicKey",
")",
",",
"}",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"keys",
"{",
"r",
".",
"Keys",
"[",
"k",
".",
"ID",
"(",
")",
"]",
"=",
"k",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] | // NewBaseRole creates a new BaseRole object with the provided parameters | [
"NewBaseRole",
"creates",
"a",
"new",
"BaseRole",
"object",
"with",
"the",
"provided",
"parameters"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L123-L133 | train |
theupdateframework/notary | tuf/data/roles.go | Equals | func (b BaseRole) Equals(o BaseRole) bool {
if b.Threshold != o.Threshold || b.Name != o.Name || len(b.Keys) != len(o.Keys) {
return false
}
for keyID, key := range b.Keys {
oKey, ok := o.Keys[keyID]
if !ok || key.ID() != oKey.ID() {
return false
}
}
return true
} | go | func (b BaseRole) Equals(o BaseRole) bool {
if b.Threshold != o.Threshold || b.Name != o.Name || len(b.Keys) != len(o.Keys) {
return false
}
for keyID, key := range b.Keys {
oKey, ok := o.Keys[keyID]
if !ok || key.ID() != oKey.ID() {
return false
}
}
return true
} | [
"func",
"(",
"b",
"BaseRole",
")",
"Equals",
"(",
"o",
"BaseRole",
")",
"bool",
"{",
"if",
"b",
".",
"Threshold",
"!=",
"o",
".",
"Threshold",
"||",
"b",
".",
"Name",
"!=",
"o",
".",
"Name",
"||",
"len",
"(",
"b",
".",
"Keys",
")",
"!=",
"len",
"(",
"o",
".",
"Keys",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"keyID",
",",
"key",
":=",
"range",
"b",
".",
"Keys",
"{",
"oKey",
",",
"ok",
":=",
"o",
".",
"Keys",
"[",
"keyID",
"]",
"\n",
"if",
"!",
"ok",
"||",
"key",
".",
"ID",
"(",
")",
"!=",
"oKey",
".",
"ID",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}"
] | // Equals returns whether this BaseRole equals another BaseRole | [
"Equals",
"returns",
"whether",
"this",
"BaseRole",
"equals",
"another",
"BaseRole"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L146-L159 | train |
theupdateframework/notary | tuf/data/roles.go | Restrict | func (d DelegationRole) Restrict(child DelegationRole) (DelegationRole, error) {
if !d.IsParentOf(child) {
return DelegationRole{}, fmt.Errorf("%s is not a parent of %s", d.Name, child.Name)
}
return DelegationRole{
BaseRole: BaseRole{
Keys: child.Keys,
Name: child.Name,
Threshold: child.Threshold,
},
Paths: RestrictDelegationPathPrefixes(d.Paths, child.Paths),
}, nil
} | go | func (d DelegationRole) Restrict(child DelegationRole) (DelegationRole, error) {
if !d.IsParentOf(child) {
return DelegationRole{}, fmt.Errorf("%s is not a parent of %s", d.Name, child.Name)
}
return DelegationRole{
BaseRole: BaseRole{
Keys: child.Keys,
Name: child.Name,
Threshold: child.Threshold,
},
Paths: RestrictDelegationPathPrefixes(d.Paths, child.Paths),
}, nil
} | [
"func",
"(",
"d",
"DelegationRole",
")",
"Restrict",
"(",
"child",
"DelegationRole",
")",
"(",
"DelegationRole",
",",
"error",
")",
"{",
"if",
"!",
"d",
".",
"IsParentOf",
"(",
"child",
")",
"{",
"return",
"DelegationRole",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"d",
".",
"Name",
",",
"child",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"DelegationRole",
"{",
"BaseRole",
":",
"BaseRole",
"{",
"Keys",
":",
"child",
".",
"Keys",
",",
"Name",
":",
"child",
".",
"Name",
",",
"Threshold",
":",
"child",
".",
"Threshold",
",",
"}",
",",
"Paths",
":",
"RestrictDelegationPathPrefixes",
"(",
"d",
".",
"Paths",
",",
"child",
".",
"Paths",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Restrict restricts the paths and path hash prefixes for the passed in delegation role,
// returning a copy of the role with validated paths as if it was a direct child | [
"Restrict",
"restricts",
"the",
"paths",
"and",
"path",
"hash",
"prefixes",
"for",
"the",
"passed",
"in",
"delegation",
"role",
"returning",
"a",
"copy",
"of",
"the",
"role",
"with",
"validated",
"paths",
"as",
"if",
"it",
"was",
"a",
"direct",
"child"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L185-L197 | train |
theupdateframework/notary | tuf/data/roles.go | RestrictDelegationPathPrefixes | func RestrictDelegationPathPrefixes(parentPaths, delegationPaths []string) []string {
validPaths := []string{}
if len(delegationPaths) == 0 {
return validPaths
}
// Validate each individual delegation path
for _, delgPath := range delegationPaths {
isPrefixed := false
for _, parentPath := range parentPaths {
if strings.HasPrefix(delgPath, parentPath) {
isPrefixed = true
break
}
}
// If the delegation path did not match prefix against any parent path, it is not valid
if isPrefixed {
validPaths = append(validPaths, delgPath)
}
}
return validPaths
} | go | func RestrictDelegationPathPrefixes(parentPaths, delegationPaths []string) []string {
validPaths := []string{}
if len(delegationPaths) == 0 {
return validPaths
}
// Validate each individual delegation path
for _, delgPath := range delegationPaths {
isPrefixed := false
for _, parentPath := range parentPaths {
if strings.HasPrefix(delgPath, parentPath) {
isPrefixed = true
break
}
}
// If the delegation path did not match prefix against any parent path, it is not valid
if isPrefixed {
validPaths = append(validPaths, delgPath)
}
}
return validPaths
} | [
"func",
"RestrictDelegationPathPrefixes",
"(",
"parentPaths",
",",
"delegationPaths",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"validPaths",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"if",
"len",
"(",
"delegationPaths",
")",
"==",
"0",
"{",
"return",
"validPaths",
"\n",
"}",
"\n\n",
"// Validate each individual delegation path",
"for",
"_",
",",
"delgPath",
":=",
"range",
"delegationPaths",
"{",
"isPrefixed",
":=",
"false",
"\n",
"for",
"_",
",",
"parentPath",
":=",
"range",
"parentPaths",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"delgPath",
",",
"parentPath",
")",
"{",
"isPrefixed",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"// If the delegation path did not match prefix against any parent path, it is not valid",
"if",
"isPrefixed",
"{",
"validPaths",
"=",
"append",
"(",
"validPaths",
",",
"delgPath",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"validPaths",
"\n",
"}"
] | // RestrictDelegationPathPrefixes returns the list of valid delegationPaths that are prefixed by parentPaths | [
"RestrictDelegationPathPrefixes",
"returns",
"the",
"list",
"of",
"valid",
"delegationPaths",
"that",
"are",
"prefixed",
"by",
"parentPaths"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L221-L242 | train |
theupdateframework/notary | tuf/data/roles.go | NewRole | func NewRole(name RoleName, threshold int, keyIDs, paths []string) (*Role, error) {
if IsDelegation(name) {
if len(paths) == 0 {
logrus.Debugf("role %s with no Paths will never be able to publish content until one or more are added", name)
}
}
if threshold < 1 {
return nil, ErrInvalidRole{Role: name}
}
if !ValidRole(name) {
return nil, ErrInvalidRole{Role: name}
}
return &Role{
RootRole: RootRole{
KeyIDs: keyIDs,
Threshold: threshold,
},
Name: name,
Paths: paths,
}, nil
} | go | func NewRole(name RoleName, threshold int, keyIDs, paths []string) (*Role, error) {
if IsDelegation(name) {
if len(paths) == 0 {
logrus.Debugf("role %s with no Paths will never be able to publish content until one or more are added", name)
}
}
if threshold < 1 {
return nil, ErrInvalidRole{Role: name}
}
if !ValidRole(name) {
return nil, ErrInvalidRole{Role: name}
}
return &Role{
RootRole: RootRole{
KeyIDs: keyIDs,
Threshold: threshold,
},
Name: name,
Paths: paths,
}, nil
} | [
"func",
"NewRole",
"(",
"name",
"RoleName",
",",
"threshold",
"int",
",",
"keyIDs",
",",
"paths",
"[",
"]",
"string",
")",
"(",
"*",
"Role",
",",
"error",
")",
"{",
"if",
"IsDelegation",
"(",
"name",
")",
"{",
"if",
"len",
"(",
"paths",
")",
"==",
"0",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"threshold",
"<",
"1",
"{",
"return",
"nil",
",",
"ErrInvalidRole",
"{",
"Role",
":",
"name",
"}",
"\n",
"}",
"\n",
"if",
"!",
"ValidRole",
"(",
"name",
")",
"{",
"return",
"nil",
",",
"ErrInvalidRole",
"{",
"Role",
":",
"name",
"}",
"\n",
"}",
"\n",
"return",
"&",
"Role",
"{",
"RootRole",
":",
"RootRole",
"{",
"KeyIDs",
":",
"keyIDs",
",",
"Threshold",
":",
"threshold",
",",
"}",
",",
"Name",
":",
"name",
",",
"Paths",
":",
"paths",
",",
"}",
",",
"nil",
"\n\n",
"}"
] | // NewRole creates a new Role object from the given parameters | [
"NewRole",
"creates",
"a",
"new",
"Role",
"object",
"from",
"the",
"given",
"parameters"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L260-L281 | train |
theupdateframework/notary | tuf/data/roles.go | AddKeys | func (r *Role) AddKeys(ids []string) {
r.KeyIDs = mergeStrSlices(r.KeyIDs, ids)
} | go | func (r *Role) AddKeys(ids []string) {
r.KeyIDs = mergeStrSlices(r.KeyIDs, ids)
} | [
"func",
"(",
"r",
"*",
"Role",
")",
"AddKeys",
"(",
"ids",
"[",
"]",
"string",
")",
"{",
"r",
".",
"KeyIDs",
"=",
"mergeStrSlices",
"(",
"r",
".",
"KeyIDs",
",",
"ids",
")",
"\n",
"}"
] | // AddKeys merges the ids into the current list of role key ids | [
"AddKeys",
"merges",
"the",
"ids",
"into",
"the",
"current",
"list",
"of",
"role",
"key",
"ids"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L289-L291 | train |
theupdateframework/notary | tuf/data/roles.go | AddPaths | func (r *Role) AddPaths(paths []string) error {
if len(paths) == 0 {
return nil
}
r.Paths = mergeStrSlices(r.Paths, paths)
return nil
} | go | func (r *Role) AddPaths(paths []string) error {
if len(paths) == 0 {
return nil
}
r.Paths = mergeStrSlices(r.Paths, paths)
return nil
} | [
"func",
"(",
"r",
"*",
"Role",
")",
"AddPaths",
"(",
"paths",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"len",
"(",
"paths",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"r",
".",
"Paths",
"=",
"mergeStrSlices",
"(",
"r",
".",
"Paths",
",",
"paths",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddPaths merges the paths into the current list of role paths | [
"AddPaths",
"merges",
"the",
"paths",
"into",
"the",
"current",
"list",
"of",
"role",
"paths"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L294-L300 | train |
theupdateframework/notary | tuf/data/roles.go | RemoveKeys | func (r *Role) RemoveKeys(ids []string) {
r.KeyIDs = subtractStrSlices(r.KeyIDs, ids)
} | go | func (r *Role) RemoveKeys(ids []string) {
r.KeyIDs = subtractStrSlices(r.KeyIDs, ids)
} | [
"func",
"(",
"r",
"*",
"Role",
")",
"RemoveKeys",
"(",
"ids",
"[",
"]",
"string",
")",
"{",
"r",
".",
"KeyIDs",
"=",
"subtractStrSlices",
"(",
"r",
".",
"KeyIDs",
",",
"ids",
")",
"\n",
"}"
] | // RemoveKeys removes the ids from the current list of key ids | [
"RemoveKeys",
"removes",
"the",
"ids",
"from",
"the",
"current",
"list",
"of",
"key",
"ids"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L303-L305 | train |
theupdateframework/notary | tuf/data/roles.go | RemovePaths | func (r *Role) RemovePaths(paths []string) {
r.Paths = subtractStrSlices(r.Paths, paths)
} | go | func (r *Role) RemovePaths(paths []string) {
r.Paths = subtractStrSlices(r.Paths, paths)
} | [
"func",
"(",
"r",
"*",
"Role",
")",
"RemovePaths",
"(",
"paths",
"[",
"]",
"string",
")",
"{",
"r",
".",
"Paths",
"=",
"subtractStrSlices",
"(",
"r",
".",
"Paths",
",",
"paths",
")",
"\n",
"}"
] | // RemovePaths removes the paths from the current list of role paths | [
"RemovePaths",
"removes",
"the",
"paths",
"from",
"the",
"current",
"list",
"of",
"role",
"paths"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/roles.go#L308-L310 | train |
theupdateframework/notary | server/storage/memory.go | NewMemStorage | func NewMemStorage() *MemStorage {
return &MemStorage{
tufMeta: make(map[string]verList),
keys: make(map[string]map[string]*key),
checksums: make(map[string]map[string]ver),
}
} | go | func NewMemStorage() *MemStorage {
return &MemStorage{
tufMeta: make(map[string]verList),
keys: make(map[string]map[string]*key),
checksums: make(map[string]map[string]ver),
}
} | [
"func",
"NewMemStorage",
"(",
")",
"*",
"MemStorage",
"{",
"return",
"&",
"MemStorage",
"{",
"tufMeta",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"verList",
")",
",",
"keys",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"*",
"key",
")",
",",
"checksums",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"ver",
")",
",",
"}",
"\n",
"}"
] | // NewMemStorage instantiates a memStorage instance | [
"NewMemStorage",
"instantiates",
"a",
"memStorage",
"instance"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/memory.go#L48-L54 | train |
theupdateframework/notary | server/storage/memory.go | UpdateCurrent | func (st *MemStorage) UpdateCurrent(gun data.GUN, update MetaUpdate) error {
id := entryKey(gun, update.Role)
st.lock.Lock()
defer st.lock.Unlock()
if space, ok := st.tufMeta[id]; ok {
for _, v := range space {
if v.version >= update.Version {
return ErrOldVersion{}
}
}
}
version := ver{version: update.Version, data: update.Data, createupdate: time.Now()}
st.tufMeta[id] = append(st.tufMeta[id], version)
checksumBytes := sha256.Sum256(update.Data)
checksum := hex.EncodeToString(checksumBytes[:])
_, ok := st.checksums[gun.String()]
if !ok {
st.checksums[gun.String()] = make(map[string]ver)
}
st.checksums[gun.String()][checksum] = version
if update.Role == data.CanonicalTimestampRole {
st.writeChange(gun, update.Version, checksum)
}
return nil
} | go | func (st *MemStorage) UpdateCurrent(gun data.GUN, update MetaUpdate) error {
id := entryKey(gun, update.Role)
st.lock.Lock()
defer st.lock.Unlock()
if space, ok := st.tufMeta[id]; ok {
for _, v := range space {
if v.version >= update.Version {
return ErrOldVersion{}
}
}
}
version := ver{version: update.Version, data: update.Data, createupdate: time.Now()}
st.tufMeta[id] = append(st.tufMeta[id], version)
checksumBytes := sha256.Sum256(update.Data)
checksum := hex.EncodeToString(checksumBytes[:])
_, ok := st.checksums[gun.String()]
if !ok {
st.checksums[gun.String()] = make(map[string]ver)
}
st.checksums[gun.String()][checksum] = version
if update.Role == data.CanonicalTimestampRole {
st.writeChange(gun, update.Version, checksum)
}
return nil
} | [
"func",
"(",
"st",
"*",
"MemStorage",
")",
"UpdateCurrent",
"(",
"gun",
"data",
".",
"GUN",
",",
"update",
"MetaUpdate",
")",
"error",
"{",
"id",
":=",
"entryKey",
"(",
"gun",
",",
"update",
".",
"Role",
")",
"\n",
"st",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"st",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"space",
",",
"ok",
":=",
"st",
".",
"tufMeta",
"[",
"id",
"]",
";",
"ok",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"space",
"{",
"if",
"v",
".",
"version",
">=",
"update",
".",
"Version",
"{",
"return",
"ErrOldVersion",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"version",
":=",
"ver",
"{",
"version",
":",
"update",
".",
"Version",
",",
"data",
":",
"update",
".",
"Data",
",",
"createupdate",
":",
"time",
".",
"Now",
"(",
")",
"}",
"\n",
"st",
".",
"tufMeta",
"[",
"id",
"]",
"=",
"append",
"(",
"st",
".",
"tufMeta",
"[",
"id",
"]",
",",
"version",
")",
"\n",
"checksumBytes",
":=",
"sha256",
".",
"Sum256",
"(",
"update",
".",
"Data",
")",
"\n",
"checksum",
":=",
"hex",
".",
"EncodeToString",
"(",
"checksumBytes",
"[",
":",
"]",
")",
"\n\n",
"_",
",",
"ok",
":=",
"st",
".",
"checksums",
"[",
"gun",
".",
"String",
"(",
")",
"]",
"\n",
"if",
"!",
"ok",
"{",
"st",
".",
"checksums",
"[",
"gun",
".",
"String",
"(",
")",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"ver",
")",
"\n",
"}",
"\n",
"st",
".",
"checksums",
"[",
"gun",
".",
"String",
"(",
")",
"]",
"[",
"checksum",
"]",
"=",
"version",
"\n",
"if",
"update",
".",
"Role",
"==",
"data",
".",
"CanonicalTimestampRole",
"{",
"st",
".",
"writeChange",
"(",
"gun",
",",
"update",
".",
"Version",
",",
"checksum",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateCurrent updates the meta data for a specific role | [
"UpdateCurrent",
"updates",
"the",
"meta",
"data",
"for",
"a",
"specific",
"role"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/memory.go#L57-L82 | train |
theupdateframework/notary | server/storage/memory.go | writeChange | func (st *MemStorage) writeChange(gun data.GUN, version int, checksum string) {
c := Change{
ID: strconv.Itoa(len(st.changes) + 1),
GUN: gun.String(),
Version: version,
SHA256: checksum,
CreatedAt: time.Now(),
Category: changeCategoryUpdate,
}
st.changes = append(st.changes, c)
} | go | func (st *MemStorage) writeChange(gun data.GUN, version int, checksum string) {
c := Change{
ID: strconv.Itoa(len(st.changes) + 1),
GUN: gun.String(),
Version: version,
SHA256: checksum,
CreatedAt: time.Now(),
Category: changeCategoryUpdate,
}
st.changes = append(st.changes, c)
} | [
"func",
"(",
"st",
"*",
"MemStorage",
")",
"writeChange",
"(",
"gun",
"data",
".",
"GUN",
",",
"version",
"int",
",",
"checksum",
"string",
")",
"{",
"c",
":=",
"Change",
"{",
"ID",
":",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"st",
".",
"changes",
")",
"+",
"1",
")",
",",
"GUN",
":",
"gun",
".",
"String",
"(",
")",
",",
"Version",
":",
"version",
",",
"SHA256",
":",
"checksum",
",",
"CreatedAt",
":",
"time",
".",
"Now",
"(",
")",
",",
"Category",
":",
"changeCategoryUpdate",
",",
"}",
"\n",
"st",
".",
"changes",
"=",
"append",
"(",
"st",
".",
"changes",
",",
"c",
")",
"\n",
"}"
] | // writeChange must only be called by a function already holding a lock on
// the MemStorage. Behaviour is undefined otherwise | [
"writeChange",
"must",
"only",
"be",
"called",
"by",
"a",
"function",
"already",
"holding",
"a",
"lock",
"on",
"the",
"MemStorage",
".",
"Behaviour",
"is",
"undefined",
"otherwise"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/memory.go#L86-L96 | train |
theupdateframework/notary | server/storage/memory.go | UpdateMany | func (st *MemStorage) UpdateMany(gun data.GUN, updates []MetaUpdate) error {
st.lock.Lock()
defer st.lock.Unlock()
versioner := make(map[string]map[int]struct{})
constant := struct{}{}
// ensure that we only update in one transaction
for _, u := range updates {
id := entryKey(gun, u.Role)
// prevent duplicate versions of the same role
if _, ok := versioner[u.Role.String()][u.Version]; ok {
return ErrOldVersion{}
}
if _, ok := versioner[u.Role.String()]; !ok {
versioner[u.Role.String()] = make(map[int]struct{})
}
versioner[u.Role.String()][u.Version] = constant
if space, ok := st.tufMeta[id]; ok {
for _, v := range space {
if v.version >= u.Version {
return ErrOldVersion{}
}
}
}
}
for _, u := range updates {
id := entryKey(gun, u.Role)
version := ver{version: u.Version, data: u.Data, createupdate: time.Now()}
st.tufMeta[id] = append(st.tufMeta[id], version)
sort.Sort(st.tufMeta[id]) // ensure that it's sorted
checksumBytes := sha256.Sum256(u.Data)
checksum := hex.EncodeToString(checksumBytes[:])
_, ok := st.checksums[gun.String()]
if !ok {
st.checksums[gun.String()] = make(map[string]ver)
}
st.checksums[gun.String()][checksum] = version
if u.Role == data.CanonicalTimestampRole {
st.writeChange(gun, u.Version, checksum)
}
}
return nil
} | go | func (st *MemStorage) UpdateMany(gun data.GUN, updates []MetaUpdate) error {
st.lock.Lock()
defer st.lock.Unlock()
versioner := make(map[string]map[int]struct{})
constant := struct{}{}
// ensure that we only update in one transaction
for _, u := range updates {
id := entryKey(gun, u.Role)
// prevent duplicate versions of the same role
if _, ok := versioner[u.Role.String()][u.Version]; ok {
return ErrOldVersion{}
}
if _, ok := versioner[u.Role.String()]; !ok {
versioner[u.Role.String()] = make(map[int]struct{})
}
versioner[u.Role.String()][u.Version] = constant
if space, ok := st.tufMeta[id]; ok {
for _, v := range space {
if v.version >= u.Version {
return ErrOldVersion{}
}
}
}
}
for _, u := range updates {
id := entryKey(gun, u.Role)
version := ver{version: u.Version, data: u.Data, createupdate: time.Now()}
st.tufMeta[id] = append(st.tufMeta[id], version)
sort.Sort(st.tufMeta[id]) // ensure that it's sorted
checksumBytes := sha256.Sum256(u.Data)
checksum := hex.EncodeToString(checksumBytes[:])
_, ok := st.checksums[gun.String()]
if !ok {
st.checksums[gun.String()] = make(map[string]ver)
}
st.checksums[gun.String()][checksum] = version
if u.Role == data.CanonicalTimestampRole {
st.writeChange(gun, u.Version, checksum)
}
}
return nil
} | [
"func",
"(",
"st",
"*",
"MemStorage",
")",
"UpdateMany",
"(",
"gun",
"data",
".",
"GUN",
",",
"updates",
"[",
"]",
"MetaUpdate",
")",
"error",
"{",
"st",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"st",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"versioner",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"constant",
":=",
"struct",
"{",
"}",
"{",
"}",
"\n\n",
"// ensure that we only update in one transaction",
"for",
"_",
",",
"u",
":=",
"range",
"updates",
"{",
"id",
":=",
"entryKey",
"(",
"gun",
",",
"u",
".",
"Role",
")",
"\n\n",
"// prevent duplicate versions of the same role",
"if",
"_",
",",
"ok",
":=",
"versioner",
"[",
"u",
".",
"Role",
".",
"String",
"(",
")",
"]",
"[",
"u",
".",
"Version",
"]",
";",
"ok",
"{",
"return",
"ErrOldVersion",
"{",
"}",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"versioner",
"[",
"u",
".",
"Role",
".",
"String",
"(",
")",
"]",
";",
"!",
"ok",
"{",
"versioner",
"[",
"u",
".",
"Role",
".",
"String",
"(",
")",
"]",
"=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"}",
"\n",
"versioner",
"[",
"u",
".",
"Role",
".",
"String",
"(",
")",
"]",
"[",
"u",
".",
"Version",
"]",
"=",
"constant",
"\n\n",
"if",
"space",
",",
"ok",
":=",
"st",
".",
"tufMeta",
"[",
"id",
"]",
";",
"ok",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"space",
"{",
"if",
"v",
".",
"version",
">=",
"u",
".",
"Version",
"{",
"return",
"ErrOldVersion",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"u",
":=",
"range",
"updates",
"{",
"id",
":=",
"entryKey",
"(",
"gun",
",",
"u",
".",
"Role",
")",
"\n\n",
"version",
":=",
"ver",
"{",
"version",
":",
"u",
".",
"Version",
",",
"data",
":",
"u",
".",
"Data",
",",
"createupdate",
":",
"time",
".",
"Now",
"(",
")",
"}",
"\n",
"st",
".",
"tufMeta",
"[",
"id",
"]",
"=",
"append",
"(",
"st",
".",
"tufMeta",
"[",
"id",
"]",
",",
"version",
")",
"\n",
"sort",
".",
"Sort",
"(",
"st",
".",
"tufMeta",
"[",
"id",
"]",
")",
"// ensure that it's sorted",
"\n",
"checksumBytes",
":=",
"sha256",
".",
"Sum256",
"(",
"u",
".",
"Data",
")",
"\n",
"checksum",
":=",
"hex",
".",
"EncodeToString",
"(",
"checksumBytes",
"[",
":",
"]",
")",
"\n\n",
"_",
",",
"ok",
":=",
"st",
".",
"checksums",
"[",
"gun",
".",
"String",
"(",
")",
"]",
"\n",
"if",
"!",
"ok",
"{",
"st",
".",
"checksums",
"[",
"gun",
".",
"String",
"(",
")",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"ver",
")",
"\n",
"}",
"\n",
"st",
".",
"checksums",
"[",
"gun",
".",
"String",
"(",
")",
"]",
"[",
"checksum",
"]",
"=",
"version",
"\n",
"if",
"u",
".",
"Role",
"==",
"data",
".",
"CanonicalTimestampRole",
"{",
"st",
".",
"writeChange",
"(",
"gun",
",",
"u",
".",
"Version",
",",
"checksum",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateMany updates multiple TUF records | [
"UpdateMany",
"updates",
"multiple",
"TUF",
"records"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/memory.go#L99-L147 | train |
theupdateframework/notary | server/storage/memory.go | GetCurrent | func (st *MemStorage) GetCurrent(gun data.GUN, role data.RoleName) (*time.Time, []byte, error) {
id := entryKey(gun, role)
st.lock.Lock()
defer st.lock.Unlock()
space, ok := st.tufMeta[id]
if !ok || len(space) == 0 {
return nil, nil, ErrNotFound{}
}
return &(space[len(space)-1].createupdate), space[len(space)-1].data, nil
} | go | func (st *MemStorage) GetCurrent(gun data.GUN, role data.RoleName) (*time.Time, []byte, error) {
id := entryKey(gun, role)
st.lock.Lock()
defer st.lock.Unlock()
space, ok := st.tufMeta[id]
if !ok || len(space) == 0 {
return nil, nil, ErrNotFound{}
}
return &(space[len(space)-1].createupdate), space[len(space)-1].data, nil
} | [
"func",
"(",
"st",
"*",
"MemStorage",
")",
"GetCurrent",
"(",
"gun",
"data",
".",
"GUN",
",",
"role",
"data",
".",
"RoleName",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"id",
":=",
"entryKey",
"(",
"gun",
",",
"role",
")",
"\n",
"st",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"st",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"space",
",",
"ok",
":=",
"st",
".",
"tufMeta",
"[",
"id",
"]",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"space",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
",",
"ErrNotFound",
"{",
"}",
"\n",
"}",
"\n",
"return",
"&",
"(",
"space",
"[",
"len",
"(",
"space",
")",
"-",
"1",
"]",
".",
"createupdate",
")",
",",
"space",
"[",
"len",
"(",
"space",
")",
"-",
"1",
"]",
".",
"data",
",",
"nil",
"\n",
"}"
] | // GetCurrent returns the createupdate date metadata for a given role, under a GUN. | [
"GetCurrent",
"returns",
"the",
"createupdate",
"date",
"metadata",
"for",
"a",
"given",
"role",
"under",
"a",
"GUN",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/memory.go#L150-L159 | train |
theupdateframework/notary | server/storage/memory.go | GetChecksum | func (st *MemStorage) GetChecksum(gun data.GUN, role data.RoleName, checksum string) (*time.Time, []byte, error) {
st.lock.Lock()
defer st.lock.Unlock()
space, ok := st.checksums[gun.String()][checksum]
if !ok || len(space.data) == 0 {
return nil, nil, ErrNotFound{}
}
return &(space.createupdate), space.data, nil
} | go | func (st *MemStorage) GetChecksum(gun data.GUN, role data.RoleName, checksum string) (*time.Time, []byte, error) {
st.lock.Lock()
defer st.lock.Unlock()
space, ok := st.checksums[gun.String()][checksum]
if !ok || len(space.data) == 0 {
return nil, nil, ErrNotFound{}
}
return &(space.createupdate), space.data, nil
} | [
"func",
"(",
"st",
"*",
"MemStorage",
")",
"GetChecksum",
"(",
"gun",
"data",
".",
"GUN",
",",
"role",
"data",
".",
"RoleName",
",",
"checksum",
"string",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"st",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"st",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"space",
",",
"ok",
":=",
"st",
".",
"checksums",
"[",
"gun",
".",
"String",
"(",
")",
"]",
"[",
"checksum",
"]",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"space",
".",
"data",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
",",
"ErrNotFound",
"{",
"}",
"\n",
"}",
"\n",
"return",
"&",
"(",
"space",
".",
"createupdate",
")",
",",
"space",
".",
"data",
",",
"nil",
"\n",
"}"
] | // GetChecksum returns the createupdate date and metadata for a given role, under a GUN. | [
"GetChecksum",
"returns",
"the",
"createupdate",
"date",
"and",
"metadata",
"for",
"a",
"given",
"role",
"under",
"a",
"GUN",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/memory.go#L162-L170 | train |
theupdateframework/notary | server/storage/memory.go | Delete | func (st *MemStorage) Delete(gun data.GUN) error {
st.lock.Lock()
defer st.lock.Unlock()
l := len(st.tufMeta)
for k := range st.tufMeta {
if strings.HasPrefix(k, gun.String()) {
delete(st.tufMeta, k)
}
}
if l == len(st.tufMeta) {
// we didn't delete anything, don't write change.
return nil
}
delete(st.checksums, gun.String())
c := Change{
ID: strconv.Itoa(len(st.changes) + 1),
GUN: gun.String(),
Category: changeCategoryDeletion,
CreatedAt: time.Now(),
}
st.changes = append(st.changes, c)
return nil
} | go | func (st *MemStorage) Delete(gun data.GUN) error {
st.lock.Lock()
defer st.lock.Unlock()
l := len(st.tufMeta)
for k := range st.tufMeta {
if strings.HasPrefix(k, gun.String()) {
delete(st.tufMeta, k)
}
}
if l == len(st.tufMeta) {
// we didn't delete anything, don't write change.
return nil
}
delete(st.checksums, gun.String())
c := Change{
ID: strconv.Itoa(len(st.changes) + 1),
GUN: gun.String(),
Category: changeCategoryDeletion,
CreatedAt: time.Now(),
}
st.changes = append(st.changes, c)
return nil
} | [
"func",
"(",
"st",
"*",
"MemStorage",
")",
"Delete",
"(",
"gun",
"data",
".",
"GUN",
")",
"error",
"{",
"st",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"st",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"l",
":=",
"len",
"(",
"st",
".",
"tufMeta",
")",
"\n",
"for",
"k",
":=",
"range",
"st",
".",
"tufMeta",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"k",
",",
"gun",
".",
"String",
"(",
")",
")",
"{",
"delete",
"(",
"st",
".",
"tufMeta",
",",
"k",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"l",
"==",
"len",
"(",
"st",
".",
"tufMeta",
")",
"{",
"// we didn't delete anything, don't write change.",
"return",
"nil",
"\n",
"}",
"\n",
"delete",
"(",
"st",
".",
"checksums",
",",
"gun",
".",
"String",
"(",
")",
")",
"\n",
"c",
":=",
"Change",
"{",
"ID",
":",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"st",
".",
"changes",
")",
"+",
"1",
")",
",",
"GUN",
":",
"gun",
".",
"String",
"(",
")",
",",
"Category",
":",
"changeCategoryDeletion",
",",
"CreatedAt",
":",
"time",
".",
"Now",
"(",
")",
",",
"}",
"\n",
"st",
".",
"changes",
"=",
"append",
"(",
"st",
".",
"changes",
",",
"c",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Delete deletes all the metadata for a given GUN | [
"Delete",
"deletes",
"all",
"the",
"metadata",
"for",
"a",
"given",
"GUN"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/memory.go#L188-L210 | train |
theupdateframework/notary | passphrase/passphrase.go | PromptRetriever | func PromptRetriever() notary.PassRetriever {
if !terminal.IsTerminal(int(os.Stdin.Fd())) {
return func(string, string, bool, int) (string, bool, error) {
return "", false, ErrNoInput
}
}
return PromptRetrieverWithInOut(os.Stdin, os.Stdout, nil)
} | go | func PromptRetriever() notary.PassRetriever {
if !terminal.IsTerminal(int(os.Stdin.Fd())) {
return func(string, string, bool, int) (string, bool, error) {
return "", false, ErrNoInput
}
}
return PromptRetrieverWithInOut(os.Stdin, os.Stdout, nil)
} | [
"func",
"PromptRetriever",
"(",
")",
"notary",
".",
"PassRetriever",
"{",
"if",
"!",
"terminal",
".",
"IsTerminal",
"(",
"int",
"(",
"os",
".",
"Stdin",
".",
"Fd",
"(",
")",
")",
")",
"{",
"return",
"func",
"(",
"string",
",",
"string",
",",
"bool",
",",
"int",
")",
"(",
"string",
",",
"bool",
",",
"error",
")",
"{",
"return",
"\"",
"\"",
",",
"false",
",",
"ErrNoInput",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"PromptRetrieverWithInOut",
"(",
"os",
".",
"Stdin",
",",
"os",
".",
"Stdout",
",",
"nil",
")",
"\n",
"}"
] | // PromptRetriever returns a new Retriever which will provide a prompt on stdin
// and stdout to retrieve a passphrase. stdin will be checked if it is a terminal,
// else the PromptRetriever will error when attempting to retrieve a passphrase.
// Upon successful passphrase retrievals, the passphrase will be cached such that
// subsequent prompts will produce the same passphrase. | [
"PromptRetriever",
"returns",
"a",
"new",
"Retriever",
"which",
"will",
"provide",
"a",
"prompt",
"on",
"stdin",
"and",
"stdout",
"to",
"retrieve",
"a",
"passphrase",
".",
"stdin",
"will",
"be",
"checked",
"if",
"it",
"is",
"a",
"terminal",
"else",
"the",
"PromptRetriever",
"will",
"error",
"when",
"attempting",
"to",
"retrieve",
"a",
"passphrase",
".",
"Upon",
"successful",
"passphrase",
"retrievals",
"the",
"passphrase",
"will",
"be",
"cached",
"such",
"that",
"subsequent",
"prompts",
"will",
"produce",
"the",
"same",
"passphrase",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/passphrase/passphrase.go#L51-L58 | train |
theupdateframework/notary | passphrase/passphrase.go | PromptRetrieverWithInOut | func PromptRetrieverWithInOut(in io.Reader, out io.Writer, aliasMap map[string]string) notary.PassRetriever {
bound := &boundRetriever{
in: in,
out: out,
aliasMap: aliasMap,
passphraseCache: make(map[string]string),
}
return bound.getPassphrase
} | go | func PromptRetrieverWithInOut(in io.Reader, out io.Writer, aliasMap map[string]string) notary.PassRetriever {
bound := &boundRetriever{
in: in,
out: out,
aliasMap: aliasMap,
passphraseCache: make(map[string]string),
}
return bound.getPassphrase
} | [
"func",
"PromptRetrieverWithInOut",
"(",
"in",
"io",
".",
"Reader",
",",
"out",
"io",
".",
"Writer",
",",
"aliasMap",
"map",
"[",
"string",
"]",
"string",
")",
"notary",
".",
"PassRetriever",
"{",
"bound",
":=",
"&",
"boundRetriever",
"{",
"in",
":",
"in",
",",
"out",
":",
"out",
",",
"aliasMap",
":",
"aliasMap",
",",
"passphraseCache",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"}",
"\n\n",
"return",
"bound",
".",
"getPassphrase",
"\n",
"}"
] | // PromptRetrieverWithInOut returns a new Retriever which will provide a
// prompt using the given in and out readers. The passphrase will be cached
// such that subsequent prompts will produce the same passphrase.
// aliasMap can be used to specify display names for TUF key aliases. If aliasMap
// is nil, a sensible default will be used. | [
"PromptRetrieverWithInOut",
"returns",
"a",
"new",
"Retriever",
"which",
"will",
"provide",
"a",
"prompt",
"using",
"the",
"given",
"in",
"and",
"out",
"readers",
".",
"The",
"passphrase",
"will",
"be",
"cached",
"such",
"that",
"subsequent",
"prompts",
"will",
"produce",
"the",
"same",
"passphrase",
".",
"aliasMap",
"can",
"be",
"used",
"to",
"specify",
"display",
"names",
"for",
"TUF",
"key",
"aliases",
".",
"If",
"aliasMap",
"is",
"nil",
"a",
"sensible",
"default",
"will",
"be",
"used",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/passphrase/passphrase.go#L176-L185 | train |
theupdateframework/notary | passphrase/passphrase.go | ConstantRetriever | func ConstantRetriever(constantPassphrase string) notary.PassRetriever {
return func(k, a string, c bool, n int) (string, bool, error) {
return constantPassphrase, false, nil
}
} | go | func ConstantRetriever(constantPassphrase string) notary.PassRetriever {
return func(k, a string, c bool, n int) (string, bool, error) {
return constantPassphrase, false, nil
}
} | [
"func",
"ConstantRetriever",
"(",
"constantPassphrase",
"string",
")",
"notary",
".",
"PassRetriever",
"{",
"return",
"func",
"(",
"k",
",",
"a",
"string",
",",
"c",
"bool",
",",
"n",
"int",
")",
"(",
"string",
",",
"bool",
",",
"error",
")",
"{",
"return",
"constantPassphrase",
",",
"false",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // ConstantRetriever returns a new Retriever which will return a constant string
// as a passphrase. | [
"ConstantRetriever",
"returns",
"a",
"new",
"Retriever",
"which",
"will",
"return",
"a",
"constant",
"string",
"as",
"a",
"passphrase",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/passphrase/passphrase.go#L189-L193 | train |
theupdateframework/notary | passphrase/passphrase.go | GetPassphrase | func GetPassphrase(in *bufio.Reader) ([]byte, error) {
var (
passphrase []byte
err error
)
if terminal.IsTerminal(int(os.Stdin.Fd())) {
passphrase, err = terminal.ReadPassword(int(os.Stdin.Fd()))
} else {
passphrase, err = in.ReadBytes('\n')
}
return passphrase, err
} | go | func GetPassphrase(in *bufio.Reader) ([]byte, error) {
var (
passphrase []byte
err error
)
if terminal.IsTerminal(int(os.Stdin.Fd())) {
passphrase, err = terminal.ReadPassword(int(os.Stdin.Fd()))
} else {
passphrase, err = in.ReadBytes('\n')
}
return passphrase, err
} | [
"func",
"GetPassphrase",
"(",
"in",
"*",
"bufio",
".",
"Reader",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"(",
"passphrase",
"[",
"]",
"byte",
"\n",
"err",
"error",
"\n",
")",
"\n\n",
"if",
"terminal",
".",
"IsTerminal",
"(",
"int",
"(",
"os",
".",
"Stdin",
".",
"Fd",
"(",
")",
")",
")",
"{",
"passphrase",
",",
"err",
"=",
"terminal",
".",
"ReadPassword",
"(",
"int",
"(",
"os",
".",
"Stdin",
".",
"Fd",
"(",
")",
")",
")",
"\n",
"}",
"else",
"{",
"passphrase",
",",
"err",
"=",
"in",
".",
"ReadBytes",
"(",
"'\\n'",
")",
"\n",
"}",
"\n\n",
"return",
"passphrase",
",",
"err",
"\n",
"}"
] | // GetPassphrase get the passphrase from bufio.Reader or from terminal.
// If typing on the terminal, we disable terminal to echo the passphrase. | [
"GetPassphrase",
"get",
"the",
"passphrase",
"from",
"bufio",
".",
"Reader",
"or",
"from",
"terminal",
".",
"If",
"typing",
"on",
"the",
"terminal",
"we",
"disable",
"terminal",
"to",
"echo",
"the",
"passphrase",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/passphrase/passphrase.go#L197-L210 | train |
theupdateframework/notary | tuf/validation/errors.go | UnmarshalJSON | func (s *SerializableError) UnmarshalJSON(text []byte) (err error) {
var x struct{ Name string }
err = json.Unmarshal(text, &x)
if err != nil {
return
}
var theError error
switch x.Name {
case "ErrValidation":
var e struct{ Error ErrValidation }
err = json.Unmarshal(text, &e)
theError = e.Error
case "ErrBadHierarchy":
var e struct{ Error ErrBadHierarchy }
err = json.Unmarshal(text, &e)
theError = e.Error
case "ErrBadRoot":
var e struct{ Error ErrBadRoot }
err = json.Unmarshal(text, &e)
theError = e.Error
case "ErrBadTargets":
var e struct{ Error ErrBadTargets }
err = json.Unmarshal(text, &e)
theError = e.Error
case "ErrBadSnapshot":
var e struct{ Error ErrBadSnapshot }
err = json.Unmarshal(text, &e)
theError = e.Error
default:
err = fmt.Errorf("do not know how to unmarshal %s", x.Name)
return
}
if err != nil {
return
}
s.Name = x.Name
s.Error = theError
return nil
} | go | func (s *SerializableError) UnmarshalJSON(text []byte) (err error) {
var x struct{ Name string }
err = json.Unmarshal(text, &x)
if err != nil {
return
}
var theError error
switch x.Name {
case "ErrValidation":
var e struct{ Error ErrValidation }
err = json.Unmarshal(text, &e)
theError = e.Error
case "ErrBadHierarchy":
var e struct{ Error ErrBadHierarchy }
err = json.Unmarshal(text, &e)
theError = e.Error
case "ErrBadRoot":
var e struct{ Error ErrBadRoot }
err = json.Unmarshal(text, &e)
theError = e.Error
case "ErrBadTargets":
var e struct{ Error ErrBadTargets }
err = json.Unmarshal(text, &e)
theError = e.Error
case "ErrBadSnapshot":
var e struct{ Error ErrBadSnapshot }
err = json.Unmarshal(text, &e)
theError = e.Error
default:
err = fmt.Errorf("do not know how to unmarshal %s", x.Name)
return
}
if err != nil {
return
}
s.Name = x.Name
s.Error = theError
return nil
} | [
"func",
"(",
"s",
"*",
"SerializableError",
")",
"UnmarshalJSON",
"(",
"text",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"var",
"x",
"struct",
"{",
"Name",
"string",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"text",
",",
"&",
"x",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"var",
"theError",
"error",
"\n",
"switch",
"x",
".",
"Name",
"{",
"case",
"\"",
"\"",
":",
"var",
"e",
"struct",
"{",
"Error",
"ErrValidation",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"text",
",",
"&",
"e",
")",
"\n",
"theError",
"=",
"e",
".",
"Error",
"\n",
"case",
"\"",
"\"",
":",
"var",
"e",
"struct",
"{",
"Error",
"ErrBadHierarchy",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"text",
",",
"&",
"e",
")",
"\n",
"theError",
"=",
"e",
".",
"Error",
"\n",
"case",
"\"",
"\"",
":",
"var",
"e",
"struct",
"{",
"Error",
"ErrBadRoot",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"text",
",",
"&",
"e",
")",
"\n",
"theError",
"=",
"e",
".",
"Error",
"\n",
"case",
"\"",
"\"",
":",
"var",
"e",
"struct",
"{",
"Error",
"ErrBadTargets",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"text",
",",
"&",
"e",
")",
"\n",
"theError",
"=",
"e",
".",
"Error",
"\n",
"case",
"\"",
"\"",
":",
"var",
"e",
"struct",
"{",
"Error",
"ErrBadSnapshot",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"text",
",",
"&",
"e",
")",
"\n",
"theError",
"=",
"e",
".",
"Error",
"\n",
"default",
":",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"x",
".",
"Name",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"s",
".",
"Name",
"=",
"x",
".",
"Name",
"\n",
"s",
".",
"Error",
"=",
"theError",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalJSON attempts to unmarshal the error into the right type | [
"UnmarshalJSON",
"attempts",
"to",
"unmarshal",
"the",
"error",
"into",
"the",
"right",
"type"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/validation/errors.go#L67-L105 | train |
theupdateframework/notary | tuf/validation/errors.go | NewSerializableError | func NewSerializableError(err error) (*SerializableError, error) {
// make sure it's one of our errors
var name string
switch err.(type) {
case ErrValidation:
name = "ErrValidation"
case ErrBadHierarchy:
name = "ErrBadHierarchy"
case ErrBadRoot:
name = "ErrBadRoot"
case ErrBadTargets:
name = "ErrBadTargets"
case ErrBadSnapshot:
name = "ErrBadSnapshot"
default:
return nil, fmt.Errorf("does not support serializing non-validation errors")
}
return &SerializableError{Name: name, Error: err}, nil
} | go | func NewSerializableError(err error) (*SerializableError, error) {
// make sure it's one of our errors
var name string
switch err.(type) {
case ErrValidation:
name = "ErrValidation"
case ErrBadHierarchy:
name = "ErrBadHierarchy"
case ErrBadRoot:
name = "ErrBadRoot"
case ErrBadTargets:
name = "ErrBadTargets"
case ErrBadSnapshot:
name = "ErrBadSnapshot"
default:
return nil, fmt.Errorf("does not support serializing non-validation errors")
}
return &SerializableError{Name: name, Error: err}, nil
} | [
"func",
"NewSerializableError",
"(",
"err",
"error",
")",
"(",
"*",
"SerializableError",
",",
"error",
")",
"{",
"// make sure it's one of our errors",
"var",
"name",
"string",
"\n",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"ErrValidation",
":",
"name",
"=",
"\"",
"\"",
"\n",
"case",
"ErrBadHierarchy",
":",
"name",
"=",
"\"",
"\"",
"\n",
"case",
"ErrBadRoot",
":",
"name",
"=",
"\"",
"\"",
"\n",
"case",
"ErrBadTargets",
":",
"name",
"=",
"\"",
"\"",
"\n",
"case",
"ErrBadSnapshot",
":",
"name",
"=",
"\"",
"\"",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"SerializableError",
"{",
"Name",
":",
"name",
",",
"Error",
":",
"err",
"}",
",",
"nil",
"\n",
"}"
] | // NewSerializableError serializes one of the above errors into JSON | [
"NewSerializableError",
"serializes",
"one",
"of",
"the",
"above",
"errors",
"into",
"JSON"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/validation/errors.go#L108-L126 | train |
theupdateframework/notary | cmd/notary/util.go | getPayload | func getPayload(t *tufCommander) ([]byte, error) {
// Reads from the given file
if t.input != "" {
// Please note that ReadFile will cut off the size if it was over 1e9.
// Thus, if the size of the file exceeds 1GB, the over part will not be
// loaded into the buffer.
payload, err := ioutil.ReadFile(t.input)
if err != nil {
return nil, err
}
return payload, nil
}
// Reads all of the data on STDIN
payload, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return nil, fmt.Errorf("Error reading content from STDIN: %v", err)
}
return payload, nil
} | go | func getPayload(t *tufCommander) ([]byte, error) {
// Reads from the given file
if t.input != "" {
// Please note that ReadFile will cut off the size if it was over 1e9.
// Thus, if the size of the file exceeds 1GB, the over part will not be
// loaded into the buffer.
payload, err := ioutil.ReadFile(t.input)
if err != nil {
return nil, err
}
return payload, nil
}
// Reads all of the data on STDIN
payload, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return nil, fmt.Errorf("Error reading content from STDIN: %v", err)
}
return payload, nil
} | [
"func",
"getPayload",
"(",
"t",
"*",
"tufCommander",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Reads from the given file",
"if",
"t",
".",
"input",
"!=",
"\"",
"\"",
"{",
"// Please note that ReadFile will cut off the size if it was over 1e9.",
"// Thus, if the size of the file exceeds 1GB, the over part will not be",
"// loaded into the buffer.",
"payload",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"t",
".",
"input",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"payload",
",",
"nil",
"\n",
"}",
"\n\n",
"// Reads all of the data on STDIN",
"payload",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"os",
".",
"Stdin",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"payload",
",",
"nil",
"\n",
"}"
] | // getPayload is a helper function to get the content used to be verified
// either from an existing file or STDIN. | [
"getPayload",
"is",
"a",
"helper",
"function",
"to",
"get",
"the",
"content",
"used",
"to",
"be",
"verified",
"either",
"from",
"an",
"existing",
"file",
"or",
"STDIN",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/util.go#L17-L37 | train |
theupdateframework/notary | cmd/notary/util.go | feedback | func feedback(t *tufCommander, payload []byte) error {
// We only get here when everything goes well, since the flag "quiet" was
// provided, we output nothing but just return.
if t.quiet {
return nil
}
// Flag "quiet" was not "true", that's why we get here.
if t.output != "" {
return ioutil.WriteFile(t.output, payload, 0644)
}
os.Stdout.Write(payload)
return nil
} | go | func feedback(t *tufCommander, payload []byte) error {
// We only get here when everything goes well, since the flag "quiet" was
// provided, we output nothing but just return.
if t.quiet {
return nil
}
// Flag "quiet" was not "true", that's why we get here.
if t.output != "" {
return ioutil.WriteFile(t.output, payload, 0644)
}
os.Stdout.Write(payload)
return nil
} | [
"func",
"feedback",
"(",
"t",
"*",
"tufCommander",
",",
"payload",
"[",
"]",
"byte",
")",
"error",
"{",
"// We only get here when everything goes well, since the flag \"quiet\" was",
"// provided, we output nothing but just return.",
"if",
"t",
".",
"quiet",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Flag \"quiet\" was not \"true\", that's why we get here.",
"if",
"t",
".",
"output",
"!=",
"\"",
"\"",
"{",
"return",
"ioutil",
".",
"WriteFile",
"(",
"t",
".",
"output",
",",
"payload",
",",
"0644",
")",
"\n",
"}",
"\n\n",
"os",
".",
"Stdout",
".",
"Write",
"(",
"payload",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // feedback is a helper function to print the payload to a file or STDOUT or keep quiet
// due to the value of flag "quiet" and "output". | [
"feedback",
"is",
"a",
"helper",
"function",
"to",
"print",
"the",
"payload",
"to",
"a",
"file",
"or",
"STDOUT",
"or",
"keep",
"quiet",
"due",
"to",
"the",
"value",
"of",
"flag",
"quiet",
"and",
"output",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/util.go#L41-L55 | train |
theupdateframework/notary | cmd/notary/util.go | homeExpand | func homeExpand(homeDir, path string) string {
if path == "" || path[0] != '~' || (len(path) > 1 && path[1] != os.PathSeparator) {
return path
}
return filepath.Join(homeDir, path[1:])
} | go | func homeExpand(homeDir, path string) string {
if path == "" || path[0] != '~' || (len(path) > 1 && path[1] != os.PathSeparator) {
return path
}
return filepath.Join(homeDir, path[1:])
} | [
"func",
"homeExpand",
"(",
"homeDir",
",",
"path",
"string",
")",
"string",
"{",
"if",
"path",
"==",
"\"",
"\"",
"||",
"path",
"[",
"0",
"]",
"!=",
"'~'",
"||",
"(",
"len",
"(",
"path",
")",
">",
"1",
"&&",
"path",
"[",
"1",
"]",
"!=",
"os",
".",
"PathSeparator",
")",
"{",
"return",
"path",
"\n",
"}",
"\n",
"return",
"filepath",
".",
"Join",
"(",
"homeDir",
",",
"path",
"[",
"1",
":",
"]",
")",
"\n",
"}"
] | // homeExpand will expand an initial ~ to the user home directory. This is supported for
// config files where the shell will not have expanded paths. | [
"homeExpand",
"will",
"expand",
"an",
"initial",
"~",
"to",
"the",
"user",
"home",
"directory",
".",
"This",
"is",
"supported",
"for",
"config",
"files",
"where",
"the",
"shell",
"will",
"not",
"have",
"expanded",
"paths",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/util.go#L59-L64 | train |
theupdateframework/notary | server/handlers/default.go | MainHandler | func MainHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// For now it only supports `GET`
if r.Method != "GET" {
return errors.ErrGenericNotFound.WithDetail(nil)
}
if _, err := w.Write([]byte("{}")); err != nil {
return errors.ErrUnknown.WithDetail(err)
}
return nil
} | go | func MainHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// For now it only supports `GET`
if r.Method != "GET" {
return errors.ErrGenericNotFound.WithDetail(nil)
}
if _, err := w.Write([]byte("{}")); err != nil {
return errors.ErrUnknown.WithDetail(err)
}
return nil
} | [
"func",
"MainHandler",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"// For now it only supports `GET`",
"if",
"r",
".",
"Method",
"!=",
"\"",
"\"",
"{",
"return",
"errors",
".",
"ErrGenericNotFound",
".",
"WithDetail",
"(",
"nil",
")",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"ErrUnknown",
".",
"WithDetail",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // MainHandler is the default handler for the server | [
"MainHandler",
"is",
"the",
"default",
"handler",
"for",
"the",
"server"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/default.go#L28-L38 | train |
theupdateframework/notary | server/handlers/default.go | AtomicUpdateHandler | func AtomicUpdateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
defer r.Body.Close()
vars := mux.Vars(r)
return atomicUpdateHandler(ctx, w, r, vars)
} | go | func AtomicUpdateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
defer r.Body.Close()
vars := mux.Vars(r)
return atomicUpdateHandler(ctx, w, r, vars)
} | [
"func",
"AtomicUpdateHandler",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"vars",
":=",
"mux",
".",
"Vars",
"(",
"r",
")",
"\n",
"return",
"atomicUpdateHandler",
"(",
"ctx",
",",
"w",
",",
"r",
",",
"vars",
")",
"\n",
"}"
] | // AtomicUpdateHandler will accept multiple TUF files and ensure that the storage
// backend is atomically updated with all the new records. | [
"AtomicUpdateHandler",
"will",
"accept",
"multiple",
"TUF",
"files",
"and",
"ensure",
"that",
"the",
"storage",
"backend",
"is",
"atomically",
"updated",
"with",
"all",
"the",
"new",
"records",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/default.go#L42-L46 | train |
theupdateframework/notary | server/handlers/default.go | logTS | func logTS(logger ctxu.Logger, gun string, updates []storage.MetaUpdate) {
for _, update := range updates {
if update.Role == data.CanonicalTimestampRole {
checksumBin := sha256.Sum256(update.Data)
checksum := hex.EncodeToString(checksumBin[:])
logger.Infof("updated %s to timestamp version %d, checksum %s", gun, update.Version, checksum)
break
}
}
} | go | func logTS(logger ctxu.Logger, gun string, updates []storage.MetaUpdate) {
for _, update := range updates {
if update.Role == data.CanonicalTimestampRole {
checksumBin := sha256.Sum256(update.Data)
checksum := hex.EncodeToString(checksumBin[:])
logger.Infof("updated %s to timestamp version %d, checksum %s", gun, update.Version, checksum)
break
}
}
} | [
"func",
"logTS",
"(",
"logger",
"ctxu",
".",
"Logger",
",",
"gun",
"string",
",",
"updates",
"[",
"]",
"storage",
".",
"MetaUpdate",
")",
"{",
"for",
"_",
",",
"update",
":=",
"range",
"updates",
"{",
"if",
"update",
".",
"Role",
"==",
"data",
".",
"CanonicalTimestampRole",
"{",
"checksumBin",
":=",
"sha256",
".",
"Sum256",
"(",
"update",
".",
"Data",
")",
"\n",
"checksum",
":=",
"hex",
".",
"EncodeToString",
"(",
"checksumBin",
"[",
":",
"]",
")",
"\n",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"gun",
",",
"update",
".",
"Version",
",",
"checksum",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // logTS logs the timestamp update at Info level | [
"logTS",
"logs",
"the",
"timestamp",
"update",
"at",
"Info",
"level"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/default.go#L126-L135 | train |
theupdateframework/notary | server/handlers/default.go | GetHandler | func GetHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
defer r.Body.Close()
vars := mux.Vars(r)
return getHandler(ctx, w, r, vars)
} | go | func GetHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
defer r.Body.Close()
vars := mux.Vars(r)
return getHandler(ctx, w, r, vars)
} | [
"func",
"GetHandler",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"vars",
":=",
"mux",
".",
"Vars",
"(",
"r",
")",
"\n",
"return",
"getHandler",
"(",
"ctx",
",",
"w",
",",
"r",
",",
"vars",
")",
"\n",
"}"
] | // GetHandler returns the json for a specified role and GUN. | [
"GetHandler",
"returns",
"the",
"json",
"for",
"a",
"specified",
"role",
"and",
"GUN",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/default.go#L138-L142 | train |
theupdateframework/notary | server/handlers/default.go | DeleteHandler | func DeleteHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
gun := data.GUN(vars["gun"])
logger := ctxu.GetLoggerWithField(ctx, gun, "gun")
s := ctx.Value(notary.CtxKeyMetaStore)
store, ok := s.(storage.MetaStore)
if !ok {
logger.Error("500 DELETE repository: no storage exists")
return errors.ErrNoStorage.WithDetail(nil)
}
err := store.Delete(gun)
if err != nil {
logger.Error("500 DELETE repository")
return errors.ErrUnknown.WithDetail(err)
}
logger.Infof("trust data deleted for %s", gun)
return nil
} | go | func DeleteHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
gun := data.GUN(vars["gun"])
logger := ctxu.GetLoggerWithField(ctx, gun, "gun")
s := ctx.Value(notary.CtxKeyMetaStore)
store, ok := s.(storage.MetaStore)
if !ok {
logger.Error("500 DELETE repository: no storage exists")
return errors.ErrNoStorage.WithDetail(nil)
}
err := store.Delete(gun)
if err != nil {
logger.Error("500 DELETE repository")
return errors.ErrUnknown.WithDetail(err)
}
logger.Infof("trust data deleted for %s", gun)
return nil
} | [
"func",
"DeleteHandler",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"vars",
":=",
"mux",
".",
"Vars",
"(",
"r",
")",
"\n",
"gun",
":=",
"data",
".",
"GUN",
"(",
"vars",
"[",
"\"",
"\"",
"]",
")",
"\n",
"logger",
":=",
"ctxu",
".",
"GetLoggerWithField",
"(",
"ctx",
",",
"gun",
",",
"\"",
"\"",
")",
"\n",
"s",
":=",
"ctx",
".",
"Value",
"(",
"notary",
".",
"CtxKeyMetaStore",
")",
"\n",
"store",
",",
"ok",
":=",
"s",
".",
"(",
"storage",
".",
"MetaStore",
")",
"\n",
"if",
"!",
"ok",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"errors",
".",
"ErrNoStorage",
".",
"WithDetail",
"(",
"nil",
")",
"\n",
"}",
"\n",
"err",
":=",
"store",
".",
"Delete",
"(",
"gun",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"errors",
".",
"ErrUnknown",
".",
"WithDetail",
"(",
"err",
")",
"\n",
"}",
"\n",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"gun",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // DeleteHandler deletes all data for a GUN. A 200 responses indicates success. | [
"DeleteHandler",
"deletes",
"all",
"data",
"for",
"a",
"GUN",
".",
"A",
"200",
"responses",
"indicates",
"success",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/default.go#L179-L196 | train |
theupdateframework/notary | server/handlers/default.go | GetKeyHandler | func GetKeyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
defer r.Body.Close()
vars := mux.Vars(r)
return getKeyHandler(ctx, w, r, vars)
} | go | func GetKeyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
defer r.Body.Close()
vars := mux.Vars(r)
return getKeyHandler(ctx, w, r, vars)
} | [
"func",
"GetKeyHandler",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"vars",
":=",
"mux",
".",
"Vars",
"(",
"r",
")",
"\n",
"return",
"getKeyHandler",
"(",
"ctx",
",",
"w",
",",
"r",
",",
"vars",
")",
"\n",
"}"
] | // GetKeyHandler returns a public key for the specified role, creating a new key-pair
// it if it doesn't yet exist | [
"GetKeyHandler",
"returns",
"a",
"public",
"key",
"for",
"the",
"specified",
"role",
"creating",
"a",
"new",
"key",
"-",
"pair",
"it",
"if",
"it",
"doesn",
"t",
"yet",
"exist"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/default.go#L200-L204 | train |
theupdateframework/notary | server/handlers/default.go | RotateKeyHandler | func RotateKeyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
defer r.Body.Close()
vars := mux.Vars(r)
return rotateKeyHandler(ctx, w, r, vars)
} | go | func RotateKeyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
defer r.Body.Close()
vars := mux.Vars(r)
return rotateKeyHandler(ctx, w, r, vars)
} | [
"func",
"RotateKeyHandler",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"vars",
":=",
"mux",
".",
"Vars",
"(",
"r",
")",
"\n",
"return",
"rotateKeyHandler",
"(",
"ctx",
",",
"w",
",",
"r",
",",
"vars",
")",
"\n",
"}"
] | // RotateKeyHandler rotates the remote key for the specified role, returning the public key | [
"RotateKeyHandler",
"rotates",
"the",
"remote",
"key",
"for",
"the",
"specified",
"role",
"returning",
"the",
"public",
"key"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/default.go#L238-L242 | train |
theupdateframework/notary | server/handlers/default.go | setupKeyHandler | func setupKeyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string, actionVerb string) (data.RoleName, data.GUN, string, storage.MetaStore, signed.CryptoService, error) {
gun := data.GUN(vars["gun"])
logger := ctxu.GetLoggerWithField(ctx, gun, "gun")
if gun == "" {
logger.Infof("400 %s no gun in request", actionVerb)
return "", "", "", nil, nil, errors.ErrUnknown.WithDetail("no gun")
}
role := data.RoleName(vars["tufRole"])
if role == "" {
logger.Infof("400 %s no role in request", actionVerb)
return "", "", "", nil, nil, errors.ErrUnknown.WithDetail("no role")
}
s := ctx.Value(notary.CtxKeyMetaStore)
store, ok := s.(storage.MetaStore)
if !ok || store == nil {
logger.Errorf("500 %s storage not configured", actionVerb)
return "", "", "", nil, nil, errors.ErrNoStorage.WithDetail(nil)
}
c := ctx.Value(notary.CtxKeyCryptoSvc)
crypto, ok := c.(signed.CryptoService)
if !ok || crypto == nil {
logger.Errorf("500 %s crypto service not configured", actionVerb)
return "", "", "", nil, nil, errors.ErrNoCryptoService.WithDetail(nil)
}
algo := ctx.Value(notary.CtxKeyKeyAlgo)
keyAlgo, ok := algo.(string)
if !ok || keyAlgo == "" {
logger.Errorf("500 %s key algorithm not configured", actionVerb)
return "", "", "", nil, nil, errors.ErrNoKeyAlgorithm.WithDetail(nil)
}
return role, gun, keyAlgo, store, crypto, nil
} | go | func setupKeyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string, actionVerb string) (data.RoleName, data.GUN, string, storage.MetaStore, signed.CryptoService, error) {
gun := data.GUN(vars["gun"])
logger := ctxu.GetLoggerWithField(ctx, gun, "gun")
if gun == "" {
logger.Infof("400 %s no gun in request", actionVerb)
return "", "", "", nil, nil, errors.ErrUnknown.WithDetail("no gun")
}
role := data.RoleName(vars["tufRole"])
if role == "" {
logger.Infof("400 %s no role in request", actionVerb)
return "", "", "", nil, nil, errors.ErrUnknown.WithDetail("no role")
}
s := ctx.Value(notary.CtxKeyMetaStore)
store, ok := s.(storage.MetaStore)
if !ok || store == nil {
logger.Errorf("500 %s storage not configured", actionVerb)
return "", "", "", nil, nil, errors.ErrNoStorage.WithDetail(nil)
}
c := ctx.Value(notary.CtxKeyCryptoSvc)
crypto, ok := c.(signed.CryptoService)
if !ok || crypto == nil {
logger.Errorf("500 %s crypto service not configured", actionVerb)
return "", "", "", nil, nil, errors.ErrNoCryptoService.WithDetail(nil)
}
algo := ctx.Value(notary.CtxKeyKeyAlgo)
keyAlgo, ok := algo.(string)
if !ok || keyAlgo == "" {
logger.Errorf("500 %s key algorithm not configured", actionVerb)
return "", "", "", nil, nil, errors.ErrNoKeyAlgorithm.WithDetail(nil)
}
return role, gun, keyAlgo, store, crypto, nil
} | [
"func",
"setupKeyHandler",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"vars",
"map",
"[",
"string",
"]",
"string",
",",
"actionVerb",
"string",
")",
"(",
"data",
".",
"RoleName",
",",
"data",
".",
"GUN",
",",
"string",
",",
"storage",
".",
"MetaStore",
",",
"signed",
".",
"CryptoService",
",",
"error",
")",
"{",
"gun",
":=",
"data",
".",
"GUN",
"(",
"vars",
"[",
"\"",
"\"",
"]",
")",
"\n",
"logger",
":=",
"ctxu",
".",
"GetLoggerWithField",
"(",
"ctx",
",",
"gun",
",",
"\"",
"\"",
")",
"\n",
"if",
"gun",
"==",
"\"",
"\"",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"actionVerb",
")",
"\n",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
",",
"nil",
",",
"errors",
".",
"ErrUnknown",
".",
"WithDetail",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"role",
":=",
"data",
".",
"RoleName",
"(",
"vars",
"[",
"\"",
"\"",
"]",
")",
"\n",
"if",
"role",
"==",
"\"",
"\"",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"actionVerb",
")",
"\n",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
",",
"nil",
",",
"errors",
".",
"ErrUnknown",
".",
"WithDetail",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"s",
":=",
"ctx",
".",
"Value",
"(",
"notary",
".",
"CtxKeyMetaStore",
")",
"\n",
"store",
",",
"ok",
":=",
"s",
".",
"(",
"storage",
".",
"MetaStore",
")",
"\n",
"if",
"!",
"ok",
"||",
"store",
"==",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"actionVerb",
")",
"\n",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
",",
"nil",
",",
"errors",
".",
"ErrNoStorage",
".",
"WithDetail",
"(",
"nil",
")",
"\n",
"}",
"\n",
"c",
":=",
"ctx",
".",
"Value",
"(",
"notary",
".",
"CtxKeyCryptoSvc",
")",
"\n",
"crypto",
",",
"ok",
":=",
"c",
".",
"(",
"signed",
".",
"CryptoService",
")",
"\n",
"if",
"!",
"ok",
"||",
"crypto",
"==",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"actionVerb",
")",
"\n",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
",",
"nil",
",",
"errors",
".",
"ErrNoCryptoService",
".",
"WithDetail",
"(",
"nil",
")",
"\n",
"}",
"\n",
"algo",
":=",
"ctx",
".",
"Value",
"(",
"notary",
".",
"CtxKeyKeyAlgo",
")",
"\n",
"keyAlgo",
",",
"ok",
":=",
"algo",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"||",
"keyAlgo",
"==",
"\"",
"\"",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"actionVerb",
")",
"\n",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
",",
"nil",
",",
"errors",
".",
"ErrNoKeyAlgorithm",
".",
"WithDetail",
"(",
"nil",
")",
"\n",
"}",
"\n\n",
"return",
"role",
",",
"gun",
",",
"keyAlgo",
",",
"store",
",",
"crypto",
",",
"nil",
"\n",
"}"
] | // To be called before getKeyHandler or rotateKeyHandler | [
"To",
"be",
"called",
"before",
"getKeyHandler",
"or",
"rotateKeyHandler"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/default.go#L276-L310 | train |
theupdateframework/notary | server/handlers/default.go | NotFoundHandler | func NotFoundHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return errors.ErrMetadataNotFound.WithDetail(nil)
} | go | func NotFoundHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return errors.ErrMetadataNotFound.WithDetail(nil)
} | [
"func",
"NotFoundHandler",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"return",
"errors",
".",
"ErrMetadataNotFound",
".",
"WithDetail",
"(",
"nil",
")",
"\n",
"}"
] | // NotFoundHandler is used as a generic catch all handler to return the ErrMetadataNotFound
// 404 response | [
"NotFoundHandler",
"is",
"used",
"as",
"a",
"generic",
"catch",
"all",
"handler",
"to",
"return",
"the",
"ErrMetadataNotFound",
"404",
"response"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/default.go#L314-L316 | train |
theupdateframework/notary | server/storage/sqldb.go | NewSQLStorage | func NewSQLStorage(dialect string, args ...interface{}) (*SQLStorage, error) {
gormDB, err := gorm.Open(dialect, args...)
if err != nil {
return nil, err
}
return &SQLStorage{
DB: *gormDB,
}, nil
} | go | func NewSQLStorage(dialect string, args ...interface{}) (*SQLStorage, error) {
gormDB, err := gorm.Open(dialect, args...)
if err != nil {
return nil, err
}
return &SQLStorage{
DB: *gormDB,
}, nil
} | [
"func",
"NewSQLStorage",
"(",
"dialect",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"SQLStorage",
",",
"error",
")",
"{",
"gormDB",
",",
"err",
":=",
"gorm",
".",
"Open",
"(",
"dialect",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"SQLStorage",
"{",
"DB",
":",
"*",
"gormDB",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewSQLStorage is a convenience method to create a SQLStorage | [
"NewSQLStorage",
"is",
"a",
"convenience",
"method",
"to",
"create",
"a",
"SQLStorage"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L23-L31 | train |
theupdateframework/notary | server/storage/sqldb.go | translateOldVersionError | func translateOldVersionError(err error) error {
switch err := err.(type) {
case *mysql.MySQLError:
// https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
// 1022 = Can't write; duplicate key in table '%s'
// 1062 = Duplicate entry '%s' for key %d
if err.Number == 1022 || err.Number == 1062 {
return ErrOldVersion{}
}
}
return err
} | go | func translateOldVersionError(err error) error {
switch err := err.(type) {
case *mysql.MySQLError:
// https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
// 1022 = Can't write; duplicate key in table '%s'
// 1062 = Duplicate entry '%s' for key %d
if err.Number == 1022 || err.Number == 1062 {
return ErrOldVersion{}
}
}
return err
} | [
"func",
"translateOldVersionError",
"(",
"err",
"error",
")",
"error",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"*",
"mysql",
".",
"MySQLError",
":",
"// https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html",
"// 1022 = Can't write; duplicate key in table '%s'",
"// 1062 = Duplicate entry '%s' for key %d",
"if",
"err",
".",
"Number",
"==",
"1022",
"||",
"err",
".",
"Number",
"==",
"1062",
"{",
"return",
"ErrOldVersion",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // translateOldVersionError captures DB errors, and attempts to translate
// duplicate entry - currently only supports MySQL and Sqlite3 | [
"translateOldVersionError",
"captures",
"DB",
"errors",
"and",
"attempts",
"to",
"translate",
"duplicate",
"entry",
"-",
"currently",
"only",
"supports",
"MySQL",
"and",
"Sqlite3"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L35-L46 | train |
theupdateframework/notary | server/storage/sqldb.go | UpdateCurrent | func (db *SQLStorage) UpdateCurrent(gun data.GUN, update MetaUpdate) error {
// ensure we're not inserting an immediately old version - can't use the
// struct, because that only works with non-zero values, and Version
// can be 0.
exists := db.Where("gun = ? and role = ? and version >= ?",
gun.String(), update.Role.String(), update.Version).First(&TUFFile{})
if !exists.RecordNotFound() {
return ErrOldVersion{}
}
// only take out the transaction once we're about to start writing
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
checksum := sha256.Sum256(update.Data)
hexChecksum := hex.EncodeToString(checksum[:])
if err := func() error {
// write new TUFFile entry
if err = translateOldVersionError(tx.Create(&TUFFile{
Gun: gun.String(),
Role: update.Role.String(),
Version: update.Version,
SHA256: hexChecksum,
Data: update.Data,
}).Error); err != nil {
return err
}
// If we're publishing a timestamp, update the changefeed as this is
// technically an new version of the TUF repo
if update.Role == data.CanonicalTimestampRole {
if err := db.writeChangefeed(tx, gun, update.Version, hexChecksum); err != nil {
return err
}
}
return nil
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | go | func (db *SQLStorage) UpdateCurrent(gun data.GUN, update MetaUpdate) error {
// ensure we're not inserting an immediately old version - can't use the
// struct, because that only works with non-zero values, and Version
// can be 0.
exists := db.Where("gun = ? and role = ? and version >= ?",
gun.String(), update.Role.String(), update.Version).First(&TUFFile{})
if !exists.RecordNotFound() {
return ErrOldVersion{}
}
// only take out the transaction once we're about to start writing
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
checksum := sha256.Sum256(update.Data)
hexChecksum := hex.EncodeToString(checksum[:])
if err := func() error {
// write new TUFFile entry
if err = translateOldVersionError(tx.Create(&TUFFile{
Gun: gun.String(),
Role: update.Role.String(),
Version: update.Version,
SHA256: hexChecksum,
Data: update.Data,
}).Error); err != nil {
return err
}
// If we're publishing a timestamp, update the changefeed as this is
// technically an new version of the TUF repo
if update.Role == data.CanonicalTimestampRole {
if err := db.writeChangefeed(tx, gun, update.Version, hexChecksum); err != nil {
return err
}
}
return nil
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"UpdateCurrent",
"(",
"gun",
"data",
".",
"GUN",
",",
"update",
"MetaUpdate",
")",
"error",
"{",
"// ensure we're not inserting an immediately old version - can't use the",
"// struct, because that only works with non-zero values, and Version",
"// can be 0.",
"exists",
":=",
"db",
".",
"Where",
"(",
"\"",
"\"",
",",
"gun",
".",
"String",
"(",
")",
",",
"update",
".",
"Role",
".",
"String",
"(",
")",
",",
"update",
".",
"Version",
")",
".",
"First",
"(",
"&",
"TUFFile",
"{",
"}",
")",
"\n\n",
"if",
"!",
"exists",
".",
"RecordNotFound",
"(",
")",
"{",
"return",
"ErrOldVersion",
"{",
"}",
"\n",
"}",
"\n\n",
"// only take out the transaction once we're about to start writing",
"tx",
",",
"rb",
",",
"err",
":=",
"db",
".",
"getTransaction",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"checksum",
":=",
"sha256",
".",
"Sum256",
"(",
"update",
".",
"Data",
")",
"\n",
"hexChecksum",
":=",
"hex",
".",
"EncodeToString",
"(",
"checksum",
"[",
":",
"]",
")",
"\n\n",
"if",
"err",
":=",
"func",
"(",
")",
"error",
"{",
"// write new TUFFile entry",
"if",
"err",
"=",
"translateOldVersionError",
"(",
"tx",
".",
"Create",
"(",
"&",
"TUFFile",
"{",
"Gun",
":",
"gun",
".",
"String",
"(",
")",
",",
"Role",
":",
"update",
".",
"Role",
".",
"String",
"(",
")",
",",
"Version",
":",
"update",
".",
"Version",
",",
"SHA256",
":",
"hexChecksum",
",",
"Data",
":",
"update",
".",
"Data",
",",
"}",
")",
".",
"Error",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// If we're publishing a timestamp, update the changefeed as this is",
"// technically an new version of the TUF repo",
"if",
"update",
".",
"Role",
"==",
"data",
".",
"CanonicalTimestampRole",
"{",
"if",
"err",
":=",
"db",
".",
"writeChangefeed",
"(",
"tx",
",",
"gun",
",",
"update",
".",
"Version",
",",
"hexChecksum",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"rb",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"tx",
".",
"Commit",
"(",
")",
".",
"Error",
"\n",
"}"
] | // UpdateCurrent updates a single TUF. | [
"UpdateCurrent",
"updates",
"a",
"single",
"TUF",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L49-L93 | train |
theupdateframework/notary | server/storage/sqldb.go | UpdateMany | func (db *SQLStorage) UpdateMany(gun data.GUN, updates []MetaUpdate) error {
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
var (
query *gorm.DB
added = make(map[uint]bool)
)
if err := func() error {
for _, update := range updates {
// This looks like the same logic as UpdateCurrent, but if we just
// called, version ordering in the updates list must be enforced
// (you cannot insert the version 2 before version 1). And we do
// not care about monotonic ordering in the updates.
query = db.Where("gun = ? and role = ? and version >= ?",
gun.String(), update.Role.String(), update.Version).First(&TUFFile{})
if !query.RecordNotFound() {
return ErrOldVersion{}
}
var row TUFFile
checksum := sha256.Sum256(update.Data)
hexChecksum := hex.EncodeToString(checksum[:])
query = tx.Where(map[string]interface{}{
"gun": gun.String(),
"role": update.Role.String(),
"version": update.Version,
}).Attrs("data", update.Data).Attrs("sha256", hexChecksum).FirstOrCreate(&row)
if query.Error != nil {
return translateOldVersionError(query.Error)
}
// it's previously been added, which means it's a duplicate entry
// in the same transaction
if _, ok := added[row.ID]; ok {
return ErrOldVersion{}
}
if update.Role == data.CanonicalTimestampRole {
if err := db.writeChangefeed(tx, gun, update.Version, hexChecksum); err != nil {
return err
}
}
added[row.ID] = true
}
return nil
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | go | func (db *SQLStorage) UpdateMany(gun data.GUN, updates []MetaUpdate) error {
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
var (
query *gorm.DB
added = make(map[uint]bool)
)
if err := func() error {
for _, update := range updates {
// This looks like the same logic as UpdateCurrent, but if we just
// called, version ordering in the updates list must be enforced
// (you cannot insert the version 2 before version 1). And we do
// not care about monotonic ordering in the updates.
query = db.Where("gun = ? and role = ? and version >= ?",
gun.String(), update.Role.String(), update.Version).First(&TUFFile{})
if !query.RecordNotFound() {
return ErrOldVersion{}
}
var row TUFFile
checksum := sha256.Sum256(update.Data)
hexChecksum := hex.EncodeToString(checksum[:])
query = tx.Where(map[string]interface{}{
"gun": gun.String(),
"role": update.Role.String(),
"version": update.Version,
}).Attrs("data", update.Data).Attrs("sha256", hexChecksum).FirstOrCreate(&row)
if query.Error != nil {
return translateOldVersionError(query.Error)
}
// it's previously been added, which means it's a duplicate entry
// in the same transaction
if _, ok := added[row.ID]; ok {
return ErrOldVersion{}
}
if update.Role == data.CanonicalTimestampRole {
if err := db.writeChangefeed(tx, gun, update.Version, hexChecksum); err != nil {
return err
}
}
added[row.ID] = true
}
return nil
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"UpdateMany",
"(",
"gun",
"data",
".",
"GUN",
",",
"updates",
"[",
"]",
"MetaUpdate",
")",
"error",
"{",
"tx",
",",
"rb",
",",
"err",
":=",
"db",
".",
"getTransaction",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"(",
"query",
"*",
"gorm",
".",
"DB",
"\n",
"added",
"=",
"make",
"(",
"map",
"[",
"uint",
"]",
"bool",
")",
"\n",
")",
"\n",
"if",
"err",
":=",
"func",
"(",
")",
"error",
"{",
"for",
"_",
",",
"update",
":=",
"range",
"updates",
"{",
"// This looks like the same logic as UpdateCurrent, but if we just",
"// called, version ordering in the updates list must be enforced",
"// (you cannot insert the version 2 before version 1). And we do",
"// not care about monotonic ordering in the updates.",
"query",
"=",
"db",
".",
"Where",
"(",
"\"",
"\"",
",",
"gun",
".",
"String",
"(",
")",
",",
"update",
".",
"Role",
".",
"String",
"(",
")",
",",
"update",
".",
"Version",
")",
".",
"First",
"(",
"&",
"TUFFile",
"{",
"}",
")",
"\n\n",
"if",
"!",
"query",
".",
"RecordNotFound",
"(",
")",
"{",
"return",
"ErrOldVersion",
"{",
"}",
"\n",
"}",
"\n\n",
"var",
"row",
"TUFFile",
"\n",
"checksum",
":=",
"sha256",
".",
"Sum256",
"(",
"update",
".",
"Data",
")",
"\n",
"hexChecksum",
":=",
"hex",
".",
"EncodeToString",
"(",
"checksum",
"[",
":",
"]",
")",
"\n",
"query",
"=",
"tx",
".",
"Where",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"gun",
".",
"String",
"(",
")",
",",
"\"",
"\"",
":",
"update",
".",
"Role",
".",
"String",
"(",
")",
",",
"\"",
"\"",
":",
"update",
".",
"Version",
",",
"}",
")",
".",
"Attrs",
"(",
"\"",
"\"",
",",
"update",
".",
"Data",
")",
".",
"Attrs",
"(",
"\"",
"\"",
",",
"hexChecksum",
")",
".",
"FirstOrCreate",
"(",
"&",
"row",
")",
"\n\n",
"if",
"query",
".",
"Error",
"!=",
"nil",
"{",
"return",
"translateOldVersionError",
"(",
"query",
".",
"Error",
")",
"\n",
"}",
"\n",
"// it's previously been added, which means it's a duplicate entry",
"// in the same transaction",
"if",
"_",
",",
"ok",
":=",
"added",
"[",
"row",
".",
"ID",
"]",
";",
"ok",
"{",
"return",
"ErrOldVersion",
"{",
"}",
"\n",
"}",
"\n",
"if",
"update",
".",
"Role",
"==",
"data",
".",
"CanonicalTimestampRole",
"{",
"if",
"err",
":=",
"db",
".",
"writeChangefeed",
"(",
"tx",
",",
"gun",
",",
"update",
".",
"Version",
",",
"hexChecksum",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"added",
"[",
"row",
".",
"ID",
"]",
"=",
"true",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"rb",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"tx",
".",
"Commit",
"(",
")",
".",
"Error",
"\n",
"}"
] | // UpdateMany atomically updates many TUF records in a single transaction | [
"UpdateMany",
"atomically",
"updates",
"many",
"TUF",
"records",
"in",
"a",
"single",
"transaction"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L115-L166 | train |
theupdateframework/notary | server/storage/sqldb.go | GetCurrent | func (db *SQLStorage) GetCurrent(gun data.GUN, tufRole data.RoleName) (*time.Time, []byte, error) {
var row TUFFile
q := db.Select("updated_at, data").Where(
&TUFFile{Gun: gun.String(), Role: tufRole.String()}).Order("version desc").Limit(1).First(&row)
if err := isReadErr(q, row); err != nil {
return nil, nil, err
}
return &(row.UpdatedAt), row.Data, nil
} | go | func (db *SQLStorage) GetCurrent(gun data.GUN, tufRole data.RoleName) (*time.Time, []byte, error) {
var row TUFFile
q := db.Select("updated_at, data").Where(
&TUFFile{Gun: gun.String(), Role: tufRole.String()}).Order("version desc").Limit(1).First(&row)
if err := isReadErr(q, row); err != nil {
return nil, nil, err
}
return &(row.UpdatedAt), row.Data, nil
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"GetCurrent",
"(",
"gun",
"data",
".",
"GUN",
",",
"tufRole",
"data",
".",
"RoleName",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"row",
"TUFFile",
"\n",
"q",
":=",
"db",
".",
"Select",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"&",
"TUFFile",
"{",
"Gun",
":",
"gun",
".",
"String",
"(",
")",
",",
"Role",
":",
"tufRole",
".",
"String",
"(",
")",
"}",
")",
".",
"Order",
"(",
"\"",
"\"",
")",
".",
"Limit",
"(",
"1",
")",
".",
"First",
"(",
"&",
"row",
")",
"\n",
"if",
"err",
":=",
"isReadErr",
"(",
"q",
",",
"row",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"(",
"row",
".",
"UpdatedAt",
")",
",",
"row",
".",
"Data",
",",
"nil",
"\n",
"}"
] | // GetCurrent gets a specific TUF record | [
"GetCurrent",
"gets",
"a",
"specific",
"TUF",
"record"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L179-L187 | train |
theupdateframework/notary | server/storage/sqldb.go | GetChecksum | func (db *SQLStorage) GetChecksum(gun data.GUN, tufRole data.RoleName, checksum string) (*time.Time, []byte, error) {
var row TUFFile
q := db.Select("created_at, data").Where(
&TUFFile{
Gun: gun.String(),
Role: tufRole.String(),
SHA256: checksum,
},
).First(&row)
if err := isReadErr(q, row); err != nil {
return nil, nil, err
}
return &(row.CreatedAt), row.Data, nil
} | go | func (db *SQLStorage) GetChecksum(gun data.GUN, tufRole data.RoleName, checksum string) (*time.Time, []byte, error) {
var row TUFFile
q := db.Select("created_at, data").Where(
&TUFFile{
Gun: gun.String(),
Role: tufRole.String(),
SHA256: checksum,
},
).First(&row)
if err := isReadErr(q, row); err != nil {
return nil, nil, err
}
return &(row.CreatedAt), row.Data, nil
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"GetChecksum",
"(",
"gun",
"data",
".",
"GUN",
",",
"tufRole",
"data",
".",
"RoleName",
",",
"checksum",
"string",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"row",
"TUFFile",
"\n",
"q",
":=",
"db",
".",
"Select",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"&",
"TUFFile",
"{",
"Gun",
":",
"gun",
".",
"String",
"(",
")",
",",
"Role",
":",
"tufRole",
".",
"String",
"(",
")",
",",
"SHA256",
":",
"checksum",
",",
"}",
",",
")",
".",
"First",
"(",
"&",
"row",
")",
"\n",
"if",
"err",
":=",
"isReadErr",
"(",
"q",
",",
"row",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"(",
"row",
".",
"CreatedAt",
")",
",",
"row",
".",
"Data",
",",
"nil",
"\n",
"}"
] | // GetChecksum gets a specific TUF record by its hex checksum | [
"GetChecksum",
"gets",
"a",
"specific",
"TUF",
"record",
"by",
"its",
"hex",
"checksum"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L190-L203 | train |
theupdateframework/notary | server/storage/sqldb.go | Delete | func (db *SQLStorage) Delete(gun data.GUN) error {
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
if err := func() error {
res := tx.Unscoped().Where(&TUFFile{Gun: gun.String()}).Delete(TUFFile{})
if err := res.Error; err != nil {
return err
}
// if there weren't actually any records for the GUN, don't write
// a deletion change record.
if res.RowsAffected == 0 {
return nil
}
c := &SQLChange{
GUN: gun.String(),
Category: changeCategoryDeletion,
}
return tx.Create(c).Error
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | go | func (db *SQLStorage) Delete(gun data.GUN) error {
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
if err := func() error {
res := tx.Unscoped().Where(&TUFFile{Gun: gun.String()}).Delete(TUFFile{})
if err := res.Error; err != nil {
return err
}
// if there weren't actually any records for the GUN, don't write
// a deletion change record.
if res.RowsAffected == 0 {
return nil
}
c := &SQLChange{
GUN: gun.String(),
Category: changeCategoryDeletion,
}
return tx.Create(c).Error
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"Delete",
"(",
"gun",
"data",
".",
"GUN",
")",
"error",
"{",
"tx",
",",
"rb",
",",
"err",
":=",
"db",
".",
"getTransaction",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"func",
"(",
")",
"error",
"{",
"res",
":=",
"tx",
".",
"Unscoped",
"(",
")",
".",
"Where",
"(",
"&",
"TUFFile",
"{",
"Gun",
":",
"gun",
".",
"String",
"(",
")",
"}",
")",
".",
"Delete",
"(",
"TUFFile",
"{",
"}",
")",
"\n",
"if",
"err",
":=",
"res",
".",
"Error",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// if there weren't actually any records for the GUN, don't write",
"// a deletion change record.",
"if",
"res",
".",
"RowsAffected",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"c",
":=",
"&",
"SQLChange",
"{",
"GUN",
":",
"gun",
".",
"String",
"(",
")",
",",
"Category",
":",
"changeCategoryDeletion",
",",
"}",
"\n",
"return",
"tx",
".",
"Create",
"(",
"c",
")",
".",
"Error",
"\n",
"}",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"rb",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"tx",
".",
"Commit",
"(",
")",
".",
"Error",
"\n",
"}"
] | // Delete deletes all the records for a specific GUN - we have to do a hard delete using Unscoped
// otherwise we can't insert for that GUN again | [
"Delete",
"deletes",
"all",
"the",
"records",
"for",
"a",
"specific",
"GUN",
"-",
"we",
"have",
"to",
"do",
"a",
"hard",
"delete",
"using",
"Unscoped",
"otherwise",
"we",
"can",
"t",
"insert",
"for",
"that",
"GUN",
"again"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L232-L256 | train |
theupdateframework/notary | server/storage/sqldb.go | CheckHealth | func (db *SQLStorage) CheckHealth() error {
tableOk := db.HasTable(&TUFFile{})
if db.Error != nil {
return db.Error
}
if !tableOk {
return fmt.Errorf(
"Cannot access table: %s", TUFFile{}.TableName())
}
return nil
} | go | func (db *SQLStorage) CheckHealth() error {
tableOk := db.HasTable(&TUFFile{})
if db.Error != nil {
return db.Error
}
if !tableOk {
return fmt.Errorf(
"Cannot access table: %s", TUFFile{}.TableName())
}
return nil
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"CheckHealth",
"(",
")",
"error",
"{",
"tableOk",
":=",
"db",
".",
"HasTable",
"(",
"&",
"TUFFile",
"{",
"}",
")",
"\n",
"if",
"db",
".",
"Error",
"!=",
"nil",
"{",
"return",
"db",
".",
"Error",
"\n",
"}",
"\n",
"if",
"!",
"tableOk",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"TUFFile",
"{",
"}",
".",
"TableName",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CheckHealth asserts that the tuf_files table is present | [
"CheckHealth",
"asserts",
"that",
"the",
"tuf_files",
"table",
"is",
"present"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L259-L269 | train |
theupdateframework/notary | server/storage/sqldb.go | GetChanges | func (db *SQLStorage) GetChanges(changeID string, records int, filterName string) ([]Change, error) {
var (
changes []Change
query = &db.DB
id int64
err error
)
if changeID == "" {
id = 0
} else {
id, err = strconv.ParseInt(changeID, 10, 32)
if err != nil {
return nil, ErrBadQuery{msg: fmt.Sprintf("change ID expected to be integer, provided ID was: %s", changeID)}
}
}
// do what I mean, not what I said, i.e. if I passed a negative number for the ID
// it's assumed I mean "start from latest and go backwards"
reversed := id < 0
if records < 0 {
reversed = true
records = -records
}
if filterName != "" {
query = query.Where("gun = ?", filterName)
}
if reversed {
if id > 0 {
// only set the id check if we're not starting from "latest"
query = query.Where("id < ?", id)
}
query = query.Order("id desc")
} else {
query = query.Where("id > ?", id).Order("id asc")
}
res := query.Limit(records).Find(&changes)
if res.Error != nil {
return nil, res.Error
}
if reversed {
// results are currently newest to oldest, should be oldest to newest
for i, j := 0, len(changes)-1; i < j; i, j = i+1, j-1 {
changes[i], changes[j] = changes[j], changes[i]
}
}
return changes, nil
} | go | func (db *SQLStorage) GetChanges(changeID string, records int, filterName string) ([]Change, error) {
var (
changes []Change
query = &db.DB
id int64
err error
)
if changeID == "" {
id = 0
} else {
id, err = strconv.ParseInt(changeID, 10, 32)
if err != nil {
return nil, ErrBadQuery{msg: fmt.Sprintf("change ID expected to be integer, provided ID was: %s", changeID)}
}
}
// do what I mean, not what I said, i.e. if I passed a negative number for the ID
// it's assumed I mean "start from latest and go backwards"
reversed := id < 0
if records < 0 {
reversed = true
records = -records
}
if filterName != "" {
query = query.Where("gun = ?", filterName)
}
if reversed {
if id > 0 {
// only set the id check if we're not starting from "latest"
query = query.Where("id < ?", id)
}
query = query.Order("id desc")
} else {
query = query.Where("id > ?", id).Order("id asc")
}
res := query.Limit(records).Find(&changes)
if res.Error != nil {
return nil, res.Error
}
if reversed {
// results are currently newest to oldest, should be oldest to newest
for i, j := 0, len(changes)-1; i < j; i, j = i+1, j-1 {
changes[i], changes[j] = changes[j], changes[i]
}
}
return changes, nil
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"GetChanges",
"(",
"changeID",
"string",
",",
"records",
"int",
",",
"filterName",
"string",
")",
"(",
"[",
"]",
"Change",
",",
"error",
")",
"{",
"var",
"(",
"changes",
"[",
"]",
"Change",
"\n",
"query",
"=",
"&",
"db",
".",
"DB",
"\n",
"id",
"int64",
"\n",
"err",
"error",
"\n",
")",
"\n",
"if",
"changeID",
"==",
"\"",
"\"",
"{",
"id",
"=",
"0",
"\n",
"}",
"else",
"{",
"id",
",",
"err",
"=",
"strconv",
".",
"ParseInt",
"(",
"changeID",
",",
"10",
",",
"32",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"ErrBadQuery",
"{",
"msg",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"changeID",
")",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// do what I mean, not what I said, i.e. if I passed a negative number for the ID",
"// it's assumed I mean \"start from latest and go backwards\"",
"reversed",
":=",
"id",
"<",
"0",
"\n",
"if",
"records",
"<",
"0",
"{",
"reversed",
"=",
"true",
"\n",
"records",
"=",
"-",
"records",
"\n",
"}",
"\n\n",
"if",
"filterName",
"!=",
"\"",
"\"",
"{",
"query",
"=",
"query",
".",
"Where",
"(",
"\"",
"\"",
",",
"filterName",
")",
"\n",
"}",
"\n",
"if",
"reversed",
"{",
"if",
"id",
">",
"0",
"{",
"// only set the id check if we're not starting from \"latest\"",
"query",
"=",
"query",
".",
"Where",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}",
"\n",
"query",
"=",
"query",
".",
"Order",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"query",
"=",
"query",
".",
"Where",
"(",
"\"",
"\"",
",",
"id",
")",
".",
"Order",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"res",
":=",
"query",
".",
"Limit",
"(",
"records",
")",
".",
"Find",
"(",
"&",
"changes",
")",
"\n",
"if",
"res",
".",
"Error",
"!=",
"nil",
"{",
"return",
"nil",
",",
"res",
".",
"Error",
"\n",
"}",
"\n\n",
"if",
"reversed",
"{",
"// results are currently newest to oldest, should be oldest to newest",
"for",
"i",
",",
"j",
":=",
"0",
",",
"len",
"(",
"changes",
")",
"-",
"1",
";",
"i",
"<",
"j",
";",
"i",
",",
"j",
"=",
"i",
"+",
"1",
",",
"j",
"-",
"1",
"{",
"changes",
"[",
"i",
"]",
",",
"changes",
"[",
"j",
"]",
"=",
"changes",
"[",
"j",
"]",
",",
"changes",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"changes",
",",
"nil",
"\n",
"}"
] | // GetChanges returns up to pageSize changes starting from changeID. | [
"GetChanges",
"returns",
"up",
"to",
"pageSize",
"changes",
"starting",
"from",
"changeID",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L272-L322 | train |
theupdateframework/notary | cmd/notary-signer/config.go | setUpCryptoservices | func setUpCryptoservices(configuration *viper.Viper, allowedBackends []string, doBootstrap bool) (
signer.CryptoServiceIndex, error) {
backend := configuration.GetString("storage.backend")
if !tufutils.StrSliceContains(allowedBackends, backend) {
return nil, fmt.Errorf("%s is not an allowed backend, must be one of: %s", backend, allowedBackends)
}
var keyService signed.CryptoService
switch backend {
case notary.MemoryBackend:
keyService = cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(
passphrase.ConstantRetriever("memory-db-ignore")))
case notary.RethinkDBBackend:
var sess *gorethink.Session
storeConfig, err := utils.ParseRethinkDBStorage(configuration)
if err != nil {
return nil, err
}
defaultAlias, err := getDefaultAlias(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 := keydbstore.NewRethinkDBKeyStore(storeConfig.DBName, storeConfig.Username, storeConfig.Password, passphraseRetriever, defaultAlias, sess)
health.RegisterPeriodicFunc("DB operational", time.Minute, s.CheckHealth)
if doBootstrap {
keyService = s
} else {
keyService = keydbstore.NewCachedKeyService(s)
}
case notary.MySQLBackend, notary.SQLiteBackend, notary.PostgresBackend:
storeConfig, err := utils.ParseSQLStorage(configuration)
if err != nil {
return nil, err
}
defaultAlias, err := getDefaultAlias(configuration)
if err != nil {
return nil, err
}
dbStore, err := keydbstore.NewSQLKeyDBStore(
passphraseRetriever, defaultAlias, storeConfig.Backend, storeConfig.Source)
if err != nil {
return nil, fmt.Errorf("failed to create a new keydbstore: %v", err)
}
health.RegisterPeriodicFunc(
"DB operational", time.Minute, dbStore.HealthCheck)
keyService = keydbstore.NewCachedKeyService(dbStore)
}
if doBootstrap {
err := bootstrap(keyService)
if err != nil {
logrus.Fatal(err.Error())
}
os.Exit(0)
}
cryptoServices := make(signer.CryptoServiceIndex)
cryptoServices[data.ED25519Key] = keyService
cryptoServices[data.ECDSAKey] = keyService
return cryptoServices, nil
} | go | func setUpCryptoservices(configuration *viper.Viper, allowedBackends []string, doBootstrap bool) (
signer.CryptoServiceIndex, error) {
backend := configuration.GetString("storage.backend")
if !tufutils.StrSliceContains(allowedBackends, backend) {
return nil, fmt.Errorf("%s is not an allowed backend, must be one of: %s", backend, allowedBackends)
}
var keyService signed.CryptoService
switch backend {
case notary.MemoryBackend:
keyService = cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(
passphrase.ConstantRetriever("memory-db-ignore")))
case notary.RethinkDBBackend:
var sess *gorethink.Session
storeConfig, err := utils.ParseRethinkDBStorage(configuration)
if err != nil {
return nil, err
}
defaultAlias, err := getDefaultAlias(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 := keydbstore.NewRethinkDBKeyStore(storeConfig.DBName, storeConfig.Username, storeConfig.Password, passphraseRetriever, defaultAlias, sess)
health.RegisterPeriodicFunc("DB operational", time.Minute, s.CheckHealth)
if doBootstrap {
keyService = s
} else {
keyService = keydbstore.NewCachedKeyService(s)
}
case notary.MySQLBackend, notary.SQLiteBackend, notary.PostgresBackend:
storeConfig, err := utils.ParseSQLStorage(configuration)
if err != nil {
return nil, err
}
defaultAlias, err := getDefaultAlias(configuration)
if err != nil {
return nil, err
}
dbStore, err := keydbstore.NewSQLKeyDBStore(
passphraseRetriever, defaultAlias, storeConfig.Backend, storeConfig.Source)
if err != nil {
return nil, fmt.Errorf("failed to create a new keydbstore: %v", err)
}
health.RegisterPeriodicFunc(
"DB operational", time.Minute, dbStore.HealthCheck)
keyService = keydbstore.NewCachedKeyService(dbStore)
}
if doBootstrap {
err := bootstrap(keyService)
if err != nil {
logrus.Fatal(err.Error())
}
os.Exit(0)
}
cryptoServices := make(signer.CryptoServiceIndex)
cryptoServices[data.ED25519Key] = keyService
cryptoServices[data.ECDSAKey] = keyService
return cryptoServices, nil
} | [
"func",
"setUpCryptoservices",
"(",
"configuration",
"*",
"viper",
".",
"Viper",
",",
"allowedBackends",
"[",
"]",
"string",
",",
"doBootstrap",
"bool",
")",
"(",
"signer",
".",
"CryptoServiceIndex",
",",
"error",
")",
"{",
"backend",
":=",
"configuration",
".",
"GetString",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"!",
"tufutils",
".",
"StrSliceContains",
"(",
"allowedBackends",
",",
"backend",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"backend",
",",
"allowedBackends",
")",
"\n",
"}",
"\n\n",
"var",
"keyService",
"signed",
".",
"CryptoService",
"\n",
"switch",
"backend",
"{",
"case",
"notary",
".",
"MemoryBackend",
":",
"keyService",
"=",
"cryptoservice",
".",
"NewCryptoService",
"(",
"trustmanager",
".",
"NewKeyMemoryStore",
"(",
"passphrase",
".",
"ConstantRetriever",
"(",
"\"",
"\"",
")",
")",
")",
"\n",
"case",
"notary",
".",
"RethinkDBBackend",
":",
"var",
"sess",
"*",
"gorethink",
".",
"Session",
"\n",
"storeConfig",
",",
"err",
":=",
"utils",
".",
"ParseRethinkDBStorage",
"(",
"configuration",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defaultAlias",
",",
"err",
":=",
"getDefaultAlias",
"(",
"configuration",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"tlsOpts",
":=",
"tlsconfig",
".",
"Options",
"{",
"CAFile",
":",
"storeConfig",
".",
"CA",
",",
"CertFile",
":",
"storeConfig",
".",
"Cert",
",",
"KeyFile",
":",
"storeConfig",
".",
"Key",
",",
"ExclusiveRootPools",
":",
"true",
",",
"}",
"\n",
"if",
"doBootstrap",
"{",
"sess",
",",
"err",
"=",
"rethinkdb",
".",
"AdminConnection",
"(",
"tlsOpts",
",",
"storeConfig",
".",
"Source",
")",
"\n",
"}",
"else",
"{",
"sess",
",",
"err",
"=",
"rethinkdb",
".",
"UserConnection",
"(",
"tlsOpts",
",",
"storeConfig",
".",
"Source",
",",
"storeConfig",
".",
"Username",
",",
"storeConfig",
".",
"Password",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"backend",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"s",
":=",
"keydbstore",
".",
"NewRethinkDBKeyStore",
"(",
"storeConfig",
".",
"DBName",
",",
"storeConfig",
".",
"Username",
",",
"storeConfig",
".",
"Password",
",",
"passphraseRetriever",
",",
"defaultAlias",
",",
"sess",
")",
"\n",
"health",
".",
"RegisterPeriodicFunc",
"(",
"\"",
"\"",
",",
"time",
".",
"Minute",
",",
"s",
".",
"CheckHealth",
")",
"\n\n",
"if",
"doBootstrap",
"{",
"keyService",
"=",
"s",
"\n",
"}",
"else",
"{",
"keyService",
"=",
"keydbstore",
".",
"NewCachedKeyService",
"(",
"s",
")",
"\n",
"}",
"\n",
"case",
"notary",
".",
"MySQLBackend",
",",
"notary",
".",
"SQLiteBackend",
",",
"notary",
".",
"PostgresBackend",
":",
"storeConfig",
",",
"err",
":=",
"utils",
".",
"ParseSQLStorage",
"(",
"configuration",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defaultAlias",
",",
"err",
":=",
"getDefaultAlias",
"(",
"configuration",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dbStore",
",",
"err",
":=",
"keydbstore",
".",
"NewSQLKeyDBStore",
"(",
"passphraseRetriever",
",",
"defaultAlias",
",",
"storeConfig",
".",
"Backend",
",",
"storeConfig",
".",
"Source",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"health",
".",
"RegisterPeriodicFunc",
"(",
"\"",
"\"",
",",
"time",
".",
"Minute",
",",
"dbStore",
".",
"HealthCheck",
")",
"\n",
"keyService",
"=",
"keydbstore",
".",
"NewCachedKeyService",
"(",
"dbStore",
")",
"\n",
"}",
"\n\n",
"if",
"doBootstrap",
"{",
"err",
":=",
"bootstrap",
"(",
"keyService",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Fatal",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"os",
".",
"Exit",
"(",
"0",
")",
"\n",
"}",
"\n\n",
"cryptoServices",
":=",
"make",
"(",
"signer",
".",
"CryptoServiceIndex",
")",
"\n",
"cryptoServices",
"[",
"data",
".",
"ED25519Key",
"]",
"=",
"keyService",
"\n",
"cryptoServices",
"[",
"data",
".",
"ECDSAKey",
"]",
"=",
"keyService",
"\n",
"return",
"cryptoServices",
",",
"nil",
"\n",
"}"
] | // Reads the configuration file for storage setup, and sets up the cryptoservice
// mapping | [
"Reads",
"the",
"configuration",
"file",
"for",
"storage",
"setup",
"and",
"sets",
"up",
"the",
"cryptoservice",
"mapping"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-signer/config.go#L103-L180 | train |
theupdateframework/notary | cmd/notary-signer/config.go | setupGRPCServer | func setupGRPCServer(signerConfig signer.Config) (*grpc.Server, net.Listener, error) {
//RPC server setup
kms := &api.KeyManagementServer{
CryptoServices: signerConfig.CryptoServices,
}
ss := &api.SignerServer{
CryptoServices: signerConfig.CryptoServices,
}
hs := ghealth.NewServer()
lis, err := net.Listen("tcp", signerConfig.GRPCAddr)
if err != nil {
return nil, nil, fmt.Errorf("grpc server failed to listen on %s: %v",
signerConfig.GRPCAddr, err)
}
creds := credentials.NewTLS(signerConfig.TLSConfig)
opts := []grpc.ServerOption{grpc.Creds(creds)}
grpcServer := grpc.NewServer(opts...)
pb.RegisterKeyManagementServer(grpcServer, kms)
pb.RegisterSignerServer(grpcServer, ss)
healthpb.RegisterHealthServer(grpcServer, hs)
// Set status for both of the grpc service "KeyManagement" and "Signer", these are
// the only two we have at present, if we add more grpc service in the future,
// we should add a new line for that service here as well.
hs.SetServingStatus(notary.HealthCheckKeyManagement, healthpb.HealthCheckResponse_SERVING)
hs.SetServingStatus(notary.HealthCheckSigner, healthpb.HealthCheckResponse_SERVING)
return grpcServer, lis, nil
} | go | func setupGRPCServer(signerConfig signer.Config) (*grpc.Server, net.Listener, error) {
//RPC server setup
kms := &api.KeyManagementServer{
CryptoServices: signerConfig.CryptoServices,
}
ss := &api.SignerServer{
CryptoServices: signerConfig.CryptoServices,
}
hs := ghealth.NewServer()
lis, err := net.Listen("tcp", signerConfig.GRPCAddr)
if err != nil {
return nil, nil, fmt.Errorf("grpc server failed to listen on %s: %v",
signerConfig.GRPCAddr, err)
}
creds := credentials.NewTLS(signerConfig.TLSConfig)
opts := []grpc.ServerOption{grpc.Creds(creds)}
grpcServer := grpc.NewServer(opts...)
pb.RegisterKeyManagementServer(grpcServer, kms)
pb.RegisterSignerServer(grpcServer, ss)
healthpb.RegisterHealthServer(grpcServer, hs)
// Set status for both of the grpc service "KeyManagement" and "Signer", these are
// the only two we have at present, if we add more grpc service in the future,
// we should add a new line for that service here as well.
hs.SetServingStatus(notary.HealthCheckKeyManagement, healthpb.HealthCheckResponse_SERVING)
hs.SetServingStatus(notary.HealthCheckSigner, healthpb.HealthCheckResponse_SERVING)
return grpcServer, lis, nil
} | [
"func",
"setupGRPCServer",
"(",
"signerConfig",
"signer",
".",
"Config",
")",
"(",
"*",
"grpc",
".",
"Server",
",",
"net",
".",
"Listener",
",",
"error",
")",
"{",
"//RPC server setup",
"kms",
":=",
"&",
"api",
".",
"KeyManagementServer",
"{",
"CryptoServices",
":",
"signerConfig",
".",
"CryptoServices",
",",
"}",
"\n",
"ss",
":=",
"&",
"api",
".",
"SignerServer",
"{",
"CryptoServices",
":",
"signerConfig",
".",
"CryptoServices",
",",
"}",
"\n",
"hs",
":=",
"ghealth",
".",
"NewServer",
"(",
")",
"\n\n",
"lis",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"",
"\"",
",",
"signerConfig",
".",
"GRPCAddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"signerConfig",
".",
"GRPCAddr",
",",
"err",
")",
"\n",
"}",
"\n\n",
"creds",
":=",
"credentials",
".",
"NewTLS",
"(",
"signerConfig",
".",
"TLSConfig",
")",
"\n",
"opts",
":=",
"[",
"]",
"grpc",
".",
"ServerOption",
"{",
"grpc",
".",
"Creds",
"(",
"creds",
")",
"}",
"\n",
"grpcServer",
":=",
"grpc",
".",
"NewServer",
"(",
"opts",
"...",
")",
"\n\n",
"pb",
".",
"RegisterKeyManagementServer",
"(",
"grpcServer",
",",
"kms",
")",
"\n",
"pb",
".",
"RegisterSignerServer",
"(",
"grpcServer",
",",
"ss",
")",
"\n",
"healthpb",
".",
"RegisterHealthServer",
"(",
"grpcServer",
",",
"hs",
")",
"\n\n",
"// Set status for both of the grpc service \"KeyManagement\" and \"Signer\", these are",
"// the only two we have at present, if we add more grpc service in the future,",
"// we should add a new line for that service here as well.",
"hs",
".",
"SetServingStatus",
"(",
"notary",
".",
"HealthCheckKeyManagement",
",",
"healthpb",
".",
"HealthCheckResponse_SERVING",
")",
"\n",
"hs",
".",
"SetServingStatus",
"(",
"notary",
".",
"HealthCheckSigner",
",",
"healthpb",
".",
"HealthCheckResponse_SERVING",
")",
"\n\n",
"return",
"grpcServer",
",",
"lis",
",",
"nil",
"\n",
"}"
] | // set up the GRPC server | [
"set",
"up",
"the",
"GRPC",
"server"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-signer/config.go#L197-L229 | train |
theupdateframework/notary | trustpinning/certs.go | validRootIntCerts | func validRootIntCerts(allIntCerts map[string][]*x509.Certificate) map[string][]*x509.Certificate {
validIntCerts := make(map[string][]*x509.Certificate)
// Go through every leaf cert ID, and build its valid intermediate certificate list
for leafID, intCertList := range allIntCerts {
for _, intCert := range intCertList {
if err := utils.ValidateCertificate(intCert, true); err != nil {
continue
}
validIntCerts[leafID] = append(validIntCerts[leafID], intCert)
}
}
return validIntCerts
} | go | func validRootIntCerts(allIntCerts map[string][]*x509.Certificate) map[string][]*x509.Certificate {
validIntCerts := make(map[string][]*x509.Certificate)
// Go through every leaf cert ID, and build its valid intermediate certificate list
for leafID, intCertList := range allIntCerts {
for _, intCert := range intCertList {
if err := utils.ValidateCertificate(intCert, true); err != nil {
continue
}
validIntCerts[leafID] = append(validIntCerts[leafID], intCert)
}
}
return validIntCerts
} | [
"func",
"validRootIntCerts",
"(",
"allIntCerts",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
"{",
"validIntCerts",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"\n\n",
"// Go through every leaf cert ID, and build its valid intermediate certificate list",
"for",
"leafID",
",",
"intCertList",
":=",
"range",
"allIntCerts",
"{",
"for",
"_",
",",
"intCert",
":=",
"range",
"intCertList",
"{",
"if",
"err",
":=",
"utils",
".",
"ValidateCertificate",
"(",
"intCert",
",",
"true",
")",
";",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"validIntCerts",
"[",
"leafID",
"]",
"=",
"append",
"(",
"validIntCerts",
"[",
"leafID",
"]",
",",
"intCert",
")",
"\n",
"}",
"\n\n",
"}",
"\n",
"return",
"validIntCerts",
"\n",
"}"
] | // validRootIntCerts filters the passed in structure of intermediate certificates to only include non-expired, non-sha1 certificates
// Note that this "validity" alone does not imply any measure of trust. | [
"validRootIntCerts",
"filters",
"the",
"passed",
"in",
"structure",
"of",
"intermediate",
"certificates",
"to",
"only",
"include",
"non",
"-",
"expired",
"non",
"-",
"sha1",
"certificates",
"Note",
"that",
"this",
"validity",
"alone",
"does",
"not",
"imply",
"any",
"measure",
"of",
"trust",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustpinning/certs.go#L227-L241 | train |
theupdateframework/notary | trustpinning/certs.go | parseAllCerts | func parseAllCerts(signedRoot *data.SignedRoot) (map[string]*x509.Certificate, map[string][]*x509.Certificate) {
if signedRoot == nil {
return nil, nil
}
leafCerts := make(map[string]*x509.Certificate)
intCerts := make(map[string][]*x509.Certificate)
// Before we loop through all root keys available, make sure any exist
rootRoles, ok := signedRoot.Signed.Roles[data.CanonicalRootRole]
if !ok {
logrus.Debugf("tried to parse certificates from invalid root signed data")
return nil, nil
}
logrus.Debugf("found the following root keys: %v", rootRoles.KeyIDs)
// Iterate over every keyID for the root role inside of roots.json
for _, keyID := range rootRoles.KeyIDs {
// check that the key exists in the signed root keys map
key, ok := signedRoot.Signed.Keys[keyID]
if !ok {
logrus.Debugf("error while getting data for keyID: %s", keyID)
continue
}
// Decode all the x509 certificates that were bundled with this
// Specific root key
decodedCerts, err := utils.LoadCertBundleFromPEM(key.Public())
if err != nil {
logrus.Debugf("error while parsing root certificate with keyID: %s, %v", keyID, err)
continue
}
// Get all non-CA certificates in the decoded certificates
leafCertList := utils.GetLeafCerts(decodedCerts)
// If we got no leaf certificates or we got more than one, fail
if len(leafCertList) != 1 {
logrus.Debugf("invalid chain due to leaf certificate missing or too many leaf certificates for keyID: %s", keyID)
continue
}
// If we found a leaf certificate, assert that the cert bundle started with a leaf
if decodedCerts[0].IsCA {
logrus.Debugf("invalid chain due to leaf certificate not being first certificate for keyID: %s", keyID)
continue
}
// Get the ID of the leaf certificate
leafCert := leafCertList[0]
// Store the leaf cert in the map
leafCerts[key.ID()] = leafCert
// Get all the remainder certificates marked as a CA to be used as intermediates
intermediateCerts := utils.GetIntermediateCerts(decodedCerts)
intCerts[key.ID()] = intermediateCerts
}
return leafCerts, intCerts
} | go | func parseAllCerts(signedRoot *data.SignedRoot) (map[string]*x509.Certificate, map[string][]*x509.Certificate) {
if signedRoot == nil {
return nil, nil
}
leafCerts := make(map[string]*x509.Certificate)
intCerts := make(map[string][]*x509.Certificate)
// Before we loop through all root keys available, make sure any exist
rootRoles, ok := signedRoot.Signed.Roles[data.CanonicalRootRole]
if !ok {
logrus.Debugf("tried to parse certificates from invalid root signed data")
return nil, nil
}
logrus.Debugf("found the following root keys: %v", rootRoles.KeyIDs)
// Iterate over every keyID for the root role inside of roots.json
for _, keyID := range rootRoles.KeyIDs {
// check that the key exists in the signed root keys map
key, ok := signedRoot.Signed.Keys[keyID]
if !ok {
logrus.Debugf("error while getting data for keyID: %s", keyID)
continue
}
// Decode all the x509 certificates that were bundled with this
// Specific root key
decodedCerts, err := utils.LoadCertBundleFromPEM(key.Public())
if err != nil {
logrus.Debugf("error while parsing root certificate with keyID: %s, %v", keyID, err)
continue
}
// Get all non-CA certificates in the decoded certificates
leafCertList := utils.GetLeafCerts(decodedCerts)
// If we got no leaf certificates or we got more than one, fail
if len(leafCertList) != 1 {
logrus.Debugf("invalid chain due to leaf certificate missing or too many leaf certificates for keyID: %s", keyID)
continue
}
// If we found a leaf certificate, assert that the cert bundle started with a leaf
if decodedCerts[0].IsCA {
logrus.Debugf("invalid chain due to leaf certificate not being first certificate for keyID: %s", keyID)
continue
}
// Get the ID of the leaf certificate
leafCert := leafCertList[0]
// Store the leaf cert in the map
leafCerts[key.ID()] = leafCert
// Get all the remainder certificates marked as a CA to be used as intermediates
intermediateCerts := utils.GetIntermediateCerts(decodedCerts)
intCerts[key.ID()] = intermediateCerts
}
return leafCerts, intCerts
} | [
"func",
"parseAllCerts",
"(",
"signedRoot",
"*",
"data",
".",
"SignedRoot",
")",
"(",
"map",
"[",
"string",
"]",
"*",
"x509",
".",
"Certificate",
",",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"{",
"if",
"signedRoot",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"leafCerts",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"x509",
".",
"Certificate",
")",
"\n",
"intCerts",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"\n\n",
"// Before we loop through all root keys available, make sure any exist",
"rootRoles",
",",
"ok",
":=",
"signedRoot",
".",
"Signed",
".",
"Roles",
"[",
"data",
".",
"CanonicalRootRole",
"]",
"\n",
"if",
"!",
"ok",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"rootRoles",
".",
"KeyIDs",
")",
"\n",
"// Iterate over every keyID for the root role inside of roots.json",
"for",
"_",
",",
"keyID",
":=",
"range",
"rootRoles",
".",
"KeyIDs",
"{",
"// check that the key exists in the signed root keys map",
"key",
",",
"ok",
":=",
"signedRoot",
".",
"Signed",
".",
"Keys",
"[",
"keyID",
"]",
"\n",
"if",
"!",
"ok",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"keyID",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Decode all the x509 certificates that were bundled with this",
"// Specific root key",
"decodedCerts",
",",
"err",
":=",
"utils",
".",
"LoadCertBundleFromPEM",
"(",
"key",
".",
"Public",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"keyID",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Get all non-CA certificates in the decoded certificates",
"leafCertList",
":=",
"utils",
".",
"GetLeafCerts",
"(",
"decodedCerts",
")",
"\n\n",
"// If we got no leaf certificates or we got more than one, fail",
"if",
"len",
"(",
"leafCertList",
")",
"!=",
"1",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"keyID",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"// If we found a leaf certificate, assert that the cert bundle started with a leaf",
"if",
"decodedCerts",
"[",
"0",
"]",
".",
"IsCA",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"keyID",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Get the ID of the leaf certificate",
"leafCert",
":=",
"leafCertList",
"[",
"0",
"]",
"\n\n",
"// Store the leaf cert in the map",
"leafCerts",
"[",
"key",
".",
"ID",
"(",
")",
"]",
"=",
"leafCert",
"\n\n",
"// Get all the remainder certificates marked as a CA to be used as intermediates",
"intermediateCerts",
":=",
"utils",
".",
"GetIntermediateCerts",
"(",
"decodedCerts",
")",
"\n",
"intCerts",
"[",
"key",
".",
"ID",
"(",
")",
"]",
"=",
"intermediateCerts",
"\n",
"}",
"\n\n",
"return",
"leafCerts",
",",
"intCerts",
"\n",
"}"
] | // parseAllCerts returns two maps, one with all of the leafCertificates and one
// with all the intermediate certificates found in signedRoot | [
"parseAllCerts",
"returns",
"two",
"maps",
"one",
"with",
"all",
"of",
"the",
"leafCertificates",
"and",
"one",
"with",
"all",
"the",
"intermediate",
"certificates",
"found",
"in",
"signedRoot"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustpinning/certs.go#L245-L304 | train |
theupdateframework/notary | storage/memorystore.go | NewMemoryStore | func NewMemoryStore(seed map[data.RoleName][]byte) *MemoryStore {
var (
consistent = make(map[string][]byte)
initial = make(map[string][]byte)
)
// add all seed meta to consistent
for name, d := range seed {
checksum := sha256.Sum256(d)
path := utils.ConsistentName(name.String(), checksum[:])
initial[name.String()] = d
consistent[path] = d
}
return &MemoryStore{
data: initial,
consistent: consistent,
}
} | go | func NewMemoryStore(seed map[data.RoleName][]byte) *MemoryStore {
var (
consistent = make(map[string][]byte)
initial = make(map[string][]byte)
)
// add all seed meta to consistent
for name, d := range seed {
checksum := sha256.Sum256(d)
path := utils.ConsistentName(name.String(), checksum[:])
initial[name.String()] = d
consistent[path] = d
}
return &MemoryStore{
data: initial,
consistent: consistent,
}
} | [
"func",
"NewMemoryStore",
"(",
"seed",
"map",
"[",
"data",
".",
"RoleName",
"]",
"[",
"]",
"byte",
")",
"*",
"MemoryStore",
"{",
"var",
"(",
"consistent",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"\n",
"initial",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"\n",
")",
"\n",
"// add all seed meta to consistent",
"for",
"name",
",",
"d",
":=",
"range",
"seed",
"{",
"checksum",
":=",
"sha256",
".",
"Sum256",
"(",
"d",
")",
"\n",
"path",
":=",
"utils",
".",
"ConsistentName",
"(",
"name",
".",
"String",
"(",
")",
",",
"checksum",
"[",
":",
"]",
")",
"\n",
"initial",
"[",
"name",
".",
"String",
"(",
")",
"]",
"=",
"d",
"\n",
"consistent",
"[",
"path",
"]",
"=",
"d",
"\n",
"}",
"\n\n",
"return",
"&",
"MemoryStore",
"{",
"data",
":",
"initial",
",",
"consistent",
":",
"consistent",
",",
"}",
"\n",
"}"
] | // NewMemoryStore returns a MetadataStore that operates entirely in memory.
// Very useful for testing | [
"NewMemoryStore",
"returns",
"a",
"MetadataStore",
"that",
"operates",
"entirely",
"in",
"memory",
".",
"Very",
"useful",
"for",
"testing"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L15-L32 | train |
theupdateframework/notary | storage/memorystore.go | GetSized | func (m MemoryStore) GetSized(name string, size int64) ([]byte, error) {
d, ok := m.data[name]
if ok {
if size == NoSizeLimit {
size = notary.MaxDownloadSize
}
if int64(len(d)) < size {
return d, nil
}
return d[:size], nil
}
d, ok = m.consistent[name]
if ok {
if int64(len(d)) < size {
return d, nil
}
return d[:size], nil
}
return nil, ErrMetaNotFound{Resource: name}
} | go | func (m MemoryStore) GetSized(name string, size int64) ([]byte, error) {
d, ok := m.data[name]
if ok {
if size == NoSizeLimit {
size = notary.MaxDownloadSize
}
if int64(len(d)) < size {
return d, nil
}
return d[:size], nil
}
d, ok = m.consistent[name]
if ok {
if int64(len(d)) < size {
return d, nil
}
return d[:size], nil
}
return nil, ErrMetaNotFound{Resource: name}
} | [
"func",
"(",
"m",
"MemoryStore",
")",
"GetSized",
"(",
"name",
"string",
",",
"size",
"int64",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"d",
",",
"ok",
":=",
"m",
".",
"data",
"[",
"name",
"]",
"\n",
"if",
"ok",
"{",
"if",
"size",
"==",
"NoSizeLimit",
"{",
"size",
"=",
"notary",
".",
"MaxDownloadSize",
"\n",
"}",
"\n",
"if",
"int64",
"(",
"len",
"(",
"d",
")",
")",
"<",
"size",
"{",
"return",
"d",
",",
"nil",
"\n",
"}",
"\n",
"return",
"d",
"[",
":",
"size",
"]",
",",
"nil",
"\n",
"}",
"\n",
"d",
",",
"ok",
"=",
"m",
".",
"consistent",
"[",
"name",
"]",
"\n",
"if",
"ok",
"{",
"if",
"int64",
"(",
"len",
"(",
"d",
")",
")",
"<",
"size",
"{",
"return",
"d",
",",
"nil",
"\n",
"}",
"\n",
"return",
"d",
"[",
":",
"size",
"]",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"ErrMetaNotFound",
"{",
"Resource",
":",
"name",
"}",
"\n",
"}"
] | // GetSized returns up to size bytes of data references by name.
// If size is "NoSizeLimit", this corresponds to "infinite," but we cut off at a
// predefined threshold "notary.MaxDownloadSize", as we will always know the
// size for everything but a timestamp and sometimes a root,
// neither of which should be exceptionally large | [
"GetSized",
"returns",
"up",
"to",
"size",
"bytes",
"of",
"data",
"references",
"by",
"name",
".",
"If",
"size",
"is",
"NoSizeLimit",
"this",
"corresponds",
"to",
"infinite",
"but",
"we",
"cut",
"off",
"at",
"a",
"predefined",
"threshold",
"notary",
".",
"MaxDownloadSize",
"as",
"we",
"will",
"always",
"know",
"the",
"size",
"for",
"everything",
"but",
"a",
"timestamp",
"and",
"sometimes",
"a",
"root",
"neither",
"of",
"which",
"should",
"be",
"exceptionally",
"large"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L46-L65 | train |
theupdateframework/notary | storage/memorystore.go | Get | func (m MemoryStore) Get(name string) ([]byte, error) {
if d, ok := m.data[name]; ok {
return d, nil
}
if d, ok := m.consistent[name]; ok {
return d, nil
}
return nil, ErrMetaNotFound{Resource: name}
} | go | func (m MemoryStore) Get(name string) ([]byte, error) {
if d, ok := m.data[name]; ok {
return d, nil
}
if d, ok := m.consistent[name]; ok {
return d, nil
}
return nil, ErrMetaNotFound{Resource: name}
} | [
"func",
"(",
"m",
"MemoryStore",
")",
"Get",
"(",
"name",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"d",
",",
"ok",
":=",
"m",
".",
"data",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"d",
",",
"nil",
"\n",
"}",
"\n",
"if",
"d",
",",
"ok",
":=",
"m",
".",
"consistent",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"d",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"ErrMetaNotFound",
"{",
"Resource",
":",
"name",
"}",
"\n",
"}"
] | // Get returns the data associated with name | [
"Get",
"returns",
"the",
"data",
"associated",
"with",
"name"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L68-L76 | train |
theupdateframework/notary | storage/memorystore.go | Set | func (m *MemoryStore) Set(name string, meta []byte) error {
m.data[name] = meta
parsedMeta := &data.SignedMeta{}
err := json.Unmarshal(meta, parsedMeta)
if err == nil {
// no parse error means this is metadata and not a key, so store by version
version := parsedMeta.Signed.Version
versionedName := fmt.Sprintf("%d.%s", version, name)
m.data[versionedName] = meta
}
checksum := sha256.Sum256(meta)
path := utils.ConsistentName(name, checksum[:])
m.consistent[path] = meta
return nil
} | go | func (m *MemoryStore) Set(name string, meta []byte) error {
m.data[name] = meta
parsedMeta := &data.SignedMeta{}
err := json.Unmarshal(meta, parsedMeta)
if err == nil {
// no parse error means this is metadata and not a key, so store by version
version := parsedMeta.Signed.Version
versionedName := fmt.Sprintf("%d.%s", version, name)
m.data[versionedName] = meta
}
checksum := sha256.Sum256(meta)
path := utils.ConsistentName(name, checksum[:])
m.consistent[path] = meta
return nil
} | [
"func",
"(",
"m",
"*",
"MemoryStore",
")",
"Set",
"(",
"name",
"string",
",",
"meta",
"[",
"]",
"byte",
")",
"error",
"{",
"m",
".",
"data",
"[",
"name",
"]",
"=",
"meta",
"\n\n",
"parsedMeta",
":=",
"&",
"data",
".",
"SignedMeta",
"{",
"}",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"meta",
",",
"parsedMeta",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"// no parse error means this is metadata and not a key, so store by version",
"version",
":=",
"parsedMeta",
".",
"Signed",
".",
"Version",
"\n",
"versionedName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"version",
",",
"name",
")",
"\n",
"m",
".",
"data",
"[",
"versionedName",
"]",
"=",
"meta",
"\n",
"}",
"\n\n",
"checksum",
":=",
"sha256",
".",
"Sum256",
"(",
"meta",
")",
"\n",
"path",
":=",
"utils",
".",
"ConsistentName",
"(",
"name",
",",
"checksum",
"[",
":",
"]",
")",
"\n",
"m",
".",
"consistent",
"[",
"path",
"]",
"=",
"meta",
"\n",
"return",
"nil",
"\n",
"}"
] | // Set sets the metadata value for the given name | [
"Set",
"sets",
"the",
"metadata",
"value",
"for",
"the",
"given",
"name"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L79-L95 | train |
theupdateframework/notary | storage/memorystore.go | SetMulti | func (m *MemoryStore) SetMulti(metas map[string][]byte) error {
for role, blob := range metas {
m.Set(role, blob)
}
return nil
} | go | func (m *MemoryStore) SetMulti(metas map[string][]byte) error {
for role, blob := range metas {
m.Set(role, blob)
}
return nil
} | [
"func",
"(",
"m",
"*",
"MemoryStore",
")",
"SetMulti",
"(",
"metas",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"error",
"{",
"for",
"role",
",",
"blob",
":=",
"range",
"metas",
"{",
"m",
".",
"Set",
"(",
"role",
",",
"blob",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetMulti sets multiple pieces of metadata for multiple names
// in a single operation. | [
"SetMulti",
"sets",
"multiple",
"pieces",
"of",
"metadata",
"for",
"multiple",
"names",
"in",
"a",
"single",
"operation",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L99-L104 | train |
theupdateframework/notary | storage/memorystore.go | ListFiles | func (m *MemoryStore) ListFiles() []string {
names := make([]string, 0, len(m.data))
for n := range m.data {
names = append(names, n)
}
return names
} | go | func (m *MemoryStore) ListFiles() []string {
names := make([]string, 0, len(m.data))
for n := range m.data {
names = append(names, n)
}
return names
} | [
"func",
"(",
"m",
"*",
"MemoryStore",
")",
"ListFiles",
"(",
")",
"[",
"]",
"string",
"{",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"m",
".",
"data",
")",
")",
"\n",
"for",
"n",
":=",
"range",
"m",
".",
"data",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"n",
")",
"\n",
"}",
"\n",
"return",
"names",
"\n",
"}"
] | // ListFiles returns a list of all files. The names returned should be
// usable with Get directly, with no modification. | [
"ListFiles",
"returns",
"a",
"list",
"of",
"all",
"files",
".",
"The",
"names",
"returned",
"should",
"be",
"usable",
"with",
"Get",
"directly",
"with",
"no",
"modification",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L131-L137 | train |
theupdateframework/notary | server/storage/tuf_store.go | NewTUFMetaStorage | func NewTUFMetaStorage(m MetaStore) *TUFMetaStorage {
return &TUFMetaStorage{
MetaStore: m,
cachedMeta: make(map[string]*storedMeta),
}
} | go | func NewTUFMetaStorage(m MetaStore) *TUFMetaStorage {
return &TUFMetaStorage{
MetaStore: m,
cachedMeta: make(map[string]*storedMeta),
}
} | [
"func",
"NewTUFMetaStorage",
"(",
"m",
"MetaStore",
")",
"*",
"TUFMetaStorage",
"{",
"return",
"&",
"TUFMetaStorage",
"{",
"MetaStore",
":",
"m",
",",
"cachedMeta",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"storedMeta",
")",
",",
"}",
"\n",
"}"
] | // NewTUFMetaStorage instantiates a TUFMetaStorage instance | [
"NewTUFMetaStorage",
"instantiates",
"a",
"TUFMetaStorage",
"instance"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/tuf_store.go#L23-L28 | train |
theupdateframework/notary | server/storage/tuf_store.go | GetCurrent | func (tms TUFMetaStorage) GetCurrent(gun data.GUN, tufRole data.RoleName) (*time.Time, []byte, error) {
timestampTime, timestampJSON, err := tms.MetaStore.GetCurrent(gun, data.CanonicalTimestampRole)
if err != nil {
return nil, nil, err
}
// If we wanted data for the timestamp role, we're done here
if tufRole == data.CanonicalTimestampRole {
return timestampTime, timestampJSON, nil
}
// If we want to lookup another role, walk to it via current timestamp --> snapshot by checksum --> desired role
timestampMeta := &data.SignedTimestamp{}
if err := json.Unmarshal(timestampJSON, timestampMeta); err != nil {
return nil, nil, fmt.Errorf("could not parse current timestamp")
}
snapshotChecksums, err := timestampMeta.GetSnapshot()
if err != nil || snapshotChecksums == nil {
return nil, nil, fmt.Errorf("could not retrieve latest snapshot checksum")
}
snapshotSHA256Bytes, ok := snapshotChecksums.Hashes[notary.SHA256]
if !ok {
return nil, nil, fmt.Errorf("could not retrieve latest snapshot sha256")
}
snapshotSHA256Hex := hex.EncodeToString(snapshotSHA256Bytes[:])
// Check the cache if we have our snapshot data
var snapshotTime *time.Time
var snapshotJSON []byte
if cachedSnapshotData, ok := tms.cachedMeta[snapshotSHA256Hex]; ok {
snapshotTime = cachedSnapshotData.createupdate
snapshotJSON = cachedSnapshotData.data
} else {
// Get the snapshot from the underlying store by checksum if it isn't cached yet
snapshotTime, snapshotJSON, err = tms.GetChecksum(gun, data.CanonicalSnapshotRole, snapshotSHA256Hex)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[snapshotSHA256Hex] = &storedMeta{data: snapshotJSON, createupdate: snapshotTime}
}
// If we wanted data for the snapshot role, we're done here
if tufRole == data.CanonicalSnapshotRole {
return snapshotTime, snapshotJSON, nil
}
// If it's a different role, we should have the checksum in snapshot metadata, and we can use it to GetChecksum()
snapshotMeta := &data.SignedSnapshot{}
if err := json.Unmarshal(snapshotJSON, snapshotMeta); err != nil {
return nil, nil, fmt.Errorf("could not parse current snapshot")
}
roleMeta, err := snapshotMeta.GetMeta(tufRole)
if err != nil {
return nil, nil, err
}
roleSHA256Bytes, ok := roleMeta.Hashes[notary.SHA256]
if !ok {
return nil, nil, fmt.Errorf("could not retrieve latest %s sha256", tufRole)
}
roleSHA256Hex := hex.EncodeToString(roleSHA256Bytes[:])
// check if we can retrieve this data from cache
if cachedRoleData, ok := tms.cachedMeta[roleSHA256Hex]; ok {
return cachedRoleData.createupdate, cachedRoleData.data, nil
}
roleTime, roleJSON, err := tms.MetaStore.GetChecksum(gun, tufRole, roleSHA256Hex)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[roleSHA256Hex] = &storedMeta{data: roleJSON, createupdate: roleTime}
return roleTime, roleJSON, nil
} | go | func (tms TUFMetaStorage) GetCurrent(gun data.GUN, tufRole data.RoleName) (*time.Time, []byte, error) {
timestampTime, timestampJSON, err := tms.MetaStore.GetCurrent(gun, data.CanonicalTimestampRole)
if err != nil {
return nil, nil, err
}
// If we wanted data for the timestamp role, we're done here
if tufRole == data.CanonicalTimestampRole {
return timestampTime, timestampJSON, nil
}
// If we want to lookup another role, walk to it via current timestamp --> snapshot by checksum --> desired role
timestampMeta := &data.SignedTimestamp{}
if err := json.Unmarshal(timestampJSON, timestampMeta); err != nil {
return nil, nil, fmt.Errorf("could not parse current timestamp")
}
snapshotChecksums, err := timestampMeta.GetSnapshot()
if err != nil || snapshotChecksums == nil {
return nil, nil, fmt.Errorf("could not retrieve latest snapshot checksum")
}
snapshotSHA256Bytes, ok := snapshotChecksums.Hashes[notary.SHA256]
if !ok {
return nil, nil, fmt.Errorf("could not retrieve latest snapshot sha256")
}
snapshotSHA256Hex := hex.EncodeToString(snapshotSHA256Bytes[:])
// Check the cache if we have our snapshot data
var snapshotTime *time.Time
var snapshotJSON []byte
if cachedSnapshotData, ok := tms.cachedMeta[snapshotSHA256Hex]; ok {
snapshotTime = cachedSnapshotData.createupdate
snapshotJSON = cachedSnapshotData.data
} else {
// Get the snapshot from the underlying store by checksum if it isn't cached yet
snapshotTime, snapshotJSON, err = tms.GetChecksum(gun, data.CanonicalSnapshotRole, snapshotSHA256Hex)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[snapshotSHA256Hex] = &storedMeta{data: snapshotJSON, createupdate: snapshotTime}
}
// If we wanted data for the snapshot role, we're done here
if tufRole == data.CanonicalSnapshotRole {
return snapshotTime, snapshotJSON, nil
}
// If it's a different role, we should have the checksum in snapshot metadata, and we can use it to GetChecksum()
snapshotMeta := &data.SignedSnapshot{}
if err := json.Unmarshal(snapshotJSON, snapshotMeta); err != nil {
return nil, nil, fmt.Errorf("could not parse current snapshot")
}
roleMeta, err := snapshotMeta.GetMeta(tufRole)
if err != nil {
return nil, nil, err
}
roleSHA256Bytes, ok := roleMeta.Hashes[notary.SHA256]
if !ok {
return nil, nil, fmt.Errorf("could not retrieve latest %s sha256", tufRole)
}
roleSHA256Hex := hex.EncodeToString(roleSHA256Bytes[:])
// check if we can retrieve this data from cache
if cachedRoleData, ok := tms.cachedMeta[roleSHA256Hex]; ok {
return cachedRoleData.createupdate, cachedRoleData.data, nil
}
roleTime, roleJSON, err := tms.MetaStore.GetChecksum(gun, tufRole, roleSHA256Hex)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[roleSHA256Hex] = &storedMeta{data: roleJSON, createupdate: roleTime}
return roleTime, roleJSON, nil
} | [
"func",
"(",
"tms",
"TUFMetaStorage",
")",
"GetCurrent",
"(",
"gun",
"data",
".",
"GUN",
",",
"tufRole",
"data",
".",
"RoleName",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"timestampTime",
",",
"timestampJSON",
",",
"err",
":=",
"tms",
".",
"MetaStore",
".",
"GetCurrent",
"(",
"gun",
",",
"data",
".",
"CanonicalTimestampRole",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// If we wanted data for the timestamp role, we're done here",
"if",
"tufRole",
"==",
"data",
".",
"CanonicalTimestampRole",
"{",
"return",
"timestampTime",
",",
"timestampJSON",
",",
"nil",
"\n",
"}",
"\n\n",
"// If we want to lookup another role, walk to it via current timestamp --> snapshot by checksum --> desired role",
"timestampMeta",
":=",
"&",
"data",
".",
"SignedTimestamp",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"timestampJSON",
",",
"timestampMeta",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"snapshotChecksums",
",",
"err",
":=",
"timestampMeta",
".",
"GetSnapshot",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"snapshotChecksums",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"snapshotSHA256Bytes",
",",
"ok",
":=",
"snapshotChecksums",
".",
"Hashes",
"[",
"notary",
".",
"SHA256",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"snapshotSHA256Hex",
":=",
"hex",
".",
"EncodeToString",
"(",
"snapshotSHA256Bytes",
"[",
":",
"]",
")",
"\n\n",
"// Check the cache if we have our snapshot data",
"var",
"snapshotTime",
"*",
"time",
".",
"Time",
"\n",
"var",
"snapshotJSON",
"[",
"]",
"byte",
"\n",
"if",
"cachedSnapshotData",
",",
"ok",
":=",
"tms",
".",
"cachedMeta",
"[",
"snapshotSHA256Hex",
"]",
";",
"ok",
"{",
"snapshotTime",
"=",
"cachedSnapshotData",
".",
"createupdate",
"\n",
"snapshotJSON",
"=",
"cachedSnapshotData",
".",
"data",
"\n",
"}",
"else",
"{",
"// Get the snapshot from the underlying store by checksum if it isn't cached yet",
"snapshotTime",
",",
"snapshotJSON",
",",
"err",
"=",
"tms",
".",
"GetChecksum",
"(",
"gun",
",",
"data",
".",
"CanonicalSnapshotRole",
",",
"snapshotSHA256Hex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// cache for subsequent lookups",
"tms",
".",
"cachedMeta",
"[",
"snapshotSHA256Hex",
"]",
"=",
"&",
"storedMeta",
"{",
"data",
":",
"snapshotJSON",
",",
"createupdate",
":",
"snapshotTime",
"}",
"\n",
"}",
"\n",
"// If we wanted data for the snapshot role, we're done here",
"if",
"tufRole",
"==",
"data",
".",
"CanonicalSnapshotRole",
"{",
"return",
"snapshotTime",
",",
"snapshotJSON",
",",
"nil",
"\n",
"}",
"\n\n",
"// If it's a different role, we should have the checksum in snapshot metadata, and we can use it to GetChecksum()",
"snapshotMeta",
":=",
"&",
"data",
".",
"SignedSnapshot",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"snapshotJSON",
",",
"snapshotMeta",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"roleMeta",
",",
"err",
":=",
"snapshotMeta",
".",
"GetMeta",
"(",
"tufRole",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"roleSHA256Bytes",
",",
"ok",
":=",
"roleMeta",
".",
"Hashes",
"[",
"notary",
".",
"SHA256",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tufRole",
")",
"\n",
"}",
"\n",
"roleSHA256Hex",
":=",
"hex",
".",
"EncodeToString",
"(",
"roleSHA256Bytes",
"[",
":",
"]",
")",
"\n",
"// check if we can retrieve this data from cache",
"if",
"cachedRoleData",
",",
"ok",
":=",
"tms",
".",
"cachedMeta",
"[",
"roleSHA256Hex",
"]",
";",
"ok",
"{",
"return",
"cachedRoleData",
".",
"createupdate",
",",
"cachedRoleData",
".",
"data",
",",
"nil",
"\n",
"}",
"\n\n",
"roleTime",
",",
"roleJSON",
",",
"err",
":=",
"tms",
".",
"MetaStore",
".",
"GetChecksum",
"(",
"gun",
",",
"tufRole",
",",
"roleSHA256Hex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// cache for subsequent lookups",
"tms",
".",
"cachedMeta",
"[",
"roleSHA256Hex",
"]",
"=",
"&",
"storedMeta",
"{",
"data",
":",
"roleJSON",
",",
"createupdate",
":",
"roleTime",
"}",
"\n",
"return",
"roleTime",
",",
"roleJSON",
",",
"nil",
"\n",
"}"
] | // GetCurrent gets a specific TUF record, by walking from the current Timestamp to other metadata by checksum | [
"GetCurrent",
"gets",
"a",
"specific",
"TUF",
"record",
"by",
"walking",
"from",
"the",
"current",
"Timestamp",
"to",
"other",
"metadata",
"by",
"checksum"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/tuf_store.go#L36-L107 | train |
theupdateframework/notary | server/storage/tuf_store.go | GetChecksum | func (tms TUFMetaStorage) GetChecksum(gun data.GUN, tufRole data.RoleName, checksum string) (*time.Time, []byte, error) {
if cachedRoleData, ok := tms.cachedMeta[checksum]; ok {
return cachedRoleData.createupdate, cachedRoleData.data, nil
}
roleTime, roleJSON, err := tms.MetaStore.GetChecksum(gun, tufRole, checksum)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[checksum] = &storedMeta{data: roleJSON, createupdate: roleTime}
return roleTime, roleJSON, nil
} | go | func (tms TUFMetaStorage) GetChecksum(gun data.GUN, tufRole data.RoleName, checksum string) (*time.Time, []byte, error) {
if cachedRoleData, ok := tms.cachedMeta[checksum]; ok {
return cachedRoleData.createupdate, cachedRoleData.data, nil
}
roleTime, roleJSON, err := tms.MetaStore.GetChecksum(gun, tufRole, checksum)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[checksum] = &storedMeta{data: roleJSON, createupdate: roleTime}
return roleTime, roleJSON, nil
} | [
"func",
"(",
"tms",
"TUFMetaStorage",
")",
"GetChecksum",
"(",
"gun",
"data",
".",
"GUN",
",",
"tufRole",
"data",
".",
"RoleName",
",",
"checksum",
"string",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"cachedRoleData",
",",
"ok",
":=",
"tms",
".",
"cachedMeta",
"[",
"checksum",
"]",
";",
"ok",
"{",
"return",
"cachedRoleData",
".",
"createupdate",
",",
"cachedRoleData",
".",
"data",
",",
"nil",
"\n",
"}",
"\n",
"roleTime",
",",
"roleJSON",
",",
"err",
":=",
"tms",
".",
"MetaStore",
".",
"GetChecksum",
"(",
"gun",
",",
"tufRole",
",",
"checksum",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// cache for subsequent lookups",
"tms",
".",
"cachedMeta",
"[",
"checksum",
"]",
"=",
"&",
"storedMeta",
"{",
"data",
":",
"roleJSON",
",",
"createupdate",
":",
"roleTime",
"}",
"\n",
"return",
"roleTime",
",",
"roleJSON",
",",
"nil",
"\n",
"}"
] | // GetChecksum gets a specific TUF record by checksum, also checking the internal cache | [
"GetChecksum",
"gets",
"a",
"specific",
"TUF",
"record",
"by",
"checksum",
"also",
"checking",
"the",
"internal",
"cache"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/tuf_store.go#L110-L121 | train |
theupdateframework/notary | server/storage/tuf_store.go | Bootstrap | func (tms TUFMetaStorage) Bootstrap() error {
if s, ok := tms.MetaStore.(storage.Bootstrapper); ok {
return s.Bootstrap()
}
return fmt.Errorf("store does not support bootstrapping")
} | go | func (tms TUFMetaStorage) Bootstrap() error {
if s, ok := tms.MetaStore.(storage.Bootstrapper); ok {
return s.Bootstrap()
}
return fmt.Errorf("store does not support bootstrapping")
} | [
"func",
"(",
"tms",
"TUFMetaStorage",
")",
"Bootstrap",
"(",
")",
"error",
"{",
"if",
"s",
",",
"ok",
":=",
"tms",
".",
"MetaStore",
".",
"(",
"storage",
".",
"Bootstrapper",
")",
";",
"ok",
"{",
"return",
"s",
".",
"Bootstrap",
"(",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Bootstrap the store with tables if possible | [
"Bootstrap",
"the",
"store",
"with",
"tables",
"if",
"possible"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/tuf_store.go#L124-L129 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.