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
|
client/changelist/changelist.go
|
Add
|
func (cl *memChangelist) Add(c Change) error {
cl.changes = append(cl.changes, c)
return nil
}
|
go
|
func (cl *memChangelist) Add(c Change) error {
cl.changes = append(cl.changes, c)
return nil
}
|
[
"func",
"(",
"cl",
"*",
"memChangelist",
")",
"Add",
"(",
"c",
"Change",
")",
"error",
"{",
"cl",
".",
"changes",
"=",
"append",
"(",
"cl",
".",
"changes",
",",
"c",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Add adds a change to the in-memory change list
|
[
"Add",
"adds",
"a",
"change",
"to",
"the",
"in",
"-",
"memory",
"change",
"list"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/changelist.go#L19-L22
|
train
|
theupdateframework/notary
|
client/changelist/changelist.go
|
Clear
|
func (cl *memChangelist) Clear(archive string) error {
// appending to a nil list initializes it.
cl.changes = nil
return nil
}
|
go
|
func (cl *memChangelist) Clear(archive string) error {
// appending to a nil list initializes it.
cl.changes = nil
return nil
}
|
[
"func",
"(",
"cl",
"*",
"memChangelist",
")",
"Clear",
"(",
"archive",
"string",
")",
"error",
"{",
"// appending to a nil list initializes it.",
"cl",
".",
"changes",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Clear empties the changelist file.
|
[
"Clear",
"empties",
"the",
"changelist",
"file",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/changelist.go#L48-L52
|
train
|
theupdateframework/notary
|
client/changelist/changelist.go
|
Next
|
func (m *MemChangeListIterator) Next() (item Change, err error) {
if m.index >= len(m.collection) {
return nil, IteratorBoundsError(m.index)
}
item = m.collection[m.index]
m.index++
return item, err
}
|
go
|
func (m *MemChangeListIterator) Next() (item Change, err error) {
if m.index >= len(m.collection) {
return nil, IteratorBoundsError(m.index)
}
item = m.collection[m.index]
m.index++
return item, err
}
|
[
"func",
"(",
"m",
"*",
"MemChangeListIterator",
")",
"Next",
"(",
")",
"(",
"item",
"Change",
",",
"err",
"error",
")",
"{",
"if",
"m",
".",
"index",
">=",
"len",
"(",
"m",
".",
"collection",
")",
"{",
"return",
"nil",
",",
"IteratorBoundsError",
"(",
"m",
".",
"index",
")",
"\n",
"}",
"\n",
"item",
"=",
"m",
".",
"collection",
"[",
"m",
".",
"index",
"]",
"\n",
"m",
".",
"index",
"++",
"\n",
"return",
"item",
",",
"err",
"\n",
"}"
] |
// Next returns the next Change
|
[
"Next",
"returns",
"the",
"next",
"Change"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/changelist.go#L70-L77
|
train
|
theupdateframework/notary
|
client/changelist/file_changelist.go
|
NewFileChangelist
|
func NewFileChangelist(dir string) (*FileChangelist, error) {
logrus.Debug("Making dir path: ", dir)
err := os.MkdirAll(dir, 0700)
if err != nil {
return nil, err
}
return &FileChangelist{dir: dir}, nil
}
|
go
|
func NewFileChangelist(dir string) (*FileChangelist, error) {
logrus.Debug("Making dir path: ", dir)
err := os.MkdirAll(dir, 0700)
if err != nil {
return nil, err
}
return &FileChangelist{dir: dir}, nil
}
|
[
"func",
"NewFileChangelist",
"(",
"dir",
"string",
")",
"(",
"*",
"FileChangelist",
",",
"error",
")",
"{",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
",",
"dir",
")",
"\n",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"dir",
",",
"0700",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"FileChangelist",
"{",
"dir",
":",
"dir",
"}",
",",
"nil",
"\n",
"}"
] |
// NewFileChangelist is a convenience method for returning FileChangeLists
|
[
"NewFileChangelist",
"is",
"a",
"convenience",
"method",
"for",
"returning",
"FileChangeLists"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L22-L29
|
train
|
theupdateframework/notary
|
client/changelist/file_changelist.go
|
getFileNames
|
func getFileNames(dirName string) ([]os.FileInfo, error) {
var dirListing, fileInfos []os.FileInfo
dir, err := os.Open(dirName)
if err != nil {
return fileInfos, err
}
defer dir.Close()
dirListing, err = dir.Readdir(0)
if err != nil {
return fileInfos, err
}
for _, f := range dirListing {
if f.IsDir() {
continue
}
fileInfos = append(fileInfos, f)
}
sort.Sort(fileChanges(fileInfos))
return fileInfos, nil
}
|
go
|
func getFileNames(dirName string) ([]os.FileInfo, error) {
var dirListing, fileInfos []os.FileInfo
dir, err := os.Open(dirName)
if err != nil {
return fileInfos, err
}
defer dir.Close()
dirListing, err = dir.Readdir(0)
if err != nil {
return fileInfos, err
}
for _, f := range dirListing {
if f.IsDir() {
continue
}
fileInfos = append(fileInfos, f)
}
sort.Sort(fileChanges(fileInfos))
return fileInfos, nil
}
|
[
"func",
"getFileNames",
"(",
"dirName",
"string",
")",
"(",
"[",
"]",
"os",
".",
"FileInfo",
",",
"error",
")",
"{",
"var",
"dirListing",
",",
"fileInfos",
"[",
"]",
"os",
".",
"FileInfo",
"\n",
"dir",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"dirName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fileInfos",
",",
"err",
"\n",
"}",
"\n",
"defer",
"dir",
".",
"Close",
"(",
")",
"\n",
"dirListing",
",",
"err",
"=",
"dir",
".",
"Readdir",
"(",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fileInfos",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"dirListing",
"{",
"if",
"f",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"fileInfos",
"=",
"append",
"(",
"fileInfos",
",",
"f",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"fileChanges",
"(",
"fileInfos",
")",
")",
"\n",
"return",
"fileInfos",
",",
"nil",
"\n",
"}"
] |
// getFileNames reads directory, filtering out child directories
|
[
"getFileNames",
"reads",
"directory",
"filtering",
"out",
"child",
"directories"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L32-L51
|
train
|
theupdateframework/notary
|
client/changelist/file_changelist.go
|
unmarshalFile
|
func unmarshalFile(dirname string, f os.FileInfo) (*TUFChange, error) {
c := &TUFChange{}
raw, err := ioutil.ReadFile(filepath.Join(dirname, f.Name()))
if err != nil {
return c, err
}
err = json.Unmarshal(raw, c)
if err != nil {
return c, err
}
return c, nil
}
|
go
|
func unmarshalFile(dirname string, f os.FileInfo) (*TUFChange, error) {
c := &TUFChange{}
raw, err := ioutil.ReadFile(filepath.Join(dirname, f.Name()))
if err != nil {
return c, err
}
err = json.Unmarshal(raw, c)
if err != nil {
return c, err
}
return c, nil
}
|
[
"func",
"unmarshalFile",
"(",
"dirname",
"string",
",",
"f",
"os",
".",
"FileInfo",
")",
"(",
"*",
"TUFChange",
",",
"error",
")",
"{",
"c",
":=",
"&",
"TUFChange",
"{",
"}",
"\n",
"raw",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filepath",
".",
"Join",
"(",
"dirname",
",",
"f",
".",
"Name",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"c",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"raw",
",",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"c",
",",
"err",
"\n",
"}",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] |
// Read a JSON formatted file from disk; convert to TUFChange struct
|
[
"Read",
"a",
"JSON",
"formatted",
"file",
"from",
"disk",
";",
"convert",
"to",
"TUFChange",
"struct"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L54-L65
|
train
|
theupdateframework/notary
|
client/changelist/file_changelist.go
|
List
|
func (cl FileChangelist) List() []Change {
var changes []Change
fileInfos, err := getFileNames(cl.dir)
if err != nil {
return changes
}
for _, f := range fileInfos {
c, err := unmarshalFile(cl.dir, f)
if err != nil {
logrus.Warn(err.Error())
continue
}
changes = append(changes, c)
}
return changes
}
|
go
|
func (cl FileChangelist) List() []Change {
var changes []Change
fileInfos, err := getFileNames(cl.dir)
if err != nil {
return changes
}
for _, f := range fileInfos {
c, err := unmarshalFile(cl.dir, f)
if err != nil {
logrus.Warn(err.Error())
continue
}
changes = append(changes, c)
}
return changes
}
|
[
"func",
"(",
"cl",
"FileChangelist",
")",
"List",
"(",
")",
"[",
"]",
"Change",
"{",
"var",
"changes",
"[",
"]",
"Change",
"\n",
"fileInfos",
",",
"err",
":=",
"getFileNames",
"(",
"cl",
".",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"changes",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"fileInfos",
"{",
"c",
",",
"err",
":=",
"unmarshalFile",
"(",
"cl",
".",
"dir",
",",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Warn",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"changes",
"=",
"append",
"(",
"changes",
",",
"c",
")",
"\n",
"}",
"\n",
"return",
"changes",
"\n",
"}"
] |
// List returns a list of sorted changes
|
[
"List",
"returns",
"a",
"list",
"of",
"sorted",
"changes"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L68-L83
|
train
|
theupdateframework/notary
|
client/changelist/file_changelist.go
|
Add
|
func (cl FileChangelist) Add(c Change) error {
cJSON, err := json.Marshal(c)
if err != nil {
return err
}
filename := fmt.Sprintf("%020d_%s.change", time.Now().UnixNano(), uuid.Generate())
return ioutil.WriteFile(filepath.Join(cl.dir, filename), cJSON, 0644)
}
|
go
|
func (cl FileChangelist) Add(c Change) error {
cJSON, err := json.Marshal(c)
if err != nil {
return err
}
filename := fmt.Sprintf("%020d_%s.change", time.Now().UnixNano(), uuid.Generate())
return ioutil.WriteFile(filepath.Join(cl.dir, filename), cJSON, 0644)
}
|
[
"func",
"(",
"cl",
"FileChangelist",
")",
"Add",
"(",
"c",
"Change",
")",
"error",
"{",
"cJSON",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"filename",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
",",
"uuid",
".",
"Generate",
"(",
")",
")",
"\n",
"return",
"ioutil",
".",
"WriteFile",
"(",
"filepath",
".",
"Join",
"(",
"cl",
".",
"dir",
",",
"filename",
")",
",",
"cJSON",
",",
"0644",
")",
"\n",
"}"
] |
// Add adds a change to the file change list
|
[
"Add",
"adds",
"a",
"change",
"to",
"the",
"file",
"change",
"list"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L86-L93
|
train
|
theupdateframework/notary
|
client/changelist/file_changelist.go
|
Clear
|
func (cl FileChangelist) Clear(archive string) error {
dir, err := os.Open(cl.dir)
if err != nil {
return err
}
defer dir.Close()
files, err := dir.Readdir(0)
if err != nil {
return err
}
for _, f := range files {
os.Remove(filepath.Join(cl.dir, f.Name()))
}
return nil
}
|
go
|
func (cl FileChangelist) Clear(archive string) error {
dir, err := os.Open(cl.dir)
if err != nil {
return err
}
defer dir.Close()
files, err := dir.Readdir(0)
if err != nil {
return err
}
for _, f := range files {
os.Remove(filepath.Join(cl.dir, f.Name()))
}
return nil
}
|
[
"func",
"(",
"cl",
"FileChangelist",
")",
"Clear",
"(",
"archive",
"string",
")",
"error",
"{",
"dir",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"cl",
".",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"dir",
".",
"Close",
"(",
")",
"\n",
"files",
",",
"err",
":=",
"dir",
".",
"Readdir",
"(",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"os",
".",
"Remove",
"(",
"filepath",
".",
"Join",
"(",
"cl",
".",
"dir",
",",
"f",
".",
"Name",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Clear clears the change list
// N.B. archiving not currently implemented
|
[
"Clear",
"clears",
"the",
"change",
"list",
"N",
".",
"B",
".",
"archiving",
"not",
"currently",
"implemented"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L118-L132
|
train
|
theupdateframework/notary
|
client/changelist/file_changelist.go
|
NewIterator
|
func (cl FileChangelist) NewIterator() (ChangeIterator, error) {
fileInfos, err := getFileNames(cl.dir)
if err != nil {
return &FileChangeListIterator{}, err
}
return &FileChangeListIterator{dirname: cl.dir, collection: fileInfos}, nil
}
|
go
|
func (cl FileChangelist) NewIterator() (ChangeIterator, error) {
fileInfos, err := getFileNames(cl.dir)
if err != nil {
return &FileChangeListIterator{}, err
}
return &FileChangeListIterator{dirname: cl.dir, collection: fileInfos}, nil
}
|
[
"func",
"(",
"cl",
"FileChangelist",
")",
"NewIterator",
"(",
")",
"(",
"ChangeIterator",
",",
"error",
")",
"{",
"fileInfos",
",",
"err",
":=",
"getFileNames",
"(",
"cl",
".",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"FileChangeListIterator",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"FileChangeListIterator",
"{",
"dirname",
":",
"cl",
".",
"dir",
",",
"collection",
":",
"fileInfos",
"}",
",",
"nil",
"\n",
"}"
] |
// NewIterator creates an iterator from FileChangelist
|
[
"NewIterator",
"creates",
"an",
"iterator",
"from",
"FileChangelist"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L146-L152
|
train
|
theupdateframework/notary
|
client/changelist/file_changelist.go
|
Next
|
func (m *FileChangeListIterator) Next() (item Change, err error) {
if m.index >= len(m.collection) {
return nil, IteratorBoundsError(m.index)
}
f := m.collection[m.index]
m.index++
item, err = unmarshalFile(m.dirname, f)
return
}
|
go
|
func (m *FileChangeListIterator) Next() (item Change, err error) {
if m.index >= len(m.collection) {
return nil, IteratorBoundsError(m.index)
}
f := m.collection[m.index]
m.index++
item, err = unmarshalFile(m.dirname, f)
return
}
|
[
"func",
"(",
"m",
"*",
"FileChangeListIterator",
")",
"Next",
"(",
")",
"(",
"item",
"Change",
",",
"err",
"error",
")",
"{",
"if",
"m",
".",
"index",
">=",
"len",
"(",
"m",
".",
"collection",
")",
"{",
"return",
"nil",
",",
"IteratorBoundsError",
"(",
"m",
".",
"index",
")",
"\n",
"}",
"\n",
"f",
":=",
"m",
".",
"collection",
"[",
"m",
".",
"index",
"]",
"\n",
"m",
".",
"index",
"++",
"\n",
"item",
",",
"err",
"=",
"unmarshalFile",
"(",
"m",
".",
"dirname",
",",
"f",
")",
"\n",
"return",
"\n",
"}"
] |
// Next returns the next Change in the FileChangeList
|
[
"Next",
"returns",
"the",
"next",
"Change",
"in",
"the",
"FileChangeList"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L170-L178
|
train
|
theupdateframework/notary
|
client/changelist/file_changelist.go
|
Less
|
func (cs fileChanges) Less(i, j int) bool {
return cs[i].Name() < cs[j].Name()
}
|
go
|
func (cs fileChanges) Less(i, j int) bool {
return cs[i].Name() < cs[j].Name()
}
|
[
"func",
"(",
"cs",
"fileChanges",
")",
"Less",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"cs",
"[",
"i",
"]",
".",
"Name",
"(",
")",
"<",
"cs",
"[",
"j",
"]",
".",
"Name",
"(",
")",
"\n",
"}"
] |
// Less compares the names of two different file changes
|
[
"Less",
"compares",
"the",
"names",
"of",
"two",
"different",
"file",
"changes"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L193-L195
|
train
|
theupdateframework/notary
|
client/changelist/file_changelist.go
|
Swap
|
func (cs fileChanges) Swap(i, j int) {
tmp := cs[i]
cs[i] = cs[j]
cs[j] = tmp
}
|
go
|
func (cs fileChanges) Swap(i, j int) {
tmp := cs[i]
cs[i] = cs[j]
cs[j] = tmp
}
|
[
"func",
"(",
"cs",
"fileChanges",
")",
"Swap",
"(",
"i",
",",
"j",
"int",
")",
"{",
"tmp",
":=",
"cs",
"[",
"i",
"]",
"\n",
"cs",
"[",
"i",
"]",
"=",
"cs",
"[",
"j",
"]",
"\n",
"cs",
"[",
"j",
"]",
"=",
"tmp",
"\n",
"}"
] |
// Swap swaps the position of two file changes
|
[
"Swap",
"swaps",
"the",
"position",
"of",
"two",
"file",
"changes"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/changelist/file_changelist.go#L198-L202
|
train
|
theupdateframework/notary
|
trustmanager/remoteks/server.go
|
Set
|
func (s *GRPCStorage) Set(ctx context.Context, msg *SetMsg) (*google_protobuf.Empty, error) {
logrus.Debugf("storing: %s", msg.FileName)
err := s.backend.Set(msg.FileName, msg.Data)
if err != nil {
logrus.Errorf("failed to store: %s", err.Error())
}
return &google_protobuf.Empty{}, err
}
|
go
|
func (s *GRPCStorage) Set(ctx context.Context, msg *SetMsg) (*google_protobuf.Empty, error) {
logrus.Debugf("storing: %s", msg.FileName)
err := s.backend.Set(msg.FileName, msg.Data)
if err != nil {
logrus.Errorf("failed to store: %s", err.Error())
}
return &google_protobuf.Empty{}, err
}
|
[
"func",
"(",
"s",
"*",
"GRPCStorage",
")",
"Set",
"(",
"ctx",
"context",
".",
"Context",
",",
"msg",
"*",
"SetMsg",
")",
"(",
"*",
"google_protobuf",
".",
"Empty",
",",
"error",
")",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"msg",
".",
"FileName",
")",
"\n",
"err",
":=",
"s",
".",
"backend",
".",
"Set",
"(",
"msg",
".",
"FileName",
",",
"msg",
".",
"Data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"&",
"google_protobuf",
".",
"Empty",
"{",
"}",
",",
"err",
"\n",
"}"
] |
// Set writes the provided data under the given identifier.
|
[
"Set",
"writes",
"the",
"provided",
"data",
"under",
"the",
"given",
"identifier",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/server.go#L27-L34
|
train
|
theupdateframework/notary
|
trustmanager/remoteks/server.go
|
Remove
|
func (s *GRPCStorage) Remove(ctx context.Context, fn *FileNameMsg) (*google_protobuf.Empty, error) {
return &google_protobuf.Empty{}, s.backend.Remove(fn.FileName)
}
|
go
|
func (s *GRPCStorage) Remove(ctx context.Context, fn *FileNameMsg) (*google_protobuf.Empty, error) {
return &google_protobuf.Empty{}, s.backend.Remove(fn.FileName)
}
|
[
"func",
"(",
"s",
"*",
"GRPCStorage",
")",
"Remove",
"(",
"ctx",
"context",
".",
"Context",
",",
"fn",
"*",
"FileNameMsg",
")",
"(",
"*",
"google_protobuf",
".",
"Empty",
",",
"error",
")",
"{",
"return",
"&",
"google_protobuf",
".",
"Empty",
"{",
"}",
",",
"s",
".",
"backend",
".",
"Remove",
"(",
"fn",
".",
"FileName",
")",
"\n",
"}"
] |
// Remove deletes the data associated with the provided identifier.
|
[
"Remove",
"deletes",
"the",
"data",
"associated",
"with",
"the",
"provided",
"identifier",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/server.go#L37-L39
|
train
|
theupdateframework/notary
|
trustmanager/remoteks/server.go
|
Get
|
func (s *GRPCStorage) Get(ctx context.Context, fn *FileNameMsg) (*ByteMsg, error) {
data, err := s.backend.Get(fn.FileName)
if err != nil {
return &ByteMsg{}, err
}
return &ByteMsg{Data: data}, nil
}
|
go
|
func (s *GRPCStorage) Get(ctx context.Context, fn *FileNameMsg) (*ByteMsg, error) {
data, err := s.backend.Get(fn.FileName)
if err != nil {
return &ByteMsg{}, err
}
return &ByteMsg{Data: data}, nil
}
|
[
"func",
"(",
"s",
"*",
"GRPCStorage",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
",",
"fn",
"*",
"FileNameMsg",
")",
"(",
"*",
"ByteMsg",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"s",
".",
"backend",
".",
"Get",
"(",
"fn",
".",
"FileName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"ByteMsg",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"ByteMsg",
"{",
"Data",
":",
"data",
"}",
",",
"nil",
"\n",
"}"
] |
// Get returns the data associated with the provided identifier.
|
[
"Get",
"returns",
"the",
"data",
"associated",
"with",
"the",
"provided",
"identifier",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/server.go#L42-L48
|
train
|
theupdateframework/notary
|
trustmanager/remoteks/server.go
|
ListFiles
|
func (s *GRPCStorage) ListFiles(ctx context.Context, _ *google_protobuf.Empty) (*StringListMsg, error) {
lst := s.backend.ListFiles()
logrus.Debugf("found %d keys", len(lst))
return &StringListMsg{
FileNames: lst,
}, nil
}
|
go
|
func (s *GRPCStorage) ListFiles(ctx context.Context, _ *google_protobuf.Empty) (*StringListMsg, error) {
lst := s.backend.ListFiles()
logrus.Debugf("found %d keys", len(lst))
return &StringListMsg{
FileNames: lst,
}, nil
}
|
[
"func",
"(",
"s",
"*",
"GRPCStorage",
")",
"ListFiles",
"(",
"ctx",
"context",
".",
"Context",
",",
"_",
"*",
"google_protobuf",
".",
"Empty",
")",
"(",
"*",
"StringListMsg",
",",
"error",
")",
"{",
"lst",
":=",
"s",
".",
"backend",
".",
"ListFiles",
"(",
")",
"\n",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"len",
"(",
"lst",
")",
")",
"\n",
"return",
"&",
"StringListMsg",
"{",
"FileNames",
":",
"lst",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// ListFiles returns all known identifiers in the storage backend.
|
[
"ListFiles",
"returns",
"all",
"known",
"identifiers",
"in",
"the",
"storage",
"backend",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/server.go#L51-L57
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
MetadataRoleMapToStringMap
|
func MetadataRoleMapToStringMap(roles map[RoleName][]byte) map[string][]byte {
metadata := make(map[string][]byte)
for k, v := range roles {
metadata[k.String()] = v
}
return metadata
}
|
go
|
func MetadataRoleMapToStringMap(roles map[RoleName][]byte) map[string][]byte {
metadata := make(map[string][]byte)
for k, v := range roles {
metadata[k.String()] = v
}
return metadata
}
|
[
"func",
"MetadataRoleMapToStringMap",
"(",
"roles",
"map",
"[",
"RoleName",
"]",
"[",
"]",
"byte",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
"{",
"metadata",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"roles",
"{",
"metadata",
"[",
"k",
".",
"String",
"(",
")",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"metadata",
"\n",
"}"
] |
// MetadataRoleMapToStringMap generates a map string of bytes from a map RoleName of bytes
|
[
"MetadataRoleMapToStringMap",
"generates",
"a",
"map",
"string",
"of",
"bytes",
"from",
"a",
"map",
"RoleName",
"of",
"bytes"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L44-L50
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
NewRoleList
|
func NewRoleList(roles []string) []RoleName {
var roleNames []RoleName
for _, role := range roles {
roleNames = append(roleNames, RoleName(role))
}
return roleNames
}
|
go
|
func NewRoleList(roles []string) []RoleName {
var roleNames []RoleName
for _, role := range roles {
roleNames = append(roleNames, RoleName(role))
}
return roleNames
}
|
[
"func",
"NewRoleList",
"(",
"roles",
"[",
"]",
"string",
")",
"[",
"]",
"RoleName",
"{",
"var",
"roleNames",
"[",
"]",
"RoleName",
"\n",
"for",
"_",
",",
"role",
":=",
"range",
"roles",
"{",
"roleNames",
"=",
"append",
"(",
"roleNames",
",",
"RoleName",
"(",
"role",
")",
")",
"\n",
"}",
"\n",
"return",
"roleNames",
"\n",
"}"
] |
// NewRoleList generates an array of RoleName objects from a slice of strings
|
[
"NewRoleList",
"generates",
"an",
"array",
"of",
"RoleName",
"objects",
"from",
"a",
"slice",
"of",
"strings"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L53-L59
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
RolesListToStringList
|
func RolesListToStringList(roles []RoleName) []string {
var roleNames []string
for _, role := range roles {
roleNames = append(roleNames, role.String())
}
return roleNames
}
|
go
|
func RolesListToStringList(roles []RoleName) []string {
var roleNames []string
for _, role := range roles {
roleNames = append(roleNames, role.String())
}
return roleNames
}
|
[
"func",
"RolesListToStringList",
"(",
"roles",
"[",
"]",
"RoleName",
")",
"[",
"]",
"string",
"{",
"var",
"roleNames",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"role",
":=",
"range",
"roles",
"{",
"roleNames",
"=",
"append",
"(",
"roleNames",
",",
"role",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"roleNames",
"\n",
"}"
] |
// RolesListToStringList generates an array of string objects from a slice of roles
|
[
"RolesListToStringList",
"generates",
"an",
"array",
"of",
"string",
"objects",
"from",
"a",
"slice",
"of",
"roles"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L62-L68
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
ValidTUFType
|
func ValidTUFType(typ string, role RoleName) bool {
if ValidRole(role) {
// All targets delegation roles must have
// the valid type is for targets.
if role == "" {
// role is unknown and does not map to
// a type
return false
}
if strings.HasPrefix(role.String(), CanonicalTargetsRole.String()+"/") {
role = CanonicalTargetsRole
}
}
// most people will just use the defaults so have this optimal check
// first. Do comparison just in case there is some unknown vulnerability
// if a key and value in the map differ.
if v, ok := TUFTypes[role]; ok {
return typ == v
}
return false
}
|
go
|
func ValidTUFType(typ string, role RoleName) bool {
if ValidRole(role) {
// All targets delegation roles must have
// the valid type is for targets.
if role == "" {
// role is unknown and does not map to
// a type
return false
}
if strings.HasPrefix(role.String(), CanonicalTargetsRole.String()+"/") {
role = CanonicalTargetsRole
}
}
// most people will just use the defaults so have this optimal check
// first. Do comparison just in case there is some unknown vulnerability
// if a key and value in the map differ.
if v, ok := TUFTypes[role]; ok {
return typ == v
}
return false
}
|
[
"func",
"ValidTUFType",
"(",
"typ",
"string",
",",
"role",
"RoleName",
")",
"bool",
"{",
"if",
"ValidRole",
"(",
"role",
")",
"{",
"// All targets delegation roles must have",
"// the valid type is for targets.",
"if",
"role",
"==",
"\"",
"\"",
"{",
"// role is unknown and does not map to",
"// a type",
"return",
"false",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"role",
".",
"String",
"(",
")",
",",
"CanonicalTargetsRole",
".",
"String",
"(",
")",
"+",
"\"",
"\"",
")",
"{",
"role",
"=",
"CanonicalTargetsRole",
"\n",
"}",
"\n",
"}",
"\n",
"// most people will just use the defaults so have this optimal check",
"// first. Do comparison just in case there is some unknown vulnerability",
"// if a key and value in the map differ.",
"if",
"v",
",",
"ok",
":=",
"TUFTypes",
"[",
"role",
"]",
";",
"ok",
"{",
"return",
"typ",
"==",
"v",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// ValidTUFType checks if the given type is valid for the role
|
[
"ValidTUFType",
"checks",
"if",
"the",
"given",
"type",
"is",
"valid",
"for",
"the",
"role"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L115-L135
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
Equals
|
func (f FileMeta) Equals(o FileMeta) bool {
if o.Length != f.Length || len(f.Hashes) != len(f.Hashes) {
return false
}
if f.Custom == nil && o.Custom != nil || f.Custom != nil && o.Custom == nil {
return false
}
// we don't care if these are valid hashes, just that they are equal
for key, val := range f.Hashes {
if !bytes.Equal(val, o.Hashes[key]) {
return false
}
}
if f.Custom == nil && o.Custom == nil {
return true
}
fBytes, err := f.Custom.MarshalJSON()
if err != nil {
return false
}
oBytes, err := o.Custom.MarshalJSON()
if err != nil {
return false
}
return bytes.Equal(fBytes, oBytes)
}
|
go
|
func (f FileMeta) Equals(o FileMeta) bool {
if o.Length != f.Length || len(f.Hashes) != len(f.Hashes) {
return false
}
if f.Custom == nil && o.Custom != nil || f.Custom != nil && o.Custom == nil {
return false
}
// we don't care if these are valid hashes, just that they are equal
for key, val := range f.Hashes {
if !bytes.Equal(val, o.Hashes[key]) {
return false
}
}
if f.Custom == nil && o.Custom == nil {
return true
}
fBytes, err := f.Custom.MarshalJSON()
if err != nil {
return false
}
oBytes, err := o.Custom.MarshalJSON()
if err != nil {
return false
}
return bytes.Equal(fBytes, oBytes)
}
|
[
"func",
"(",
"f",
"FileMeta",
")",
"Equals",
"(",
"o",
"FileMeta",
")",
"bool",
"{",
"if",
"o",
".",
"Length",
"!=",
"f",
".",
"Length",
"||",
"len",
"(",
"f",
".",
"Hashes",
")",
"!=",
"len",
"(",
"f",
".",
"Hashes",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"f",
".",
"Custom",
"==",
"nil",
"&&",
"o",
".",
"Custom",
"!=",
"nil",
"||",
"f",
".",
"Custom",
"!=",
"nil",
"&&",
"o",
".",
"Custom",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// we don't care if these are valid hashes, just that they are equal",
"for",
"key",
",",
"val",
":=",
"range",
"f",
".",
"Hashes",
"{",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"val",
",",
"o",
".",
"Hashes",
"[",
"key",
"]",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"f",
".",
"Custom",
"==",
"nil",
"&&",
"o",
".",
"Custom",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"fBytes",
",",
"err",
":=",
"f",
".",
"Custom",
".",
"MarshalJSON",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"oBytes",
",",
"err",
":=",
"o",
".",
"Custom",
".",
"MarshalJSON",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"bytes",
".",
"Equal",
"(",
"fBytes",
",",
"oBytes",
")",
"\n",
"}"
] |
// Equals returns true if the other FileMeta object is equivalent to this one
|
[
"Equals",
"returns",
"true",
"if",
"the",
"other",
"FileMeta",
"object",
"is",
"equivalent",
"to",
"this",
"one"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L188-L213
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
CheckHashes
|
func CheckHashes(payload []byte, name string, hashes Hashes) error {
cnt := 0
// k, v indicate the hash algorithm and the corresponding value
for k, v := range hashes {
switch k {
case notary.SHA256:
checksum := sha256.Sum256(payload)
if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
return ErrMismatchedChecksum{alg: notary.SHA256, name: name, expected: hex.EncodeToString(v)}
}
cnt++
case notary.SHA512:
checksum := sha512.Sum512(payload)
if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
return ErrMismatchedChecksum{alg: notary.SHA512, name: name, expected: hex.EncodeToString(v)}
}
cnt++
}
}
if cnt == 0 {
return ErrMissingMeta{Role: name}
}
return nil
}
|
go
|
func CheckHashes(payload []byte, name string, hashes Hashes) error {
cnt := 0
// k, v indicate the hash algorithm and the corresponding value
for k, v := range hashes {
switch k {
case notary.SHA256:
checksum := sha256.Sum256(payload)
if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
return ErrMismatchedChecksum{alg: notary.SHA256, name: name, expected: hex.EncodeToString(v)}
}
cnt++
case notary.SHA512:
checksum := sha512.Sum512(payload)
if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
return ErrMismatchedChecksum{alg: notary.SHA512, name: name, expected: hex.EncodeToString(v)}
}
cnt++
}
}
if cnt == 0 {
return ErrMissingMeta{Role: name}
}
return nil
}
|
[
"func",
"CheckHashes",
"(",
"payload",
"[",
"]",
"byte",
",",
"name",
"string",
",",
"hashes",
"Hashes",
")",
"error",
"{",
"cnt",
":=",
"0",
"\n\n",
"// k, v indicate the hash algorithm and the corresponding value",
"for",
"k",
",",
"v",
":=",
"range",
"hashes",
"{",
"switch",
"k",
"{",
"case",
"notary",
".",
"SHA256",
":",
"checksum",
":=",
"sha256",
".",
"Sum256",
"(",
"payload",
")",
"\n",
"if",
"subtle",
".",
"ConstantTimeCompare",
"(",
"checksum",
"[",
":",
"]",
",",
"v",
")",
"==",
"0",
"{",
"return",
"ErrMismatchedChecksum",
"{",
"alg",
":",
"notary",
".",
"SHA256",
",",
"name",
":",
"name",
",",
"expected",
":",
"hex",
".",
"EncodeToString",
"(",
"v",
")",
"}",
"\n",
"}",
"\n",
"cnt",
"++",
"\n",
"case",
"notary",
".",
"SHA512",
":",
"checksum",
":=",
"sha512",
".",
"Sum512",
"(",
"payload",
")",
"\n",
"if",
"subtle",
".",
"ConstantTimeCompare",
"(",
"checksum",
"[",
":",
"]",
",",
"v",
")",
"==",
"0",
"{",
"return",
"ErrMismatchedChecksum",
"{",
"alg",
":",
"notary",
".",
"SHA512",
",",
"name",
":",
"name",
",",
"expected",
":",
"hex",
".",
"EncodeToString",
"(",
"v",
")",
"}",
"\n",
"}",
"\n",
"cnt",
"++",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"cnt",
"==",
"0",
"{",
"return",
"ErrMissingMeta",
"{",
"Role",
":",
"name",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// CheckHashes verifies all the checksums specified by the "hashes" of the payload.
|
[
"CheckHashes",
"verifies",
"all",
"the",
"checksums",
"specified",
"by",
"the",
"hashes",
"of",
"the",
"payload",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L216-L242
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
CompareMultiHashes
|
func CompareMultiHashes(hashes1, hashes2 Hashes) error {
// First check if the two hash structures are valid
if err := CheckValidHashStructures(hashes1); err != nil {
return err
}
if err := CheckValidHashStructures(hashes2); err != nil {
return err
}
// Check if they have at least one matching hash, and no conflicts
cnt := 0
for hashAlg, hash1 := range hashes1 {
hash2, ok := hashes2[hashAlg]
if !ok {
continue
}
if subtle.ConstantTimeCompare(hash1[:], hash2[:]) == 0 {
return fmt.Errorf("mismatched %s checksum", hashAlg)
}
// If we reached here, we had a match
cnt++
}
if cnt == 0 {
return fmt.Errorf("at least one matching hash needed")
}
return nil
}
|
go
|
func CompareMultiHashes(hashes1, hashes2 Hashes) error {
// First check if the two hash structures are valid
if err := CheckValidHashStructures(hashes1); err != nil {
return err
}
if err := CheckValidHashStructures(hashes2); err != nil {
return err
}
// Check if they have at least one matching hash, and no conflicts
cnt := 0
for hashAlg, hash1 := range hashes1 {
hash2, ok := hashes2[hashAlg]
if !ok {
continue
}
if subtle.ConstantTimeCompare(hash1[:], hash2[:]) == 0 {
return fmt.Errorf("mismatched %s checksum", hashAlg)
}
// If we reached here, we had a match
cnt++
}
if cnt == 0 {
return fmt.Errorf("at least one matching hash needed")
}
return nil
}
|
[
"func",
"CompareMultiHashes",
"(",
"hashes1",
",",
"hashes2",
"Hashes",
")",
"error",
"{",
"// First check if the two hash structures are valid",
"if",
"err",
":=",
"CheckValidHashStructures",
"(",
"hashes1",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"CheckValidHashStructures",
"(",
"hashes2",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Check if they have at least one matching hash, and no conflicts",
"cnt",
":=",
"0",
"\n",
"for",
"hashAlg",
",",
"hash1",
":=",
"range",
"hashes1",
"{",
"hash2",
",",
"ok",
":=",
"hashes2",
"[",
"hashAlg",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"subtle",
".",
"ConstantTimeCompare",
"(",
"hash1",
"[",
":",
"]",
",",
"hash2",
"[",
":",
"]",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hashAlg",
")",
"\n",
"}",
"\n",
"// If we reached here, we had a match",
"cnt",
"++",
"\n",
"}",
"\n\n",
"if",
"cnt",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// CompareMultiHashes verifies that the two Hashes passed in can represent the same data.
// This means that both maps must have at least one key defined for which they map, and no conflicts.
// Note that we check the intersection of map keys, which adds support for non-default hash algorithms in notary
|
[
"CompareMultiHashes",
"verifies",
"that",
"the",
"two",
"Hashes",
"passed",
"in",
"can",
"represent",
"the",
"same",
"data",
".",
"This",
"means",
"that",
"both",
"maps",
"must",
"have",
"at",
"least",
"one",
"key",
"defined",
"for",
"which",
"they",
"map",
"and",
"no",
"conflicts",
".",
"Note",
"that",
"we",
"check",
"the",
"intersection",
"of",
"map",
"keys",
"which",
"adds",
"support",
"for",
"non",
"-",
"default",
"hash",
"algorithms",
"in",
"notary"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L247-L276
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
CheckValidHashStructures
|
func CheckValidHashStructures(hashes Hashes) error {
cnt := 0
for k, v := range hashes {
switch k {
case notary.SHA256:
if len(v) != sha256.Size {
return ErrInvalidChecksum{alg: notary.SHA256}
}
cnt++
case notary.SHA512:
if len(v) != sha512.Size {
return ErrInvalidChecksum{alg: notary.SHA512}
}
cnt++
}
}
if cnt == 0 {
return fmt.Errorf("at least one supported hash needed")
}
return nil
}
|
go
|
func CheckValidHashStructures(hashes Hashes) error {
cnt := 0
for k, v := range hashes {
switch k {
case notary.SHA256:
if len(v) != sha256.Size {
return ErrInvalidChecksum{alg: notary.SHA256}
}
cnt++
case notary.SHA512:
if len(v) != sha512.Size {
return ErrInvalidChecksum{alg: notary.SHA512}
}
cnt++
}
}
if cnt == 0 {
return fmt.Errorf("at least one supported hash needed")
}
return nil
}
|
[
"func",
"CheckValidHashStructures",
"(",
"hashes",
"Hashes",
")",
"error",
"{",
"cnt",
":=",
"0",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"hashes",
"{",
"switch",
"k",
"{",
"case",
"notary",
".",
"SHA256",
":",
"if",
"len",
"(",
"v",
")",
"!=",
"sha256",
".",
"Size",
"{",
"return",
"ErrInvalidChecksum",
"{",
"alg",
":",
"notary",
".",
"SHA256",
"}",
"\n",
"}",
"\n",
"cnt",
"++",
"\n",
"case",
"notary",
".",
"SHA512",
":",
"if",
"len",
"(",
"v",
")",
"!=",
"sha512",
".",
"Size",
"{",
"return",
"ErrInvalidChecksum",
"{",
"alg",
":",
"notary",
".",
"SHA512",
"}",
"\n",
"}",
"\n",
"cnt",
"++",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"cnt",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// CheckValidHashStructures returns an error, or nil, depending on whether
// the content of the hashes is valid or not.
|
[
"CheckValidHashStructures",
"returns",
"an",
"error",
"or",
"nil",
"depending",
"on",
"whether",
"the",
"content",
"of",
"the",
"hashes",
"is",
"valid",
"or",
"not",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L280-L303
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
NewFileMeta
|
func NewFileMeta(r io.Reader, hashAlgorithms ...string) (FileMeta, error) {
if len(hashAlgorithms) == 0 {
hashAlgorithms = []string{defaultHashAlgorithm}
}
hashes := make(map[string]hash.Hash, len(hashAlgorithms))
for _, hashAlgorithm := range hashAlgorithms {
var h hash.Hash
switch hashAlgorithm {
case notary.SHA256:
h = sha256.New()
case notary.SHA512:
h = sha512.New()
default:
return FileMeta{}, fmt.Errorf("Unknown hash algorithm: %s", hashAlgorithm)
}
hashes[hashAlgorithm] = h
r = io.TeeReader(r, h)
}
n, err := io.Copy(ioutil.Discard, r)
if err != nil {
return FileMeta{}, err
}
m := FileMeta{Length: n, Hashes: make(Hashes, len(hashes))}
for hashAlgorithm, h := range hashes {
m.Hashes[hashAlgorithm] = h.Sum(nil)
}
return m, nil
}
|
go
|
func NewFileMeta(r io.Reader, hashAlgorithms ...string) (FileMeta, error) {
if len(hashAlgorithms) == 0 {
hashAlgorithms = []string{defaultHashAlgorithm}
}
hashes := make(map[string]hash.Hash, len(hashAlgorithms))
for _, hashAlgorithm := range hashAlgorithms {
var h hash.Hash
switch hashAlgorithm {
case notary.SHA256:
h = sha256.New()
case notary.SHA512:
h = sha512.New()
default:
return FileMeta{}, fmt.Errorf("Unknown hash algorithm: %s", hashAlgorithm)
}
hashes[hashAlgorithm] = h
r = io.TeeReader(r, h)
}
n, err := io.Copy(ioutil.Discard, r)
if err != nil {
return FileMeta{}, err
}
m := FileMeta{Length: n, Hashes: make(Hashes, len(hashes))}
for hashAlgorithm, h := range hashes {
m.Hashes[hashAlgorithm] = h.Sum(nil)
}
return m, nil
}
|
[
"func",
"NewFileMeta",
"(",
"r",
"io",
".",
"Reader",
",",
"hashAlgorithms",
"...",
"string",
")",
"(",
"FileMeta",
",",
"error",
")",
"{",
"if",
"len",
"(",
"hashAlgorithms",
")",
"==",
"0",
"{",
"hashAlgorithms",
"=",
"[",
"]",
"string",
"{",
"defaultHashAlgorithm",
"}",
"\n",
"}",
"\n",
"hashes",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"hash",
".",
"Hash",
",",
"len",
"(",
"hashAlgorithms",
")",
")",
"\n",
"for",
"_",
",",
"hashAlgorithm",
":=",
"range",
"hashAlgorithms",
"{",
"var",
"h",
"hash",
".",
"Hash",
"\n",
"switch",
"hashAlgorithm",
"{",
"case",
"notary",
".",
"SHA256",
":",
"h",
"=",
"sha256",
".",
"New",
"(",
")",
"\n",
"case",
"notary",
".",
"SHA512",
":",
"h",
"=",
"sha512",
".",
"New",
"(",
")",
"\n",
"default",
":",
"return",
"FileMeta",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hashAlgorithm",
")",
"\n",
"}",
"\n",
"hashes",
"[",
"hashAlgorithm",
"]",
"=",
"h",
"\n",
"r",
"=",
"io",
".",
"TeeReader",
"(",
"r",
",",
"h",
")",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"ioutil",
".",
"Discard",
",",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"FileMeta",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"m",
":=",
"FileMeta",
"{",
"Length",
":",
"n",
",",
"Hashes",
":",
"make",
"(",
"Hashes",
",",
"len",
"(",
"hashes",
")",
")",
"}",
"\n",
"for",
"hashAlgorithm",
",",
"h",
":=",
"range",
"hashes",
"{",
"m",
".",
"Hashes",
"[",
"hashAlgorithm",
"]",
"=",
"h",
".",
"Sum",
"(",
"nil",
")",
"\n",
"}",
"\n",
"return",
"m",
",",
"nil",
"\n",
"}"
] |
// NewFileMeta generates a FileMeta object from the reader, using the
// hash algorithms provided
|
[
"NewFileMeta",
"generates",
"a",
"FileMeta",
"object",
"from",
"the",
"reader",
"using",
"the",
"hash",
"algorithms",
"provided"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L307-L334
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
NewDelegations
|
func NewDelegations() *Delegations {
return &Delegations{
Keys: make(map[string]PublicKey),
Roles: make([]*Role, 0),
}
}
|
go
|
func NewDelegations() *Delegations {
return &Delegations{
Keys: make(map[string]PublicKey),
Roles: make([]*Role, 0),
}
}
|
[
"func",
"NewDelegations",
"(",
")",
"*",
"Delegations",
"{",
"return",
"&",
"Delegations",
"{",
"Keys",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"PublicKey",
")",
",",
"Roles",
":",
"make",
"(",
"[",
"]",
"*",
"Role",
",",
"0",
")",
",",
"}",
"\n",
"}"
] |
// NewDelegations initializes an empty Delegations object
|
[
"NewDelegations",
"initializes",
"an",
"empty",
"Delegations",
"object"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L343-L348
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
SetDefaultExpiryTimes
|
func SetDefaultExpiryTimes(times map[RoleName]time.Duration) {
for key, value := range times {
if _, ok := defaultExpiryTimes[key]; !ok {
logrus.Errorf("Attempted to set default expiry for an unknown role: %s", key.String())
continue
}
defaultExpiryTimes[key] = value
}
}
|
go
|
func SetDefaultExpiryTimes(times map[RoleName]time.Duration) {
for key, value := range times {
if _, ok := defaultExpiryTimes[key]; !ok {
logrus.Errorf("Attempted to set default expiry for an unknown role: %s", key.String())
continue
}
defaultExpiryTimes[key] = value
}
}
|
[
"func",
"SetDefaultExpiryTimes",
"(",
"times",
"map",
"[",
"RoleName",
"]",
"time",
".",
"Duration",
")",
"{",
"for",
"key",
",",
"value",
":=",
"range",
"times",
"{",
"if",
"_",
",",
"ok",
":=",
"defaultExpiryTimes",
"[",
"key",
"]",
";",
"!",
"ok",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
".",
"String",
"(",
")",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"defaultExpiryTimes",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n",
"}"
] |
// SetDefaultExpiryTimes allows one to change the default expiries.
|
[
"SetDefaultExpiryTimes",
"allows",
"one",
"to",
"change",
"the",
"default",
"expiries",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L359-L367
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
DefaultExpires
|
func DefaultExpires(role RoleName) time.Time {
if d, ok := defaultExpiryTimes[role]; ok {
return time.Now().Add(d)
}
var t time.Time
return t.UTC().Round(time.Second)
}
|
go
|
func DefaultExpires(role RoleName) time.Time {
if d, ok := defaultExpiryTimes[role]; ok {
return time.Now().Add(d)
}
var t time.Time
return t.UTC().Round(time.Second)
}
|
[
"func",
"DefaultExpires",
"(",
"role",
"RoleName",
")",
"time",
".",
"Time",
"{",
"if",
"d",
",",
"ok",
":=",
"defaultExpiryTimes",
"[",
"role",
"]",
";",
"ok",
"{",
"return",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"d",
")",
"\n",
"}",
"\n",
"var",
"t",
"time",
".",
"Time",
"\n",
"return",
"t",
".",
"UTC",
"(",
")",
".",
"Round",
"(",
"time",
".",
"Second",
")",
"\n",
"}"
] |
// DefaultExpires gets the default expiry time for the given role
|
[
"DefaultExpires",
"gets",
"the",
"default",
"expiry",
"time",
"for",
"the",
"given",
"role"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L370-L376
|
train
|
theupdateframework/notary
|
tuf/data/types.go
|
UnmarshalJSON
|
func (s *Signature) UnmarshalJSON(data []byte) error {
uSignature := unmarshalledSignature{}
err := json.Unmarshal(data, &uSignature)
if err != nil {
return err
}
uSignature.Method = SigAlgorithm(strings.ToLower(string(uSignature.Method)))
*s = Signature(uSignature)
return nil
}
|
go
|
func (s *Signature) UnmarshalJSON(data []byte) error {
uSignature := unmarshalledSignature{}
err := json.Unmarshal(data, &uSignature)
if err != nil {
return err
}
uSignature.Method = SigAlgorithm(strings.ToLower(string(uSignature.Method)))
*s = Signature(uSignature)
return nil
}
|
[
"func",
"(",
"s",
"*",
"Signature",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"uSignature",
":=",
"unmarshalledSignature",
"{",
"}",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"uSignature",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"uSignature",
".",
"Method",
"=",
"SigAlgorithm",
"(",
"strings",
".",
"ToLower",
"(",
"string",
"(",
"uSignature",
".",
"Method",
")",
")",
")",
"\n",
"*",
"s",
"=",
"Signature",
"(",
"uSignature",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalJSON does a custom unmarshalling of the signature JSON
|
[
"UnmarshalJSON",
"does",
"a",
"custom",
"unmarshalling",
"of",
"the",
"signature",
"JSON"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/data/types.go#L381-L390
|
train
|
theupdateframework/notary
|
cryptoservice/crypto_service.go
|
Create
|
func (cs *CryptoService) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) {
if algorithm == data.RSAKey {
return nil, fmt.Errorf("%s keys can only be imported", data.RSAKey)
}
privKey, err := utils.GenerateKey(algorithm)
if err != nil {
return nil, fmt.Errorf("failed to generate %s key: %v", algorithm, err)
}
logrus.Debugf("generated new %s key for role: %s and keyID: %s", algorithm, role.String(), privKey.ID())
pubKey := data.PublicKeyFromPrivate(privKey)
return pubKey, cs.AddKey(role, gun, privKey)
}
|
go
|
func (cs *CryptoService) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) {
if algorithm == data.RSAKey {
return nil, fmt.Errorf("%s keys can only be imported", data.RSAKey)
}
privKey, err := utils.GenerateKey(algorithm)
if err != nil {
return nil, fmt.Errorf("failed to generate %s key: %v", algorithm, err)
}
logrus.Debugf("generated new %s key for role: %s and keyID: %s", algorithm, role.String(), privKey.ID())
pubKey := data.PublicKeyFromPrivate(privKey)
return pubKey, cs.AddKey(role, gun, privKey)
}
|
[
"func",
"(",
"cs",
"*",
"CryptoService",
")",
"Create",
"(",
"role",
"data",
".",
"RoleName",
",",
"gun",
"data",
".",
"GUN",
",",
"algorithm",
"string",
")",
"(",
"data",
".",
"PublicKey",
",",
"error",
")",
"{",
"if",
"algorithm",
"==",
"data",
".",
"RSAKey",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"data",
".",
"RSAKey",
")",
"\n",
"}",
"\n\n",
"privKey",
",",
"err",
":=",
"utils",
".",
"GenerateKey",
"(",
"algorithm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"algorithm",
",",
"err",
")",
"\n",
"}",
"\n",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"algorithm",
",",
"role",
".",
"String",
"(",
")",
",",
"privKey",
".",
"ID",
"(",
")",
")",
"\n",
"pubKey",
":=",
"data",
".",
"PublicKeyFromPrivate",
"(",
"privKey",
")",
"\n\n",
"return",
"pubKey",
",",
"cs",
".",
"AddKey",
"(",
"role",
",",
"gun",
",",
"privKey",
")",
"\n",
"}"
] |
// Create is used to generate keys for targets, snapshots and timestamps
|
[
"Create",
"is",
"used",
"to",
"generate",
"keys",
"for",
"targets",
"snapshots",
"and",
"timestamps"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L41-L54
|
train
|
theupdateframework/notary
|
cryptoservice/crypto_service.go
|
GetPrivateKey
|
func (cs *CryptoService) GetPrivateKey(keyID string) (k data.PrivateKey, role data.RoleName, err error) {
for _, ks := range cs.keyStores {
if k, role, err = ks.GetKey(keyID); err == nil {
return
}
switch err.(type) {
case trustmanager.ErrPasswordInvalid, trustmanager.ErrAttemptsExceeded:
return
default:
continue
}
}
return // returns whatever the final values were
}
|
go
|
func (cs *CryptoService) GetPrivateKey(keyID string) (k data.PrivateKey, role data.RoleName, err error) {
for _, ks := range cs.keyStores {
if k, role, err = ks.GetKey(keyID); err == nil {
return
}
switch err.(type) {
case trustmanager.ErrPasswordInvalid, trustmanager.ErrAttemptsExceeded:
return
default:
continue
}
}
return // returns whatever the final values were
}
|
[
"func",
"(",
"cs",
"*",
"CryptoService",
")",
"GetPrivateKey",
"(",
"keyID",
"string",
")",
"(",
"k",
"data",
".",
"PrivateKey",
",",
"role",
"data",
".",
"RoleName",
",",
"err",
"error",
")",
"{",
"for",
"_",
",",
"ks",
":=",
"range",
"cs",
".",
"keyStores",
"{",
"if",
"k",
",",
"role",
",",
"err",
"=",
"ks",
".",
"GetKey",
"(",
"keyID",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"trustmanager",
".",
"ErrPasswordInvalid",
",",
"trustmanager",
".",
"ErrAttemptsExceeded",
":",
"return",
"\n",
"default",
":",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"// returns whatever the final values were",
"\n",
"}"
] |
// GetPrivateKey returns a private key and role if present by ID.
|
[
"GetPrivateKey",
"returns",
"a",
"private",
"key",
"and",
"role",
"if",
"present",
"by",
"ID",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L57-L70
|
train
|
theupdateframework/notary
|
cryptoservice/crypto_service.go
|
GetKey
|
func (cs *CryptoService) GetKey(keyID string) data.PublicKey {
privKey, _, err := cs.GetPrivateKey(keyID)
if err != nil {
return nil
}
return data.PublicKeyFromPrivate(privKey)
}
|
go
|
func (cs *CryptoService) GetKey(keyID string) data.PublicKey {
privKey, _, err := cs.GetPrivateKey(keyID)
if err != nil {
return nil
}
return data.PublicKeyFromPrivate(privKey)
}
|
[
"func",
"(",
"cs",
"*",
"CryptoService",
")",
"GetKey",
"(",
"keyID",
"string",
")",
"data",
".",
"PublicKey",
"{",
"privKey",
",",
"_",
",",
"err",
":=",
"cs",
".",
"GetPrivateKey",
"(",
"keyID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"data",
".",
"PublicKeyFromPrivate",
"(",
"privKey",
")",
"\n",
"}"
] |
// GetKey returns a key by ID
|
[
"GetKey",
"returns",
"a",
"key",
"by",
"ID"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L73-L79
|
train
|
theupdateframework/notary
|
cryptoservice/crypto_service.go
|
GetKeyInfo
|
func (cs *CryptoService) GetKeyInfo(keyID string) (trustmanager.KeyInfo, error) {
for _, store := range cs.keyStores {
if info, err := store.GetKeyInfo(keyID); err == nil {
return info, nil
}
}
return trustmanager.KeyInfo{}, fmt.Errorf("Could not find info for keyID %s", keyID)
}
|
go
|
func (cs *CryptoService) GetKeyInfo(keyID string) (trustmanager.KeyInfo, error) {
for _, store := range cs.keyStores {
if info, err := store.GetKeyInfo(keyID); err == nil {
return info, nil
}
}
return trustmanager.KeyInfo{}, fmt.Errorf("Could not find info for keyID %s", keyID)
}
|
[
"func",
"(",
"cs",
"*",
"CryptoService",
")",
"GetKeyInfo",
"(",
"keyID",
"string",
")",
"(",
"trustmanager",
".",
"KeyInfo",
",",
"error",
")",
"{",
"for",
"_",
",",
"store",
":=",
"range",
"cs",
".",
"keyStores",
"{",
"if",
"info",
",",
"err",
":=",
"store",
".",
"GetKeyInfo",
"(",
"keyID",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"info",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"trustmanager",
".",
"KeyInfo",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyID",
")",
"\n",
"}"
] |
// GetKeyInfo returns role and GUN info of a key by ID
|
[
"GetKeyInfo",
"returns",
"role",
"and",
"GUN",
"info",
"of",
"a",
"key",
"by",
"ID"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L82-L89
|
train
|
theupdateframework/notary
|
cryptoservice/crypto_service.go
|
RemoveKey
|
func (cs *CryptoService) RemoveKey(keyID string) (err error) {
for _, ks := range cs.keyStores {
ks.RemoveKey(keyID)
}
return // returns whatever the final values were
}
|
go
|
func (cs *CryptoService) RemoveKey(keyID string) (err error) {
for _, ks := range cs.keyStores {
ks.RemoveKey(keyID)
}
return // returns whatever the final values were
}
|
[
"func",
"(",
"cs",
"*",
"CryptoService",
")",
"RemoveKey",
"(",
"keyID",
"string",
")",
"(",
"err",
"error",
")",
"{",
"for",
"_",
",",
"ks",
":=",
"range",
"cs",
".",
"keyStores",
"{",
"ks",
".",
"RemoveKey",
"(",
"keyID",
")",
"\n",
"}",
"\n",
"return",
"// returns whatever the final values were",
"\n",
"}"
] |
// RemoveKey deletes a key by ID
|
[
"RemoveKey",
"deletes",
"a",
"key",
"by",
"ID"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L92-L97
|
train
|
theupdateframework/notary
|
cryptoservice/crypto_service.go
|
AddKey
|
func (cs *CryptoService) AddKey(role data.RoleName, gun data.GUN, key data.PrivateKey) (err error) {
// First check if this key already exists in any of our keystores
for _, ks := range cs.keyStores {
if keyInfo, err := ks.GetKeyInfo(key.ID()); err == nil {
if keyInfo.Role != role {
return fmt.Errorf("key with same ID already exists for role: %s", keyInfo.Role.String())
}
logrus.Debugf("key with same ID %s and role %s already exists", key.ID(), keyInfo.Role.String())
return nil
}
}
// If the key didn't exist in any of our keystores, add and return on the first successful keystore
for _, ks := range cs.keyStores {
// Try to add to this keystore, return if successful
if err = ks.AddKey(trustmanager.KeyInfo{Role: role, Gun: gun}, key); err == nil {
return nil
}
}
return // returns whatever the final values were
}
|
go
|
func (cs *CryptoService) AddKey(role data.RoleName, gun data.GUN, key data.PrivateKey) (err error) {
// First check if this key already exists in any of our keystores
for _, ks := range cs.keyStores {
if keyInfo, err := ks.GetKeyInfo(key.ID()); err == nil {
if keyInfo.Role != role {
return fmt.Errorf("key with same ID already exists for role: %s", keyInfo.Role.String())
}
logrus.Debugf("key with same ID %s and role %s already exists", key.ID(), keyInfo.Role.String())
return nil
}
}
// If the key didn't exist in any of our keystores, add and return on the first successful keystore
for _, ks := range cs.keyStores {
// Try to add to this keystore, return if successful
if err = ks.AddKey(trustmanager.KeyInfo{Role: role, Gun: gun}, key); err == nil {
return nil
}
}
return // returns whatever the final values were
}
|
[
"func",
"(",
"cs",
"*",
"CryptoService",
")",
"AddKey",
"(",
"role",
"data",
".",
"RoleName",
",",
"gun",
"data",
".",
"GUN",
",",
"key",
"data",
".",
"PrivateKey",
")",
"(",
"err",
"error",
")",
"{",
"// First check if this key already exists in any of our keystores",
"for",
"_",
",",
"ks",
":=",
"range",
"cs",
".",
"keyStores",
"{",
"if",
"keyInfo",
",",
"err",
":=",
"ks",
".",
"GetKeyInfo",
"(",
"key",
".",
"ID",
"(",
")",
")",
";",
"err",
"==",
"nil",
"{",
"if",
"keyInfo",
".",
"Role",
"!=",
"role",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyInfo",
".",
"Role",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"key",
".",
"ID",
"(",
")",
",",
"keyInfo",
".",
"Role",
".",
"String",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"// If the key didn't exist in any of our keystores, add and return on the first successful keystore",
"for",
"_",
",",
"ks",
":=",
"range",
"cs",
".",
"keyStores",
"{",
"// Try to add to this keystore, return if successful",
"if",
"err",
"=",
"ks",
".",
"AddKey",
"(",
"trustmanager",
".",
"KeyInfo",
"{",
"Role",
":",
"role",
",",
"Gun",
":",
"gun",
"}",
",",
"key",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"// returns whatever the final values were",
"\n",
"}"
] |
// AddKey adds a private key to a specified role.
// The GUN is inferred from the cryptoservice itself for non-root roles
|
[
"AddKey",
"adds",
"a",
"private",
"key",
"to",
"a",
"specified",
"role",
".",
"The",
"GUN",
"is",
"inferred",
"from",
"the",
"cryptoservice",
"itself",
"for",
"non",
"-",
"root",
"roles"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L101-L120
|
train
|
theupdateframework/notary
|
cryptoservice/crypto_service.go
|
ListKeys
|
func (cs *CryptoService) ListKeys(role data.RoleName) []string {
var res []string
for _, ks := range cs.keyStores {
for k, r := range ks.ListKeys() {
if r.Role == role {
res = append(res, k)
}
}
}
return res
}
|
go
|
func (cs *CryptoService) ListKeys(role data.RoleName) []string {
var res []string
for _, ks := range cs.keyStores {
for k, r := range ks.ListKeys() {
if r.Role == role {
res = append(res, k)
}
}
}
return res
}
|
[
"func",
"(",
"cs",
"*",
"CryptoService",
")",
"ListKeys",
"(",
"role",
"data",
".",
"RoleName",
")",
"[",
"]",
"string",
"{",
"var",
"res",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"ks",
":=",
"range",
"cs",
".",
"keyStores",
"{",
"for",
"k",
",",
"r",
":=",
"range",
"ks",
".",
"ListKeys",
"(",
")",
"{",
"if",
"r",
".",
"Role",
"==",
"role",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"k",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] |
// ListKeys returns a list of key IDs valid for the given role
|
[
"ListKeys",
"returns",
"a",
"list",
"of",
"key",
"IDs",
"valid",
"for",
"the",
"given",
"role"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L123-L133
|
train
|
theupdateframework/notary
|
cryptoservice/crypto_service.go
|
ListAllKeys
|
func (cs *CryptoService) ListAllKeys() map[string]data.RoleName {
res := make(map[string]data.RoleName)
for _, ks := range cs.keyStores {
for k, r := range ks.ListKeys() {
res[k] = r.Role // keys are content addressed so don't care about overwrites
}
}
return res
}
|
go
|
func (cs *CryptoService) ListAllKeys() map[string]data.RoleName {
res := make(map[string]data.RoleName)
for _, ks := range cs.keyStores {
for k, r := range ks.ListKeys() {
res[k] = r.Role // keys are content addressed so don't care about overwrites
}
}
return res
}
|
[
"func",
"(",
"cs",
"*",
"CryptoService",
")",
"ListAllKeys",
"(",
")",
"map",
"[",
"string",
"]",
"data",
".",
"RoleName",
"{",
"res",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"data",
".",
"RoleName",
")",
"\n",
"for",
"_",
",",
"ks",
":=",
"range",
"cs",
".",
"keyStores",
"{",
"for",
"k",
",",
"r",
":=",
"range",
"ks",
".",
"ListKeys",
"(",
")",
"{",
"res",
"[",
"k",
"]",
"=",
"r",
".",
"Role",
"// keys are content addressed so don't care about overwrites",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] |
// ListAllKeys returns a map of key IDs to role
|
[
"ListAllKeys",
"returns",
"a",
"map",
"of",
"key",
"IDs",
"to",
"role"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L136-L144
|
train
|
theupdateframework/notary
|
cryptoservice/crypto_service.go
|
CheckRootKeyIsEncrypted
|
func CheckRootKeyIsEncrypted(pemBytes []byte) error {
block, _ := pem.Decode(pemBytes)
if block == nil {
return ErrNoValidPrivateKey
}
if block.Type == "ENCRYPTED PRIVATE KEY" {
return nil
}
if !notary.FIPSEnabled() && x509.IsEncryptedPEMBlock(block) {
return nil
}
return ErrRootKeyNotEncrypted
}
|
go
|
func CheckRootKeyIsEncrypted(pemBytes []byte) error {
block, _ := pem.Decode(pemBytes)
if block == nil {
return ErrNoValidPrivateKey
}
if block.Type == "ENCRYPTED PRIVATE KEY" {
return nil
}
if !notary.FIPSEnabled() && x509.IsEncryptedPEMBlock(block) {
return nil
}
return ErrRootKeyNotEncrypted
}
|
[
"func",
"CheckRootKeyIsEncrypted",
"(",
"pemBytes",
"[",
"]",
"byte",
")",
"error",
"{",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"pemBytes",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"ErrNoValidPrivateKey",
"\n",
"}",
"\n\n",
"if",
"block",
".",
"Type",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"notary",
".",
"FIPSEnabled",
"(",
")",
"&&",
"x509",
".",
"IsEncryptedPEMBlock",
"(",
"block",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"ErrRootKeyNotEncrypted",
"\n",
"}"
] |
// CheckRootKeyIsEncrypted makes sure the root key is encrypted. We have
// internal assumptions that depend on this.
|
[
"CheckRootKeyIsEncrypted",
"makes",
"sure",
"the",
"root",
"key",
"is",
"encrypted",
".",
"We",
"have",
"internal",
"assumptions",
"that",
"depend",
"on",
"this",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/crypto_service.go#L148-L162
|
train
|
theupdateframework/notary
|
signer/api/rpc_api.go
|
CreateKey
|
func (s *KeyManagementServer) CreateKey(ctx context.Context, req *pb.CreateKeyRequest) (*pb.PublicKey, error) {
service := s.CryptoServices[req.Algorithm]
logger := ctxu.GetLogger(ctx)
if service == nil {
logger.Error("CreateKey: unsupported algorithm: ", req.Algorithm)
return nil, fmt.Errorf("algorithm %s not supported for create key", req.Algorithm)
}
var tufKey data.PublicKey
var err error
tufKey, err = service.Create(data.RoleName(req.Role), data.GUN(req.Gun), req.Algorithm)
if err != nil {
logger.Error("CreateKey: failed to create key: ", err)
return nil, grpc.Errorf(codes.Internal, "Key creation failed")
}
logger.Info("CreateKey: Created KeyID ", tufKey.ID())
return &pb.PublicKey{
KeyInfo: &pb.KeyInfo{
KeyID: &pb.KeyID{ID: tufKey.ID()},
Algorithm: &pb.Algorithm{Algorithm: tufKey.Algorithm()},
},
PublicKey: tufKey.Public(),
}, nil
}
|
go
|
func (s *KeyManagementServer) CreateKey(ctx context.Context, req *pb.CreateKeyRequest) (*pb.PublicKey, error) {
service := s.CryptoServices[req.Algorithm]
logger := ctxu.GetLogger(ctx)
if service == nil {
logger.Error("CreateKey: unsupported algorithm: ", req.Algorithm)
return nil, fmt.Errorf("algorithm %s not supported for create key", req.Algorithm)
}
var tufKey data.PublicKey
var err error
tufKey, err = service.Create(data.RoleName(req.Role), data.GUN(req.Gun), req.Algorithm)
if err != nil {
logger.Error("CreateKey: failed to create key: ", err)
return nil, grpc.Errorf(codes.Internal, "Key creation failed")
}
logger.Info("CreateKey: Created KeyID ", tufKey.ID())
return &pb.PublicKey{
KeyInfo: &pb.KeyInfo{
KeyID: &pb.KeyID{ID: tufKey.ID()},
Algorithm: &pb.Algorithm{Algorithm: tufKey.Algorithm()},
},
PublicKey: tufKey.Public(),
}, nil
}
|
[
"func",
"(",
"s",
"*",
"KeyManagementServer",
")",
"CreateKey",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"pb",
".",
"CreateKeyRequest",
")",
"(",
"*",
"pb",
".",
"PublicKey",
",",
"error",
")",
"{",
"service",
":=",
"s",
".",
"CryptoServices",
"[",
"req",
".",
"Algorithm",
"]",
"\n\n",
"logger",
":=",
"ctxu",
".",
"GetLogger",
"(",
"ctx",
")",
"\n\n",
"if",
"service",
"==",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"req",
".",
"Algorithm",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"req",
".",
"Algorithm",
")",
"\n",
"}",
"\n\n",
"var",
"tufKey",
"data",
".",
"PublicKey",
"\n",
"var",
"err",
"error",
"\n\n",
"tufKey",
",",
"err",
"=",
"service",
".",
"Create",
"(",
"data",
".",
"RoleName",
"(",
"req",
".",
"Role",
")",
",",
"data",
".",
"GUN",
"(",
"req",
".",
"Gun",
")",
",",
"req",
".",
"Algorithm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"tufKey",
".",
"ID",
"(",
")",
")",
"\n\n",
"return",
"&",
"pb",
".",
"PublicKey",
"{",
"KeyInfo",
":",
"&",
"pb",
".",
"KeyInfo",
"{",
"KeyID",
":",
"&",
"pb",
".",
"KeyID",
"{",
"ID",
":",
"tufKey",
".",
"ID",
"(",
")",
"}",
",",
"Algorithm",
":",
"&",
"pb",
".",
"Algorithm",
"{",
"Algorithm",
":",
"tufKey",
".",
"Algorithm",
"(",
")",
"}",
",",
"}",
",",
"PublicKey",
":",
"tufKey",
".",
"Public",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] |
//CreateKey returns a PublicKey created using KeyManagementServer's SigningService
|
[
"CreateKey",
"returns",
"a",
"PublicKey",
"created",
"using",
"KeyManagementServer",
"s",
"SigningService"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/api/rpc_api.go#L30-L57
|
train
|
theupdateframework/notary
|
signer/api/rpc_api.go
|
DeleteKey
|
func (s *KeyManagementServer) DeleteKey(ctx context.Context, keyID *pb.KeyID) (*pb.Void, error) {
logger := ctxu.GetLogger(ctx)
// delete key ID from all services
for _, service := range s.CryptoServices {
if err := service.RemoveKey(keyID.ID); err != nil {
logger.Errorf("Failed to delete key %s", keyID.ID)
return nil, grpc.Errorf(codes.Internal, "Key deletion for KeyID %s failed", keyID.ID)
}
}
return &pb.Void{}, nil
}
|
go
|
func (s *KeyManagementServer) DeleteKey(ctx context.Context, keyID *pb.KeyID) (*pb.Void, error) {
logger := ctxu.GetLogger(ctx)
// delete key ID from all services
for _, service := range s.CryptoServices {
if err := service.RemoveKey(keyID.ID); err != nil {
logger.Errorf("Failed to delete key %s", keyID.ID)
return nil, grpc.Errorf(codes.Internal, "Key deletion for KeyID %s failed", keyID.ID)
}
}
return &pb.Void{}, nil
}
|
[
"func",
"(",
"s",
"*",
"KeyManagementServer",
")",
"DeleteKey",
"(",
"ctx",
"context",
".",
"Context",
",",
"keyID",
"*",
"pb",
".",
"KeyID",
")",
"(",
"*",
"pb",
".",
"Void",
",",
"error",
")",
"{",
"logger",
":=",
"ctxu",
".",
"GetLogger",
"(",
"ctx",
")",
"\n",
"// delete key ID from all services",
"for",
"_",
",",
"service",
":=",
"range",
"s",
".",
"CryptoServices",
"{",
"if",
"err",
":=",
"service",
".",
"RemoveKey",
"(",
"keyID",
".",
"ID",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyID",
".",
"ID",
")",
"\n",
"return",
"nil",
",",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
",",
"keyID",
".",
"ID",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"pb",
".",
"Void",
"{",
"}",
",",
"nil",
"\n",
"}"
] |
//DeleteKey deletes they key associated with a KeyID
|
[
"DeleteKey",
"deletes",
"they",
"key",
"associated",
"with",
"a",
"KeyID"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/api/rpc_api.go#L60-L71
|
train
|
theupdateframework/notary
|
signer/api/rpc_api.go
|
GetKeyInfo
|
func (s *KeyManagementServer) GetKeyInfo(ctx context.Context, keyID *pb.KeyID) (*pb.GetKeyInfoResponse, error) {
privKey, role, err := findKeyByID(s.CryptoServices, keyID)
logger := ctxu.GetLogger(ctx)
if err != nil {
logger.Errorf("GetKeyInfo: key %s not found", keyID.ID)
return nil, grpc.Errorf(codes.NotFound, "key %s not found", keyID.ID)
}
logger.Debug("GetKeyInfo: Returning PublicKey for KeyID ", keyID.ID)
return &pb.GetKeyInfoResponse{
KeyInfo: &pb.KeyInfo{
KeyID: &pb.KeyID{ID: privKey.ID()},
Algorithm: &pb.Algorithm{Algorithm: privKey.Algorithm()},
},
PublicKey: privKey.Public(),
Role: role.String(),
}, nil
}
|
go
|
func (s *KeyManagementServer) GetKeyInfo(ctx context.Context, keyID *pb.KeyID) (*pb.GetKeyInfoResponse, error) {
privKey, role, err := findKeyByID(s.CryptoServices, keyID)
logger := ctxu.GetLogger(ctx)
if err != nil {
logger.Errorf("GetKeyInfo: key %s not found", keyID.ID)
return nil, grpc.Errorf(codes.NotFound, "key %s not found", keyID.ID)
}
logger.Debug("GetKeyInfo: Returning PublicKey for KeyID ", keyID.ID)
return &pb.GetKeyInfoResponse{
KeyInfo: &pb.KeyInfo{
KeyID: &pb.KeyID{ID: privKey.ID()},
Algorithm: &pb.Algorithm{Algorithm: privKey.Algorithm()},
},
PublicKey: privKey.Public(),
Role: role.String(),
}, nil
}
|
[
"func",
"(",
"s",
"*",
"KeyManagementServer",
")",
"GetKeyInfo",
"(",
"ctx",
"context",
".",
"Context",
",",
"keyID",
"*",
"pb",
".",
"KeyID",
")",
"(",
"*",
"pb",
".",
"GetKeyInfoResponse",
",",
"error",
")",
"{",
"privKey",
",",
"role",
",",
"err",
":=",
"findKeyByID",
"(",
"s",
".",
"CryptoServices",
",",
"keyID",
")",
"\n\n",
"logger",
":=",
"ctxu",
".",
"GetLogger",
"(",
"ctx",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyID",
".",
"ID",
")",
"\n",
"return",
"nil",
",",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"\"",
"\"",
",",
"keyID",
".",
"ID",
")",
"\n",
"}",
"\n\n",
"logger",
".",
"Debug",
"(",
"\"",
"\"",
",",
"keyID",
".",
"ID",
")",
"\n",
"return",
"&",
"pb",
".",
"GetKeyInfoResponse",
"{",
"KeyInfo",
":",
"&",
"pb",
".",
"KeyInfo",
"{",
"KeyID",
":",
"&",
"pb",
".",
"KeyID",
"{",
"ID",
":",
"privKey",
".",
"ID",
"(",
")",
"}",
",",
"Algorithm",
":",
"&",
"pb",
".",
"Algorithm",
"{",
"Algorithm",
":",
"privKey",
".",
"Algorithm",
"(",
")",
"}",
",",
"}",
",",
"PublicKey",
":",
"privKey",
".",
"Public",
"(",
")",
",",
"Role",
":",
"role",
".",
"String",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] |
//GetKeyInfo returns they PublicKey associated with a KeyID
|
[
"GetKeyInfo",
"returns",
"they",
"PublicKey",
"associated",
"with",
"a",
"KeyID"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/api/rpc_api.go#L74-L93
|
train
|
theupdateframework/notary
|
signer/api/rpc_api.go
|
Sign
|
func (s *SignerServer) Sign(ctx context.Context, sr *pb.SignatureRequest) (*pb.Signature, error) {
privKey, _, err := findKeyByID(s.CryptoServices, sr.KeyID)
logger := ctxu.GetLogger(ctx)
switch err.(type) {
case trustmanager.ErrKeyNotFound:
logger.Errorf("Sign: key %s not found", sr.KeyID.ID)
return nil, grpc.Errorf(codes.NotFound, err.Error())
case nil:
break
default:
logger.Errorf("Getting key %s failed: %s", sr.KeyID.ID, err.Error())
return nil, grpc.Errorf(codes.Internal, err.Error())
}
sig, err := privKey.Sign(rand.Reader, sr.Content, nil)
if err != nil {
logger.Errorf("Sign: signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content)
return nil, grpc.Errorf(codes.Internal, "Signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content)
}
logger.Info("Sign: Signed ", string(sr.Content), " with KeyID ", sr.KeyID.ID)
signature := &pb.Signature{
KeyInfo: &pb.KeyInfo{
KeyID: &pb.KeyID{ID: privKey.ID()},
Algorithm: &pb.Algorithm{Algorithm: privKey.Algorithm()},
},
Algorithm: &pb.Algorithm{Algorithm: privKey.SignatureAlgorithm().String()},
Content: sig,
}
return signature, nil
}
|
go
|
func (s *SignerServer) Sign(ctx context.Context, sr *pb.SignatureRequest) (*pb.Signature, error) {
privKey, _, err := findKeyByID(s.CryptoServices, sr.KeyID)
logger := ctxu.GetLogger(ctx)
switch err.(type) {
case trustmanager.ErrKeyNotFound:
logger.Errorf("Sign: key %s not found", sr.KeyID.ID)
return nil, grpc.Errorf(codes.NotFound, err.Error())
case nil:
break
default:
logger.Errorf("Getting key %s failed: %s", sr.KeyID.ID, err.Error())
return nil, grpc.Errorf(codes.Internal, err.Error())
}
sig, err := privKey.Sign(rand.Reader, sr.Content, nil)
if err != nil {
logger.Errorf("Sign: signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content)
return nil, grpc.Errorf(codes.Internal, "Signing failed for KeyID %s on hash %s", sr.KeyID.ID, sr.Content)
}
logger.Info("Sign: Signed ", string(sr.Content), " with KeyID ", sr.KeyID.ID)
signature := &pb.Signature{
KeyInfo: &pb.KeyInfo{
KeyID: &pb.KeyID{ID: privKey.ID()},
Algorithm: &pb.Algorithm{Algorithm: privKey.Algorithm()},
},
Algorithm: &pb.Algorithm{Algorithm: privKey.SignatureAlgorithm().String()},
Content: sig,
}
return signature, nil
}
|
[
"func",
"(",
"s",
"*",
"SignerServer",
")",
"Sign",
"(",
"ctx",
"context",
".",
"Context",
",",
"sr",
"*",
"pb",
".",
"SignatureRequest",
")",
"(",
"*",
"pb",
".",
"Signature",
",",
"error",
")",
"{",
"privKey",
",",
"_",
",",
"err",
":=",
"findKeyByID",
"(",
"s",
".",
"CryptoServices",
",",
"sr",
".",
"KeyID",
")",
"\n\n",
"logger",
":=",
"ctxu",
".",
"GetLogger",
"(",
"ctx",
")",
"\n\n",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"trustmanager",
".",
"ErrKeyNotFound",
":",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sr",
".",
"KeyID",
".",
"ID",
")",
"\n",
"return",
"nil",
",",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"case",
"nil",
":",
"break",
"\n",
"default",
":",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sr",
".",
"KeyID",
".",
"ID",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n\n",
"}",
"\n\n",
"sig",
",",
"err",
":=",
"privKey",
".",
"Sign",
"(",
"rand",
".",
"Reader",
",",
"sr",
".",
"Content",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sr",
".",
"KeyID",
".",
"ID",
",",
"sr",
".",
"Content",
")",
"\n",
"return",
"nil",
",",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
",",
"sr",
".",
"KeyID",
".",
"ID",
",",
"sr",
".",
"Content",
")",
"\n",
"}",
"\n\n",
"logger",
".",
"Info",
"(",
"\"",
"\"",
",",
"string",
"(",
"sr",
".",
"Content",
")",
",",
"\"",
"\"",
",",
"sr",
".",
"KeyID",
".",
"ID",
")",
"\n\n",
"signature",
":=",
"&",
"pb",
".",
"Signature",
"{",
"KeyInfo",
":",
"&",
"pb",
".",
"KeyInfo",
"{",
"KeyID",
":",
"&",
"pb",
".",
"KeyID",
"{",
"ID",
":",
"privKey",
".",
"ID",
"(",
")",
"}",
",",
"Algorithm",
":",
"&",
"pb",
".",
"Algorithm",
"{",
"Algorithm",
":",
"privKey",
".",
"Algorithm",
"(",
")",
"}",
",",
"}",
",",
"Algorithm",
":",
"&",
"pb",
".",
"Algorithm",
"{",
"Algorithm",
":",
"privKey",
".",
"SignatureAlgorithm",
"(",
")",
".",
"String",
"(",
")",
"}",
",",
"Content",
":",
"sig",
",",
"}",
"\n\n",
"return",
"signature",
",",
"nil",
"\n",
"}"
] |
//Sign signs a message and returns the signature using a private key associate with the KeyID from the SignatureRequest
|
[
"Sign",
"signs",
"a",
"message",
"and",
"returns",
"the",
"signature",
"using",
"a",
"private",
"key",
"associate",
"with",
"the",
"KeyID",
"from",
"the",
"SignatureRequest"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/api/rpc_api.go#L96-L131
|
train
|
theupdateframework/notary
|
cmd/notary/tuf.go
|
getTargetCustom
|
func getTargetCustom(targetCustomFilename string) (*canonicaljson.RawMessage, error) {
targetCustom := new(canonicaljson.RawMessage)
rawTargetCustom, err := ioutil.ReadFile(targetCustomFilename)
if err != nil {
return nil, err
}
if err := targetCustom.UnmarshalJSON(rawTargetCustom); err != nil {
return nil, err
}
return targetCustom, nil
}
|
go
|
func getTargetCustom(targetCustomFilename string) (*canonicaljson.RawMessage, error) {
targetCustom := new(canonicaljson.RawMessage)
rawTargetCustom, err := ioutil.ReadFile(targetCustomFilename)
if err != nil {
return nil, err
}
if err := targetCustom.UnmarshalJSON(rawTargetCustom); err != nil {
return nil, err
}
return targetCustom, nil
}
|
[
"func",
"getTargetCustom",
"(",
"targetCustomFilename",
"string",
")",
"(",
"*",
"canonicaljson",
".",
"RawMessage",
",",
"error",
")",
"{",
"targetCustom",
":=",
"new",
"(",
"canonicaljson",
".",
"RawMessage",
")",
"\n",
"rawTargetCustom",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"targetCustomFilename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"targetCustom",
".",
"UnmarshalJSON",
"(",
"rawTargetCustom",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"targetCustom",
",",
"nil",
"\n",
"}"
] |
// Open and read a file containing the targetCustom data
|
[
"Open",
"and",
"read",
"a",
"file",
"containing",
"the",
"targetCustom",
"data"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/tuf.go#L256-L267
|
train
|
theupdateframework/notary
|
cmd/notary/tuf.go
|
importRootKey
|
func importRootKey(cmd *cobra.Command, rootKey string, nRepo notaryclient.Repository, retriever notary.PassRetriever) ([]string, error) {
var rootKeyList []string
if rootKey != "" {
privKey, err := readKey(data.CanonicalRootRole, rootKey, retriever)
if err != nil {
return nil, err
}
// add root key to repo
err = nRepo.GetCryptoService().AddKey(data.CanonicalRootRole, "", privKey)
if err != nil {
return nil, fmt.Errorf("Error importing key: %v", err)
}
rootKeyList = []string{privKey.ID()}
} else {
rootKeyList = nRepo.GetCryptoService().ListKeys(data.CanonicalRootRole)
}
if len(rootKeyList) > 0 {
// Chooses the first root key available, which is initialization specific
// but should return the HW one first.
rootKeyID := rootKeyList[0]
cmd.Printf("Root key found, using: %s\n", rootKeyID)
return []string{rootKeyID}, nil
}
return []string{}, nil
}
|
go
|
func importRootKey(cmd *cobra.Command, rootKey string, nRepo notaryclient.Repository, retriever notary.PassRetriever) ([]string, error) {
var rootKeyList []string
if rootKey != "" {
privKey, err := readKey(data.CanonicalRootRole, rootKey, retriever)
if err != nil {
return nil, err
}
// add root key to repo
err = nRepo.GetCryptoService().AddKey(data.CanonicalRootRole, "", privKey)
if err != nil {
return nil, fmt.Errorf("Error importing key: %v", err)
}
rootKeyList = []string{privKey.ID()}
} else {
rootKeyList = nRepo.GetCryptoService().ListKeys(data.CanonicalRootRole)
}
if len(rootKeyList) > 0 {
// Chooses the first root key available, which is initialization specific
// but should return the HW one first.
rootKeyID := rootKeyList[0]
cmd.Printf("Root key found, using: %s\n", rootKeyID)
return []string{rootKeyID}, nil
}
return []string{}, nil
}
|
[
"func",
"importRootKey",
"(",
"cmd",
"*",
"cobra",
".",
"Command",
",",
"rootKey",
"string",
",",
"nRepo",
"notaryclient",
".",
"Repository",
",",
"retriever",
"notary",
".",
"PassRetriever",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"rootKeyList",
"[",
"]",
"string",
"\n\n",
"if",
"rootKey",
"!=",
"\"",
"\"",
"{",
"privKey",
",",
"err",
":=",
"readKey",
"(",
"data",
".",
"CanonicalRootRole",
",",
"rootKey",
",",
"retriever",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// add root key to repo",
"err",
"=",
"nRepo",
".",
"GetCryptoService",
"(",
")",
".",
"AddKey",
"(",
"data",
".",
"CanonicalRootRole",
",",
"\"",
"\"",
",",
"privKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"rootKeyList",
"=",
"[",
"]",
"string",
"{",
"privKey",
".",
"ID",
"(",
")",
"}",
"\n",
"}",
"else",
"{",
"rootKeyList",
"=",
"nRepo",
".",
"GetCryptoService",
"(",
")",
".",
"ListKeys",
"(",
"data",
".",
"CanonicalRootRole",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"rootKeyList",
")",
">",
"0",
"{",
"// Chooses the first root key available, which is initialization specific",
"// but should return the HW one first.",
"rootKeyID",
":=",
"rootKeyList",
"[",
"0",
"]",
"\n",
"cmd",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"rootKeyID",
")",
"\n\n",
"return",
"[",
"]",
"string",
"{",
"rootKeyID",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"nil",
"\n",
"}"
] |
// importRootKey imports the root key from path then adds the key to repo
// returns key ids
|
[
"importRootKey",
"imports",
"the",
"root",
"key",
"from",
"path",
"then",
"adds",
"the",
"key",
"to",
"repo",
"returns",
"key",
"ids"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/tuf.go#L413-L441
|
train
|
theupdateframework/notary
|
cmd/notary/tuf.go
|
importRootCert
|
func importRootCert(certFilePath string) ([]data.PublicKey, error) {
publicKeys := make([]data.PublicKey, 0, 1)
if certFilePath == "" {
return publicKeys, nil
}
// read certificate from file
certPEM, err := ioutil.ReadFile(certFilePath)
if err != nil {
return nil, fmt.Errorf("error reading certificate file: %v", err)
}
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
return nil, fmt.Errorf("the provided file does not contain a valid PEM certificate %v", err)
}
// convert the file to data.PublicKey
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("Parsing certificate PEM bytes to x509 certificate: %v", err)
}
publicKeys = append(publicKeys, tufutils.CertToKey(cert))
return publicKeys, nil
}
|
go
|
func importRootCert(certFilePath string) ([]data.PublicKey, error) {
publicKeys := make([]data.PublicKey, 0, 1)
if certFilePath == "" {
return publicKeys, nil
}
// read certificate from file
certPEM, err := ioutil.ReadFile(certFilePath)
if err != nil {
return nil, fmt.Errorf("error reading certificate file: %v", err)
}
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
return nil, fmt.Errorf("the provided file does not contain a valid PEM certificate %v", err)
}
// convert the file to data.PublicKey
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("Parsing certificate PEM bytes to x509 certificate: %v", err)
}
publicKeys = append(publicKeys, tufutils.CertToKey(cert))
return publicKeys, nil
}
|
[
"func",
"importRootCert",
"(",
"certFilePath",
"string",
")",
"(",
"[",
"]",
"data",
".",
"PublicKey",
",",
"error",
")",
"{",
"publicKeys",
":=",
"make",
"(",
"[",
"]",
"data",
".",
"PublicKey",
",",
"0",
",",
"1",
")",
"\n\n",
"if",
"certFilePath",
"==",
"\"",
"\"",
"{",
"return",
"publicKeys",
",",
"nil",
"\n",
"}",
"\n\n",
"// read certificate from file",
"certPEM",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"certFilePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"[",
"]",
"byte",
"(",
"certPEM",
")",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// convert the file to data.PublicKey",
"cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"block",
".",
"Bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"publicKeys",
"=",
"append",
"(",
"publicKeys",
",",
"tufutils",
".",
"CertToKey",
"(",
"cert",
")",
")",
"\n\n",
"return",
"publicKeys",
",",
"nil",
"\n",
"}"
] |
// importRootCert imports the base64 encoded public certificate corresponding to the root key
// returns empty slice if path is empty
|
[
"importRootCert",
"imports",
"the",
"base64",
"encoded",
"public",
"certificate",
"corresponding",
"to",
"the",
"root",
"key",
"returns",
"empty",
"slice",
"if",
"path",
"is",
"empty"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/tuf.go#L445-L470
|
train
|
theupdateframework/notary
|
cmd/notary/tuf.go
|
readKey
|
func readKey(role data.RoleName, keyFilename string, retriever notary.PassRetriever) (data.PrivateKey, error) {
pemBytes, err := ioutil.ReadFile(keyFilename)
if err != nil {
return nil, fmt.Errorf("Error reading input root key file: %v", err)
}
isEncrypted := true
if err = cryptoservice.CheckRootKeyIsEncrypted(pemBytes); err != nil {
if role == data.CanonicalRootRole {
return nil, err
}
isEncrypted = false
}
var privKey data.PrivateKey
if isEncrypted {
privKey, _, err = trustmanager.GetPasswdDecryptBytes(retriever, pemBytes, "", data.CanonicalRootRole.String())
} else {
privKey, err = tufutils.ParsePEMPrivateKey(pemBytes, "")
}
if err != nil {
return nil, err
}
return privKey, nil
}
|
go
|
func readKey(role data.RoleName, keyFilename string, retriever notary.PassRetriever) (data.PrivateKey, error) {
pemBytes, err := ioutil.ReadFile(keyFilename)
if err != nil {
return nil, fmt.Errorf("Error reading input root key file: %v", err)
}
isEncrypted := true
if err = cryptoservice.CheckRootKeyIsEncrypted(pemBytes); err != nil {
if role == data.CanonicalRootRole {
return nil, err
}
isEncrypted = false
}
var privKey data.PrivateKey
if isEncrypted {
privKey, _, err = trustmanager.GetPasswdDecryptBytes(retriever, pemBytes, "", data.CanonicalRootRole.String())
} else {
privKey, err = tufutils.ParsePEMPrivateKey(pemBytes, "")
}
if err != nil {
return nil, err
}
return privKey, nil
}
|
[
"func",
"readKey",
"(",
"role",
"data",
".",
"RoleName",
",",
"keyFilename",
"string",
",",
"retriever",
"notary",
".",
"PassRetriever",
")",
"(",
"data",
".",
"PrivateKey",
",",
"error",
")",
"{",
"pemBytes",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"keyFilename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"isEncrypted",
":=",
"true",
"\n",
"if",
"err",
"=",
"cryptoservice",
".",
"CheckRootKeyIsEncrypted",
"(",
"pemBytes",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"role",
"==",
"data",
".",
"CanonicalRootRole",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"isEncrypted",
"=",
"false",
"\n",
"}",
"\n",
"var",
"privKey",
"data",
".",
"PrivateKey",
"\n",
"if",
"isEncrypted",
"{",
"privKey",
",",
"_",
",",
"err",
"=",
"trustmanager",
".",
"GetPasswdDecryptBytes",
"(",
"retriever",
",",
"pemBytes",
",",
"\"",
"\"",
",",
"data",
".",
"CanonicalRootRole",
".",
"String",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"privKey",
",",
"err",
"=",
"tufutils",
".",
"ParsePEMPrivateKey",
"(",
"pemBytes",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"privKey",
",",
"nil",
"\n",
"}"
] |
// Attempt to read a role key from a file, and return it as a data.PrivateKey
// If key is for the Root role, it must be encrypted
|
[
"Attempt",
"to",
"read",
"a",
"role",
"key",
"from",
"a",
"file",
"and",
"return",
"it",
"as",
"a",
"data",
".",
"PrivateKey",
"If",
"key",
"is",
"for",
"the",
"Root",
"role",
"it",
"must",
"be",
"encrypted"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/tuf.go#L514-L537
|
train
|
theupdateframework/notary
|
server/handlers/validation.go
|
validateUpdate
|
func validateUpdate(cs signed.CryptoService, gun data.GUN, updates []storage.MetaUpdate, store storage.MetaStore) ([]storage.MetaUpdate, error) {
// some delegated targets role may be invalid based on other updates
// that have been made by other clients. We'll rebuild the slice of
// updates with only the things we should actually update
updatesToApply := make([]storage.MetaUpdate, 0, len(updates))
roles := make(map[data.RoleName]storage.MetaUpdate)
for _, v := range updates {
roles[v.Role] = v
}
builder := tuf.NewRepoBuilder(gun, cs, trustpinning.TrustPinConfig{})
if err := loadFromStore(gun, data.CanonicalRootRole, builder, store); err != nil {
if _, ok := err.(storage.ErrNotFound); !ok {
return nil, err
}
}
if rootUpdate, ok := roles[data.CanonicalRootRole]; ok {
currentRootVersion := builder.GetLoadedVersion(data.CanonicalRootRole)
if rootUpdate.Version != currentRootVersion && rootUpdate.Version != currentRootVersion+1 {
msg := fmt.Sprintf("Root modifications must increment the version. Current %d, new %d", currentRootVersion, rootUpdate.Version)
return nil, validation.ErrBadRoot{Msg: msg}
}
builder = builder.BootstrapNewBuilder()
if err := builder.Load(data.CanonicalRootRole, rootUpdate.Data, currentRootVersion, false); err != nil {
return nil, validation.ErrBadRoot{Msg: err.Error()}
}
logrus.Debug("Successfully validated root")
updatesToApply = append(updatesToApply, rootUpdate)
} else if !builder.IsLoaded(data.CanonicalRootRole) {
return nil, validation.ErrValidation{Msg: "no pre-existing root and no root provided in update."}
}
targetsToUpdate, err := loadAndValidateTargets(gun, builder, roles, store)
if err != nil {
return nil, err
}
updatesToApply = append(updatesToApply, targetsToUpdate...)
// there's no need to load files from the database if no targets etc...
// were uploaded because that means they haven't been updated and
// the snapshot will already contain the correct hashes and sizes for
// those targets (incl. delegated targets)
logrus.Debug("Successfully validated targets")
// At this point, root and targets must have been loaded into the repo
if snapshotUpdate, ok := roles[data.CanonicalSnapshotRole]; ok {
if err := builder.Load(data.CanonicalSnapshotRole, snapshotUpdate.Data, 1, false); err != nil {
return nil, validation.ErrBadSnapshot{Msg: err.Error()}
}
logrus.Debug("Successfully validated snapshot")
updatesToApply = append(updatesToApply, roles[data.CanonicalSnapshotRole])
} else {
// Check:
// - we have a snapshot key
// - it matches a snapshot key signed into the root.json
// Then:
// - generate a new snapshot
// - add it to the updates
update, err := generateSnapshot(gun, builder, store)
if err != nil {
return nil, err
}
updatesToApply = append(updatesToApply, *update)
}
// generate a timestamp immediately
update, err := generateTimestamp(gun, builder, store)
if err != nil {
return nil, err
}
return append(updatesToApply, *update), nil
}
|
go
|
func validateUpdate(cs signed.CryptoService, gun data.GUN, updates []storage.MetaUpdate, store storage.MetaStore) ([]storage.MetaUpdate, error) {
// some delegated targets role may be invalid based on other updates
// that have been made by other clients. We'll rebuild the slice of
// updates with only the things we should actually update
updatesToApply := make([]storage.MetaUpdate, 0, len(updates))
roles := make(map[data.RoleName]storage.MetaUpdate)
for _, v := range updates {
roles[v.Role] = v
}
builder := tuf.NewRepoBuilder(gun, cs, trustpinning.TrustPinConfig{})
if err := loadFromStore(gun, data.CanonicalRootRole, builder, store); err != nil {
if _, ok := err.(storage.ErrNotFound); !ok {
return nil, err
}
}
if rootUpdate, ok := roles[data.CanonicalRootRole]; ok {
currentRootVersion := builder.GetLoadedVersion(data.CanonicalRootRole)
if rootUpdate.Version != currentRootVersion && rootUpdate.Version != currentRootVersion+1 {
msg := fmt.Sprintf("Root modifications must increment the version. Current %d, new %d", currentRootVersion, rootUpdate.Version)
return nil, validation.ErrBadRoot{Msg: msg}
}
builder = builder.BootstrapNewBuilder()
if err := builder.Load(data.CanonicalRootRole, rootUpdate.Data, currentRootVersion, false); err != nil {
return nil, validation.ErrBadRoot{Msg: err.Error()}
}
logrus.Debug("Successfully validated root")
updatesToApply = append(updatesToApply, rootUpdate)
} else if !builder.IsLoaded(data.CanonicalRootRole) {
return nil, validation.ErrValidation{Msg: "no pre-existing root and no root provided in update."}
}
targetsToUpdate, err := loadAndValidateTargets(gun, builder, roles, store)
if err != nil {
return nil, err
}
updatesToApply = append(updatesToApply, targetsToUpdate...)
// there's no need to load files from the database if no targets etc...
// were uploaded because that means they haven't been updated and
// the snapshot will already contain the correct hashes and sizes for
// those targets (incl. delegated targets)
logrus.Debug("Successfully validated targets")
// At this point, root and targets must have been loaded into the repo
if snapshotUpdate, ok := roles[data.CanonicalSnapshotRole]; ok {
if err := builder.Load(data.CanonicalSnapshotRole, snapshotUpdate.Data, 1, false); err != nil {
return nil, validation.ErrBadSnapshot{Msg: err.Error()}
}
logrus.Debug("Successfully validated snapshot")
updatesToApply = append(updatesToApply, roles[data.CanonicalSnapshotRole])
} else {
// Check:
// - we have a snapshot key
// - it matches a snapshot key signed into the root.json
// Then:
// - generate a new snapshot
// - add it to the updates
update, err := generateSnapshot(gun, builder, store)
if err != nil {
return nil, err
}
updatesToApply = append(updatesToApply, *update)
}
// generate a timestamp immediately
update, err := generateTimestamp(gun, builder, store)
if err != nil {
return nil, err
}
return append(updatesToApply, *update), nil
}
|
[
"func",
"validateUpdate",
"(",
"cs",
"signed",
".",
"CryptoService",
",",
"gun",
"data",
".",
"GUN",
",",
"updates",
"[",
"]",
"storage",
".",
"MetaUpdate",
",",
"store",
"storage",
".",
"MetaStore",
")",
"(",
"[",
"]",
"storage",
".",
"MetaUpdate",
",",
"error",
")",
"{",
"// some delegated targets role may be invalid based on other updates",
"// that have been made by other clients. We'll rebuild the slice of",
"// updates with only the things we should actually update",
"updatesToApply",
":=",
"make",
"(",
"[",
"]",
"storage",
".",
"MetaUpdate",
",",
"0",
",",
"len",
"(",
"updates",
")",
")",
"\n\n",
"roles",
":=",
"make",
"(",
"map",
"[",
"data",
".",
"RoleName",
"]",
"storage",
".",
"MetaUpdate",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"updates",
"{",
"roles",
"[",
"v",
".",
"Role",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"builder",
":=",
"tuf",
".",
"NewRepoBuilder",
"(",
"gun",
",",
"cs",
",",
"trustpinning",
".",
"TrustPinConfig",
"{",
"}",
")",
"\n",
"if",
"err",
":=",
"loadFromStore",
"(",
"gun",
",",
"data",
".",
"CanonicalRootRole",
",",
"builder",
",",
"store",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"storage",
".",
"ErrNotFound",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"rootUpdate",
",",
"ok",
":=",
"roles",
"[",
"data",
".",
"CanonicalRootRole",
"]",
";",
"ok",
"{",
"currentRootVersion",
":=",
"builder",
".",
"GetLoadedVersion",
"(",
"data",
".",
"CanonicalRootRole",
")",
"\n",
"if",
"rootUpdate",
".",
"Version",
"!=",
"currentRootVersion",
"&&",
"rootUpdate",
".",
"Version",
"!=",
"currentRootVersion",
"+",
"1",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"currentRootVersion",
",",
"rootUpdate",
".",
"Version",
")",
"\n",
"return",
"nil",
",",
"validation",
".",
"ErrBadRoot",
"{",
"Msg",
":",
"msg",
"}",
"\n",
"}",
"\n",
"builder",
"=",
"builder",
".",
"BootstrapNewBuilder",
"(",
")",
"\n",
"if",
"err",
":=",
"builder",
".",
"Load",
"(",
"data",
".",
"CanonicalRootRole",
",",
"rootUpdate",
".",
"Data",
",",
"currentRootVersion",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"validation",
".",
"ErrBadRoot",
"{",
"Msg",
":",
"err",
".",
"Error",
"(",
")",
"}",
"\n",
"}",
"\n\n",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"updatesToApply",
"=",
"append",
"(",
"updatesToApply",
",",
"rootUpdate",
")",
"\n",
"}",
"else",
"if",
"!",
"builder",
".",
"IsLoaded",
"(",
"data",
".",
"CanonicalRootRole",
")",
"{",
"return",
"nil",
",",
"validation",
".",
"ErrValidation",
"{",
"Msg",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n\n",
"targetsToUpdate",
",",
"err",
":=",
"loadAndValidateTargets",
"(",
"gun",
",",
"builder",
",",
"roles",
",",
"store",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"updatesToApply",
"=",
"append",
"(",
"updatesToApply",
",",
"targetsToUpdate",
"...",
")",
"\n",
"// there's no need to load files from the database if no targets etc...",
"// were uploaded because that means they haven't been updated and",
"// the snapshot will already contain the correct hashes and sizes for",
"// those targets (incl. delegated targets)",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"// At this point, root and targets must have been loaded into the repo",
"if",
"snapshotUpdate",
",",
"ok",
":=",
"roles",
"[",
"data",
".",
"CanonicalSnapshotRole",
"]",
";",
"ok",
"{",
"if",
"err",
":=",
"builder",
".",
"Load",
"(",
"data",
".",
"CanonicalSnapshotRole",
",",
"snapshotUpdate",
".",
"Data",
",",
"1",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"validation",
".",
"ErrBadSnapshot",
"{",
"Msg",
":",
"err",
".",
"Error",
"(",
")",
"}",
"\n",
"}",
"\n",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"updatesToApply",
"=",
"append",
"(",
"updatesToApply",
",",
"roles",
"[",
"data",
".",
"CanonicalSnapshotRole",
"]",
")",
"\n",
"}",
"else",
"{",
"// Check:",
"// - we have a snapshot key",
"// - it matches a snapshot key signed into the root.json",
"// Then:",
"// - generate a new snapshot",
"// - add it to the updates",
"update",
",",
"err",
":=",
"generateSnapshot",
"(",
"gun",
",",
"builder",
",",
"store",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"updatesToApply",
"=",
"append",
"(",
"updatesToApply",
",",
"*",
"update",
")",
"\n",
"}",
"\n\n",
"// generate a timestamp immediately",
"update",
",",
"err",
":=",
"generateTimestamp",
"(",
"gun",
",",
"builder",
",",
"store",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"append",
"(",
"updatesToApply",
",",
"*",
"update",
")",
",",
"nil",
"\n",
"}"
] |
// validateUpload checks that the updates being pushed
// are semantically correct and the signatures are correct
// A list of possibly modified updates are returned if all
// validation was successful. This allows the snapshot to be
// created and added if snapshotting has been delegated to the
// server
|
[
"validateUpload",
"checks",
"that",
"the",
"updates",
"being",
"pushed",
"are",
"semantically",
"correct",
"and",
"the",
"signatures",
"are",
"correct",
"A",
"list",
"of",
"possibly",
"modified",
"updates",
"are",
"returned",
"if",
"all",
"validation",
"was",
"successful",
".",
"This",
"allows",
"the",
"snapshot",
"to",
"be",
"created",
"and",
"added",
"if",
"snapshotting",
"has",
"been",
"delegated",
"to",
"the",
"server"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/validation.go#L25-L99
|
train
|
theupdateframework/notary
|
server/handlers/validation.go
|
generateSnapshot
|
func generateSnapshot(gun data.GUN, builder tuf.RepoBuilder, store storage.MetaStore) (*storage.MetaUpdate, error) {
var prev *data.SignedSnapshot
_, currentJSON, err := store.GetCurrent(gun, data.CanonicalSnapshotRole)
if err == nil {
prev = new(data.SignedSnapshot)
if err = json.Unmarshal(currentJSON, prev); err != nil {
logrus.Error("Failed to unmarshal existing snapshot for GUN ", gun)
return nil, err
}
}
if _, ok := err.(storage.ErrNotFound); !ok && err != nil {
return nil, err
}
meta, ver, err := builder.GenerateSnapshot(prev)
switch err.(type) {
case nil:
return &storage.MetaUpdate{
Role: data.CanonicalSnapshotRole,
Version: ver,
Data: meta,
}, nil
case signed.ErrInsufficientSignatures, signed.ErrNoKeys, signed.ErrRoleThreshold:
// If we cannot sign the snapshot, then we don't have keys for the snapshot,
// and the client should have submitted a snapshot
return nil, validation.ErrBadHierarchy{
Missing: data.CanonicalSnapshotRole.String(),
Msg: "no snapshot was included in update and server does not hold current snapshot key for repository"}
default:
return nil, validation.ErrValidation{Msg: err.Error()}
}
}
|
go
|
func generateSnapshot(gun data.GUN, builder tuf.RepoBuilder, store storage.MetaStore) (*storage.MetaUpdate, error) {
var prev *data.SignedSnapshot
_, currentJSON, err := store.GetCurrent(gun, data.CanonicalSnapshotRole)
if err == nil {
prev = new(data.SignedSnapshot)
if err = json.Unmarshal(currentJSON, prev); err != nil {
logrus.Error("Failed to unmarshal existing snapshot for GUN ", gun)
return nil, err
}
}
if _, ok := err.(storage.ErrNotFound); !ok && err != nil {
return nil, err
}
meta, ver, err := builder.GenerateSnapshot(prev)
switch err.(type) {
case nil:
return &storage.MetaUpdate{
Role: data.CanonicalSnapshotRole,
Version: ver,
Data: meta,
}, nil
case signed.ErrInsufficientSignatures, signed.ErrNoKeys, signed.ErrRoleThreshold:
// If we cannot sign the snapshot, then we don't have keys for the snapshot,
// and the client should have submitted a snapshot
return nil, validation.ErrBadHierarchy{
Missing: data.CanonicalSnapshotRole.String(),
Msg: "no snapshot was included in update and server does not hold current snapshot key for repository"}
default:
return nil, validation.ErrValidation{Msg: err.Error()}
}
}
|
[
"func",
"generateSnapshot",
"(",
"gun",
"data",
".",
"GUN",
",",
"builder",
"tuf",
".",
"RepoBuilder",
",",
"store",
"storage",
".",
"MetaStore",
")",
"(",
"*",
"storage",
".",
"MetaUpdate",
",",
"error",
")",
"{",
"var",
"prev",
"*",
"data",
".",
"SignedSnapshot",
"\n",
"_",
",",
"currentJSON",
",",
"err",
":=",
"store",
".",
"GetCurrent",
"(",
"gun",
",",
"data",
".",
"CanonicalSnapshotRole",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"prev",
"=",
"new",
"(",
"data",
".",
"SignedSnapshot",
")",
"\n",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"currentJSON",
",",
"prev",
")",
";",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Error",
"(",
"\"",
"\"",
",",
"gun",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"storage",
".",
"ErrNotFound",
")",
";",
"!",
"ok",
"&&",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"meta",
",",
"ver",
",",
"err",
":=",
"builder",
".",
"GenerateSnapshot",
"(",
"prev",
")",
"\n\n",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"return",
"&",
"storage",
".",
"MetaUpdate",
"{",
"Role",
":",
"data",
".",
"CanonicalSnapshotRole",
",",
"Version",
":",
"ver",
",",
"Data",
":",
"meta",
",",
"}",
",",
"nil",
"\n",
"case",
"signed",
".",
"ErrInsufficientSignatures",
",",
"signed",
".",
"ErrNoKeys",
",",
"signed",
".",
"ErrRoleThreshold",
":",
"// If we cannot sign the snapshot, then we don't have keys for the snapshot,",
"// and the client should have submitted a snapshot",
"return",
"nil",
",",
"validation",
".",
"ErrBadHierarchy",
"{",
"Missing",
":",
"data",
".",
"CanonicalSnapshotRole",
".",
"String",
"(",
")",
",",
"Msg",
":",
"\"",
"\"",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"validation",
".",
"ErrValidation",
"{",
"Msg",
":",
"err",
".",
"Error",
"(",
")",
"}",
"\n",
"}",
"\n",
"}"
] |
// generateSnapshot generates a new snapshot from the previous one in the store - this assumes all
// the other roles except timestamp have already been set on the repo, and will set the generated
// snapshot on the repo as well
|
[
"generateSnapshot",
"generates",
"a",
"new",
"snapshot",
"from",
"the",
"previous",
"one",
"in",
"the",
"store",
"-",
"this",
"assumes",
"all",
"the",
"other",
"roles",
"except",
"timestamp",
"have",
"already",
"been",
"set",
"on",
"the",
"repo",
"and",
"will",
"set",
"the",
"generated",
"snapshot",
"on",
"the",
"repo",
"as",
"well"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/validation.go#L152-L185
|
train
|
theupdateframework/notary
|
server/handlers/validation.go
|
generateTimestamp
|
func generateTimestamp(gun data.GUN, builder tuf.RepoBuilder, store storage.MetaStore) (*storage.MetaUpdate, error) {
var prev *data.SignedTimestamp
_, currentJSON, err := store.GetCurrent(gun, data.CanonicalTimestampRole)
switch err.(type) {
case nil:
prev = new(data.SignedTimestamp)
if err := json.Unmarshal(currentJSON, prev); err != nil {
logrus.Error("Failed to unmarshal existing timestamp for GUN ", gun)
return nil, err
}
case storage.ErrNotFound:
break // this is the first timestamp ever for the repo
default:
return nil, err
}
meta, ver, err := builder.GenerateTimestamp(prev)
switch err.(type) {
case nil:
return &storage.MetaUpdate{
Role: data.CanonicalTimestampRole,
Version: ver,
Data: meta,
}, nil
case signed.ErrInsufficientSignatures, signed.ErrNoKeys:
// If we cannot sign the timestamp, then we don't have keys for the timestamp,
// and the client screwed up their root
return nil, validation.ErrBadRoot{
Msg: fmt.Sprintf("no timestamp keys exist on the server"),
}
default:
return nil, validation.ErrValidation{Msg: err.Error()}
}
}
|
go
|
func generateTimestamp(gun data.GUN, builder tuf.RepoBuilder, store storage.MetaStore) (*storage.MetaUpdate, error) {
var prev *data.SignedTimestamp
_, currentJSON, err := store.GetCurrent(gun, data.CanonicalTimestampRole)
switch err.(type) {
case nil:
prev = new(data.SignedTimestamp)
if err := json.Unmarshal(currentJSON, prev); err != nil {
logrus.Error("Failed to unmarshal existing timestamp for GUN ", gun)
return nil, err
}
case storage.ErrNotFound:
break // this is the first timestamp ever for the repo
default:
return nil, err
}
meta, ver, err := builder.GenerateTimestamp(prev)
switch err.(type) {
case nil:
return &storage.MetaUpdate{
Role: data.CanonicalTimestampRole,
Version: ver,
Data: meta,
}, nil
case signed.ErrInsufficientSignatures, signed.ErrNoKeys:
// If we cannot sign the timestamp, then we don't have keys for the timestamp,
// and the client screwed up their root
return nil, validation.ErrBadRoot{
Msg: fmt.Sprintf("no timestamp keys exist on the server"),
}
default:
return nil, validation.ErrValidation{Msg: err.Error()}
}
}
|
[
"func",
"generateTimestamp",
"(",
"gun",
"data",
".",
"GUN",
",",
"builder",
"tuf",
".",
"RepoBuilder",
",",
"store",
"storage",
".",
"MetaStore",
")",
"(",
"*",
"storage",
".",
"MetaUpdate",
",",
"error",
")",
"{",
"var",
"prev",
"*",
"data",
".",
"SignedTimestamp",
"\n",
"_",
",",
"currentJSON",
",",
"err",
":=",
"store",
".",
"GetCurrent",
"(",
"gun",
",",
"data",
".",
"CanonicalTimestampRole",
")",
"\n\n",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"prev",
"=",
"new",
"(",
"data",
".",
"SignedTimestamp",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"currentJSON",
",",
"prev",
")",
";",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Error",
"(",
"\"",
"\"",
",",
"gun",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"case",
"storage",
".",
"ErrNotFound",
":",
"break",
"// this is the first timestamp ever for the repo",
"\n",
"default",
":",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"meta",
",",
"ver",
",",
"err",
":=",
"builder",
".",
"GenerateTimestamp",
"(",
"prev",
")",
"\n\n",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"return",
"&",
"storage",
".",
"MetaUpdate",
"{",
"Role",
":",
"data",
".",
"CanonicalTimestampRole",
",",
"Version",
":",
"ver",
",",
"Data",
":",
"meta",
",",
"}",
",",
"nil",
"\n",
"case",
"signed",
".",
"ErrInsufficientSignatures",
",",
"signed",
".",
"ErrNoKeys",
":",
"// If we cannot sign the timestamp, then we don't have keys for the timestamp,",
"// and the client screwed up their root",
"return",
"nil",
",",
"validation",
".",
"ErrBadRoot",
"{",
"Msg",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
")",
",",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"validation",
".",
"ErrValidation",
"{",
"Msg",
":",
"err",
".",
"Error",
"(",
")",
"}",
"\n",
"}",
"\n",
"}"
] |
// generateTimestamp generates a new timestamp from the previous one in the store - this assumes all
// the other roles have already been set on the repo, and will set the generated timestamp on the repo as well
|
[
"generateTimestamp",
"generates",
"a",
"new",
"timestamp",
"from",
"the",
"previous",
"one",
"in",
"the",
"store",
"-",
"this",
"assumes",
"all",
"the",
"other",
"roles",
"have",
"already",
"been",
"set",
"on",
"the",
"repo",
"and",
"will",
"set",
"the",
"generated",
"timestamp",
"on",
"the",
"repo",
"as",
"well"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/handlers/validation.go#L189-L224
|
train
|
theupdateframework/notary
|
tuf/signed/sign.go
|
Sign
|
func Sign(service CryptoService, s *data.Signed, signingKeys []data.PublicKey,
minSignatures int, otherWhitelistedKeys []data.PublicKey) error {
logrus.Debugf("sign called with %d/%d required keys", minSignatures, len(signingKeys))
signatures := make([]data.Signature, 0, len(s.Signatures)+1)
signingKeyIDs := make(map[string]struct{})
tufIDs := make(map[string]data.PublicKey)
privKeys := make(map[string]data.PrivateKey)
// Get all the private key objects related to the public keys
missingKeyIDs := []string{}
for _, key := range signingKeys {
canonicalID, err := utils.CanonicalKeyID(key)
tufIDs[key.ID()] = key
if err != nil {
return err
}
k, _, err := service.GetPrivateKey(canonicalID)
if err != nil {
if _, ok := err.(trustmanager.ErrKeyNotFound); ok {
missingKeyIDs = append(missingKeyIDs, canonicalID)
continue
}
return err
}
privKeys[key.ID()] = k
}
// include the list of otherWhitelistedKeys
for _, key := range otherWhitelistedKeys {
if _, ok := tufIDs[key.ID()]; !ok {
tufIDs[key.ID()] = key
}
}
// Check to ensure we have enough signing keys
if len(privKeys) < minSignatures {
return ErrInsufficientSignatures{FoundKeys: len(privKeys),
NeededKeys: minSignatures, MissingKeyIDs: missingKeyIDs}
}
emptyStruct := struct{}{}
// Do signing and generate list of signatures
for keyID, pk := range privKeys {
sig, err := pk.Sign(rand.Reader, *s.Signed, nil)
if err != nil {
logrus.Debugf("Failed to sign with key: %s. Reason: %v", keyID, err)
return err
}
signingKeyIDs[keyID] = emptyStruct
signatures = append(signatures, data.Signature{
KeyID: keyID,
Method: pk.SignatureAlgorithm(),
Signature: sig[:],
})
}
for _, sig := range s.Signatures {
if _, ok := signingKeyIDs[sig.KeyID]; ok {
// key is in the set of key IDs for which a signature has been created
continue
}
var (
k data.PublicKey
ok bool
)
if k, ok = tufIDs[sig.KeyID]; !ok {
// key is no longer a valid signing key
continue
}
if err := VerifySignature(*s.Signed, &sig, k); err != nil {
// signature is no longer valid
continue
}
// keep any signatures that still represent valid keys and are
// themselves valid
signatures = append(signatures, sig)
}
s.Signatures = signatures
return nil
}
|
go
|
func Sign(service CryptoService, s *data.Signed, signingKeys []data.PublicKey,
minSignatures int, otherWhitelistedKeys []data.PublicKey) error {
logrus.Debugf("sign called with %d/%d required keys", minSignatures, len(signingKeys))
signatures := make([]data.Signature, 0, len(s.Signatures)+1)
signingKeyIDs := make(map[string]struct{})
tufIDs := make(map[string]data.PublicKey)
privKeys := make(map[string]data.PrivateKey)
// Get all the private key objects related to the public keys
missingKeyIDs := []string{}
for _, key := range signingKeys {
canonicalID, err := utils.CanonicalKeyID(key)
tufIDs[key.ID()] = key
if err != nil {
return err
}
k, _, err := service.GetPrivateKey(canonicalID)
if err != nil {
if _, ok := err.(trustmanager.ErrKeyNotFound); ok {
missingKeyIDs = append(missingKeyIDs, canonicalID)
continue
}
return err
}
privKeys[key.ID()] = k
}
// include the list of otherWhitelistedKeys
for _, key := range otherWhitelistedKeys {
if _, ok := tufIDs[key.ID()]; !ok {
tufIDs[key.ID()] = key
}
}
// Check to ensure we have enough signing keys
if len(privKeys) < minSignatures {
return ErrInsufficientSignatures{FoundKeys: len(privKeys),
NeededKeys: minSignatures, MissingKeyIDs: missingKeyIDs}
}
emptyStruct := struct{}{}
// Do signing and generate list of signatures
for keyID, pk := range privKeys {
sig, err := pk.Sign(rand.Reader, *s.Signed, nil)
if err != nil {
logrus.Debugf("Failed to sign with key: %s. Reason: %v", keyID, err)
return err
}
signingKeyIDs[keyID] = emptyStruct
signatures = append(signatures, data.Signature{
KeyID: keyID,
Method: pk.SignatureAlgorithm(),
Signature: sig[:],
})
}
for _, sig := range s.Signatures {
if _, ok := signingKeyIDs[sig.KeyID]; ok {
// key is in the set of key IDs for which a signature has been created
continue
}
var (
k data.PublicKey
ok bool
)
if k, ok = tufIDs[sig.KeyID]; !ok {
// key is no longer a valid signing key
continue
}
if err := VerifySignature(*s.Signed, &sig, k); err != nil {
// signature is no longer valid
continue
}
// keep any signatures that still represent valid keys and are
// themselves valid
signatures = append(signatures, sig)
}
s.Signatures = signatures
return nil
}
|
[
"func",
"Sign",
"(",
"service",
"CryptoService",
",",
"s",
"*",
"data",
".",
"Signed",
",",
"signingKeys",
"[",
"]",
"data",
".",
"PublicKey",
",",
"minSignatures",
"int",
",",
"otherWhitelistedKeys",
"[",
"]",
"data",
".",
"PublicKey",
")",
"error",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"minSignatures",
",",
"len",
"(",
"signingKeys",
")",
")",
"\n",
"signatures",
":=",
"make",
"(",
"[",
"]",
"data",
".",
"Signature",
",",
"0",
",",
"len",
"(",
"s",
".",
"Signatures",
")",
"+",
"1",
")",
"\n",
"signingKeyIDs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"tufIDs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"data",
".",
"PublicKey",
")",
"\n\n",
"privKeys",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"data",
".",
"PrivateKey",
")",
"\n\n",
"// Get all the private key objects related to the public keys",
"missingKeyIDs",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"signingKeys",
"{",
"canonicalID",
",",
"err",
":=",
"utils",
".",
"CanonicalKeyID",
"(",
"key",
")",
"\n",
"tufIDs",
"[",
"key",
".",
"ID",
"(",
")",
"]",
"=",
"key",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"k",
",",
"_",
",",
"err",
":=",
"service",
".",
"GetPrivateKey",
"(",
"canonicalID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"trustmanager",
".",
"ErrKeyNotFound",
")",
";",
"ok",
"{",
"missingKeyIDs",
"=",
"append",
"(",
"missingKeyIDs",
",",
"canonicalID",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"privKeys",
"[",
"key",
".",
"ID",
"(",
")",
"]",
"=",
"k",
"\n",
"}",
"\n\n",
"// include the list of otherWhitelistedKeys",
"for",
"_",
",",
"key",
":=",
"range",
"otherWhitelistedKeys",
"{",
"if",
"_",
",",
"ok",
":=",
"tufIDs",
"[",
"key",
".",
"ID",
"(",
")",
"]",
";",
"!",
"ok",
"{",
"tufIDs",
"[",
"key",
".",
"ID",
"(",
")",
"]",
"=",
"key",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Check to ensure we have enough signing keys",
"if",
"len",
"(",
"privKeys",
")",
"<",
"minSignatures",
"{",
"return",
"ErrInsufficientSignatures",
"{",
"FoundKeys",
":",
"len",
"(",
"privKeys",
")",
",",
"NeededKeys",
":",
"minSignatures",
",",
"MissingKeyIDs",
":",
"missingKeyIDs",
"}",
"\n",
"}",
"\n\n",
"emptyStruct",
":=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"// Do signing and generate list of signatures",
"for",
"keyID",
",",
"pk",
":=",
"range",
"privKeys",
"{",
"sig",
",",
"err",
":=",
"pk",
".",
"Sign",
"(",
"rand",
".",
"Reader",
",",
"*",
"s",
".",
"Signed",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"keyID",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"signingKeyIDs",
"[",
"keyID",
"]",
"=",
"emptyStruct",
"\n",
"signatures",
"=",
"append",
"(",
"signatures",
",",
"data",
".",
"Signature",
"{",
"KeyID",
":",
"keyID",
",",
"Method",
":",
"pk",
".",
"SignatureAlgorithm",
"(",
")",
",",
"Signature",
":",
"sig",
"[",
":",
"]",
",",
"}",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"sig",
":=",
"range",
"s",
".",
"Signatures",
"{",
"if",
"_",
",",
"ok",
":=",
"signingKeyIDs",
"[",
"sig",
".",
"KeyID",
"]",
";",
"ok",
"{",
"// key is in the set of key IDs for which a signature has been created",
"continue",
"\n",
"}",
"\n",
"var",
"(",
"k",
"data",
".",
"PublicKey",
"\n",
"ok",
"bool",
"\n",
")",
"\n",
"if",
"k",
",",
"ok",
"=",
"tufIDs",
"[",
"sig",
".",
"KeyID",
"]",
";",
"!",
"ok",
"{",
"// key is no longer a valid signing key",
"continue",
"\n",
"}",
"\n",
"if",
"err",
":=",
"VerifySignature",
"(",
"*",
"s",
".",
"Signed",
",",
"&",
"sig",
",",
"k",
")",
";",
"err",
"!=",
"nil",
"{",
"// signature is no longer valid",
"continue",
"\n",
"}",
"\n",
"// keep any signatures that still represent valid keys and are",
"// themselves valid",
"signatures",
"=",
"append",
"(",
"signatures",
",",
"sig",
")",
"\n",
"}",
"\n",
"s",
".",
"Signatures",
"=",
"signatures",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Sign takes a data.Signed and a cryptoservice containing private keys,
// calculates and adds at least minSignature signatures using signingKeys the
// data.Signed. It will also clean up any signatures that are not in produced
// by either a signingKey or an otherWhitelistedKey.
// Note that in most cases, otherWhitelistedKeys should probably be null. They
// are for keys you don't want to sign with, but you also don't want to remove
// existing signatures by those keys. For instance, if you want to call Sign
// multiple times with different sets of signing keys without undoing removing
// signatures produced by the previous call to Sign.
|
[
"Sign",
"takes",
"a",
"data",
".",
"Signed",
"and",
"a",
"cryptoservice",
"containing",
"private",
"keys",
"calculates",
"and",
"adds",
"at",
"least",
"minSignature",
"signatures",
"using",
"signingKeys",
"the",
"data",
".",
"Signed",
".",
"It",
"will",
"also",
"clean",
"up",
"any",
"signatures",
"that",
"are",
"not",
"in",
"produced",
"by",
"either",
"a",
"signingKey",
"or",
"an",
"otherWhitelistedKey",
".",
"Note",
"that",
"in",
"most",
"cases",
"otherWhitelistedKeys",
"should",
"probably",
"be",
"null",
".",
"They",
"are",
"for",
"keys",
"you",
"don",
"t",
"want",
"to",
"sign",
"with",
"but",
"you",
"also",
"don",
"t",
"want",
"to",
"remove",
"existing",
"signatures",
"by",
"those",
"keys",
".",
"For",
"instance",
"if",
"you",
"want",
"to",
"call",
"Sign",
"multiple",
"times",
"with",
"different",
"sets",
"of",
"signing",
"keys",
"without",
"undoing",
"removing",
"signatures",
"produced",
"by",
"the",
"previous",
"call",
"to",
"Sign",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/sign.go#L32-L113
|
train
|
theupdateframework/notary
|
tuf/utils/role_sort.go
|
Swap
|
func (r RoleList) Swap(i, j int) {
r[i], r[j] = r[j], r[i]
}
|
go
|
func (r RoleList) Swap(i, j int) {
r[i], r[j] = r[j], r[i]
}
|
[
"func",
"(",
"r",
"RoleList",
")",
"Swap",
"(",
"i",
",",
"j",
"int",
")",
"{",
"r",
"[",
"i",
"]",
",",
"r",
"[",
"j",
"]",
"=",
"r",
"[",
"j",
"]",
",",
"r",
"[",
"i",
"]",
"\n",
"}"
] |
// Swap the items at 2 locations in the list
|
[
"Swap",
"the",
"items",
"at",
"2",
"locations",
"in",
"the",
"list"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/role_sort.go#L29-L31
|
train
|
theupdateframework/notary
|
client/reader.go
|
GetTargetByName
|
func (r *reader) GetTargetByName(name string, roles ...data.RoleName) (*TargetWithRole, error) {
if len(roles) == 0 {
roles = append(roles, data.CanonicalTargetsRole)
}
var resultMeta data.FileMeta
var resultRoleName data.RoleName
var foundTarget bool
for _, role := range roles {
// Define an array of roles to skip for this walk (see IMPORTANT comment above)
skipRoles := utils.RoleNameSliceRemove(roles, role)
// Define a visitor function to find the specified target
getTargetVisitorFunc := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
if tgt == nil {
return nil
}
// We found the target and validated path compatibility in our walk,
// so we should stop our walk and set the resultMeta and resultRoleName variables
if resultMeta, foundTarget = tgt.Signed.Targets[name]; foundTarget {
resultRoleName = validRole.Name
return tuf.StopWalk{}
}
return nil
}
// Check that we didn't error, and that we assigned to our target
if err := r.tufRepo.WalkTargets(name, role, getTargetVisitorFunc, skipRoles...); err == nil && foundTarget {
return &TargetWithRole{Target: Target{Name: name, Hashes: resultMeta.Hashes, Length: resultMeta.Length, Custom: resultMeta.Custom}, Role: resultRoleName}, nil
}
}
return nil, ErrNoSuchTarget(name)
}
|
go
|
func (r *reader) GetTargetByName(name string, roles ...data.RoleName) (*TargetWithRole, error) {
if len(roles) == 0 {
roles = append(roles, data.CanonicalTargetsRole)
}
var resultMeta data.FileMeta
var resultRoleName data.RoleName
var foundTarget bool
for _, role := range roles {
// Define an array of roles to skip for this walk (see IMPORTANT comment above)
skipRoles := utils.RoleNameSliceRemove(roles, role)
// Define a visitor function to find the specified target
getTargetVisitorFunc := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
if tgt == nil {
return nil
}
// We found the target and validated path compatibility in our walk,
// so we should stop our walk and set the resultMeta and resultRoleName variables
if resultMeta, foundTarget = tgt.Signed.Targets[name]; foundTarget {
resultRoleName = validRole.Name
return tuf.StopWalk{}
}
return nil
}
// Check that we didn't error, and that we assigned to our target
if err := r.tufRepo.WalkTargets(name, role, getTargetVisitorFunc, skipRoles...); err == nil && foundTarget {
return &TargetWithRole{Target: Target{Name: name, Hashes: resultMeta.Hashes, Length: resultMeta.Length, Custom: resultMeta.Custom}, Role: resultRoleName}, nil
}
}
return nil, ErrNoSuchTarget(name)
}
|
[
"func",
"(",
"r",
"*",
"reader",
")",
"GetTargetByName",
"(",
"name",
"string",
",",
"roles",
"...",
"data",
".",
"RoleName",
")",
"(",
"*",
"TargetWithRole",
",",
"error",
")",
"{",
"if",
"len",
"(",
"roles",
")",
"==",
"0",
"{",
"roles",
"=",
"append",
"(",
"roles",
",",
"data",
".",
"CanonicalTargetsRole",
")",
"\n",
"}",
"\n",
"var",
"resultMeta",
"data",
".",
"FileMeta",
"\n",
"var",
"resultRoleName",
"data",
".",
"RoleName",
"\n",
"var",
"foundTarget",
"bool",
"\n",
"for",
"_",
",",
"role",
":=",
"range",
"roles",
"{",
"// Define an array of roles to skip for this walk (see IMPORTANT comment above)",
"skipRoles",
":=",
"utils",
".",
"RoleNameSliceRemove",
"(",
"roles",
",",
"role",
")",
"\n\n",
"// Define a visitor function to find the specified target",
"getTargetVisitorFunc",
":=",
"func",
"(",
"tgt",
"*",
"data",
".",
"SignedTargets",
",",
"validRole",
"data",
".",
"DelegationRole",
")",
"interface",
"{",
"}",
"{",
"if",
"tgt",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"// We found the target and validated path compatibility in our walk,",
"// so we should stop our walk and set the resultMeta and resultRoleName variables",
"if",
"resultMeta",
",",
"foundTarget",
"=",
"tgt",
".",
"Signed",
".",
"Targets",
"[",
"name",
"]",
";",
"foundTarget",
"{",
"resultRoleName",
"=",
"validRole",
".",
"Name",
"\n",
"return",
"tuf",
".",
"StopWalk",
"{",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"// Check that we didn't error, and that we assigned to our target",
"if",
"err",
":=",
"r",
".",
"tufRepo",
".",
"WalkTargets",
"(",
"name",
",",
"role",
",",
"getTargetVisitorFunc",
",",
"skipRoles",
"...",
")",
";",
"err",
"==",
"nil",
"&&",
"foundTarget",
"{",
"return",
"&",
"TargetWithRole",
"{",
"Target",
":",
"Target",
"{",
"Name",
":",
"name",
",",
"Hashes",
":",
"resultMeta",
".",
"Hashes",
",",
"Length",
":",
"resultMeta",
".",
"Length",
",",
"Custom",
":",
"resultMeta",
".",
"Custom",
"}",
",",
"Role",
":",
"resultRoleName",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"ErrNoSuchTarget",
"(",
"name",
")",
"\n\n",
"}"
] |
// GetTargetByName returns a target by the given name. If no roles are passed
// it uses the targets role and does a search of the entire delegation
// graph, finding the first entry in a breadth first search of the delegations.
// If roles are passed, they should be passed in descending priority and
// the target entry found in the subtree of the highest priority role
// will be returned.
// See the IMPORTANT section on ListTargets above. Those roles also apply here.
|
[
"GetTargetByName",
"returns",
"a",
"target",
"by",
"the",
"given",
"name",
".",
"If",
"no",
"roles",
"are",
"passed",
"it",
"uses",
"the",
"targets",
"role",
"and",
"does",
"a",
"search",
"of",
"the",
"entire",
"delegation",
"graph",
"finding",
"the",
"first",
"entry",
"in",
"a",
"breadth",
"first",
"search",
"of",
"the",
"delegations",
".",
"If",
"roles",
"are",
"passed",
"they",
"should",
"be",
"passed",
"in",
"descending",
"priority",
"and",
"the",
"target",
"entry",
"found",
"in",
"the",
"subtree",
"of",
"the",
"highest",
"priority",
"role",
"will",
"be",
"returned",
".",
"See",
"the",
"IMPORTANT",
"section",
"on",
"ListTargets",
"above",
".",
"Those",
"roles",
"also",
"apply",
"here",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/reader.go#L117-L148
|
train
|
theupdateframework/notary
|
client/reader.go
|
GetAllTargetMetadataByName
|
func (r *reader) GetAllTargetMetadataByName(name string) ([]TargetSignedStruct, error) {
var targetInfoList []TargetSignedStruct
// Define a visitor function to find the specified target
getAllTargetInfoByNameVisitorFunc := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
if tgt == nil {
return nil
}
// We found a target and validated path compatibility in our walk,
// so add it to our list if we have a match
// if we have an empty name, add all targets, else check if we have it
var targetMetaToAdd data.Files
if name == "" {
targetMetaToAdd = tgt.Signed.Targets
} else {
if meta, ok := tgt.Signed.Targets[name]; ok {
targetMetaToAdd = data.Files{name: meta}
}
}
for targetName, resultMeta := range targetMetaToAdd {
targetInfo := TargetSignedStruct{
Role: validRole,
Target: Target{Name: targetName, Hashes: resultMeta.Hashes, Length: resultMeta.Length, Custom: resultMeta.Custom},
Signatures: tgt.Signatures,
}
targetInfoList = append(targetInfoList, targetInfo)
}
// continue walking to all child roles
return nil
}
// Check that we didn't error, and that we found the target at least once
if err := r.tufRepo.WalkTargets(name, "", getAllTargetInfoByNameVisitorFunc); err != nil {
return nil, err
}
if len(targetInfoList) == 0 {
return nil, ErrNoSuchTarget(name)
}
return targetInfoList, nil
}
|
go
|
func (r *reader) GetAllTargetMetadataByName(name string) ([]TargetSignedStruct, error) {
var targetInfoList []TargetSignedStruct
// Define a visitor function to find the specified target
getAllTargetInfoByNameVisitorFunc := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
if tgt == nil {
return nil
}
// We found a target and validated path compatibility in our walk,
// so add it to our list if we have a match
// if we have an empty name, add all targets, else check if we have it
var targetMetaToAdd data.Files
if name == "" {
targetMetaToAdd = tgt.Signed.Targets
} else {
if meta, ok := tgt.Signed.Targets[name]; ok {
targetMetaToAdd = data.Files{name: meta}
}
}
for targetName, resultMeta := range targetMetaToAdd {
targetInfo := TargetSignedStruct{
Role: validRole,
Target: Target{Name: targetName, Hashes: resultMeta.Hashes, Length: resultMeta.Length, Custom: resultMeta.Custom},
Signatures: tgt.Signatures,
}
targetInfoList = append(targetInfoList, targetInfo)
}
// continue walking to all child roles
return nil
}
// Check that we didn't error, and that we found the target at least once
if err := r.tufRepo.WalkTargets(name, "", getAllTargetInfoByNameVisitorFunc); err != nil {
return nil, err
}
if len(targetInfoList) == 0 {
return nil, ErrNoSuchTarget(name)
}
return targetInfoList, nil
}
|
[
"func",
"(",
"r",
"*",
"reader",
")",
"GetAllTargetMetadataByName",
"(",
"name",
"string",
")",
"(",
"[",
"]",
"TargetSignedStruct",
",",
"error",
")",
"{",
"var",
"targetInfoList",
"[",
"]",
"TargetSignedStruct",
"\n\n",
"// Define a visitor function to find the specified target",
"getAllTargetInfoByNameVisitorFunc",
":=",
"func",
"(",
"tgt",
"*",
"data",
".",
"SignedTargets",
",",
"validRole",
"data",
".",
"DelegationRole",
")",
"interface",
"{",
"}",
"{",
"if",
"tgt",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"// We found a target and validated path compatibility in our walk,",
"// so add it to our list if we have a match",
"// if we have an empty name, add all targets, else check if we have it",
"var",
"targetMetaToAdd",
"data",
".",
"Files",
"\n",
"if",
"name",
"==",
"\"",
"\"",
"{",
"targetMetaToAdd",
"=",
"tgt",
".",
"Signed",
".",
"Targets",
"\n",
"}",
"else",
"{",
"if",
"meta",
",",
"ok",
":=",
"tgt",
".",
"Signed",
".",
"Targets",
"[",
"name",
"]",
";",
"ok",
"{",
"targetMetaToAdd",
"=",
"data",
".",
"Files",
"{",
"name",
":",
"meta",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"targetName",
",",
"resultMeta",
":=",
"range",
"targetMetaToAdd",
"{",
"targetInfo",
":=",
"TargetSignedStruct",
"{",
"Role",
":",
"validRole",
",",
"Target",
":",
"Target",
"{",
"Name",
":",
"targetName",
",",
"Hashes",
":",
"resultMeta",
".",
"Hashes",
",",
"Length",
":",
"resultMeta",
".",
"Length",
",",
"Custom",
":",
"resultMeta",
".",
"Custom",
"}",
",",
"Signatures",
":",
"tgt",
".",
"Signatures",
",",
"}",
"\n",
"targetInfoList",
"=",
"append",
"(",
"targetInfoList",
",",
"targetInfo",
")",
"\n",
"}",
"\n",
"// continue walking to all child roles",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Check that we didn't error, and that we found the target at least once",
"if",
"err",
":=",
"r",
".",
"tufRepo",
".",
"WalkTargets",
"(",
"name",
",",
"\"",
"\"",
",",
"getAllTargetInfoByNameVisitorFunc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"targetInfoList",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"ErrNoSuchTarget",
"(",
"name",
")",
"\n",
"}",
"\n",
"return",
"targetInfoList",
",",
"nil",
"\n",
"}"
] |
// GetAllTargetMetadataByName searches the entire delegation role tree to find the specified target by name for all
// roles, and returns a list of TargetSignedStructs for each time it finds the specified target.
// If given an empty string for a target name, it will return back all targets signed into the repository in every role
|
[
"GetAllTargetMetadataByName",
"searches",
"the",
"entire",
"delegation",
"role",
"tree",
"to",
"find",
"the",
"specified",
"target",
"by",
"name",
"for",
"all",
"roles",
"and",
"returns",
"a",
"list",
"of",
"TargetSignedStructs",
"for",
"each",
"time",
"it",
"finds",
"the",
"specified",
"target",
".",
"If",
"given",
"an",
"empty",
"string",
"for",
"a",
"target",
"name",
"it",
"will",
"return",
"back",
"all",
"targets",
"signed",
"into",
"the",
"repository",
"in",
"every",
"role"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/reader.go#L153-L193
|
train
|
theupdateframework/notary
|
client/reader.go
|
ListRoles
|
func (r *reader) ListRoles() ([]RoleWithSignatures, error) {
// Get all role info from our updated keysDB, can be empty
roles := r.tufRepo.GetAllLoadedRoles()
var roleWithSigs []RoleWithSignatures
// Populate RoleWithSignatures with Role from keysDB and signatures from TUF metadata
for _, role := range roles {
roleWithSig := RoleWithSignatures{Role: *role, Signatures: nil}
switch role.Name {
case data.CanonicalRootRole:
roleWithSig.Signatures = r.tufRepo.Root.Signatures
case data.CanonicalTargetsRole:
roleWithSig.Signatures = r.tufRepo.Targets[data.CanonicalTargetsRole].Signatures
case data.CanonicalSnapshotRole:
roleWithSig.Signatures = r.tufRepo.Snapshot.Signatures
case data.CanonicalTimestampRole:
roleWithSig.Signatures = r.tufRepo.Timestamp.Signatures
default:
if !data.IsDelegation(role.Name) {
continue
}
if _, ok := r.tufRepo.Targets[role.Name]; ok {
// We'll only find a signature if we've published any targets with this delegation
roleWithSig.Signatures = r.tufRepo.Targets[role.Name].Signatures
}
}
roleWithSigs = append(roleWithSigs, roleWithSig)
}
return roleWithSigs, nil
}
|
go
|
func (r *reader) ListRoles() ([]RoleWithSignatures, error) {
// Get all role info from our updated keysDB, can be empty
roles := r.tufRepo.GetAllLoadedRoles()
var roleWithSigs []RoleWithSignatures
// Populate RoleWithSignatures with Role from keysDB and signatures from TUF metadata
for _, role := range roles {
roleWithSig := RoleWithSignatures{Role: *role, Signatures: nil}
switch role.Name {
case data.CanonicalRootRole:
roleWithSig.Signatures = r.tufRepo.Root.Signatures
case data.CanonicalTargetsRole:
roleWithSig.Signatures = r.tufRepo.Targets[data.CanonicalTargetsRole].Signatures
case data.CanonicalSnapshotRole:
roleWithSig.Signatures = r.tufRepo.Snapshot.Signatures
case data.CanonicalTimestampRole:
roleWithSig.Signatures = r.tufRepo.Timestamp.Signatures
default:
if !data.IsDelegation(role.Name) {
continue
}
if _, ok := r.tufRepo.Targets[role.Name]; ok {
// We'll only find a signature if we've published any targets with this delegation
roleWithSig.Signatures = r.tufRepo.Targets[role.Name].Signatures
}
}
roleWithSigs = append(roleWithSigs, roleWithSig)
}
return roleWithSigs, nil
}
|
[
"func",
"(",
"r",
"*",
"reader",
")",
"ListRoles",
"(",
")",
"(",
"[",
"]",
"RoleWithSignatures",
",",
"error",
")",
"{",
"// Get all role info from our updated keysDB, can be empty",
"roles",
":=",
"r",
".",
"tufRepo",
".",
"GetAllLoadedRoles",
"(",
")",
"\n\n",
"var",
"roleWithSigs",
"[",
"]",
"RoleWithSignatures",
"\n\n",
"// Populate RoleWithSignatures with Role from keysDB and signatures from TUF metadata",
"for",
"_",
",",
"role",
":=",
"range",
"roles",
"{",
"roleWithSig",
":=",
"RoleWithSignatures",
"{",
"Role",
":",
"*",
"role",
",",
"Signatures",
":",
"nil",
"}",
"\n",
"switch",
"role",
".",
"Name",
"{",
"case",
"data",
".",
"CanonicalRootRole",
":",
"roleWithSig",
".",
"Signatures",
"=",
"r",
".",
"tufRepo",
".",
"Root",
".",
"Signatures",
"\n",
"case",
"data",
".",
"CanonicalTargetsRole",
":",
"roleWithSig",
".",
"Signatures",
"=",
"r",
".",
"tufRepo",
".",
"Targets",
"[",
"data",
".",
"CanonicalTargetsRole",
"]",
".",
"Signatures",
"\n",
"case",
"data",
".",
"CanonicalSnapshotRole",
":",
"roleWithSig",
".",
"Signatures",
"=",
"r",
".",
"tufRepo",
".",
"Snapshot",
".",
"Signatures",
"\n",
"case",
"data",
".",
"CanonicalTimestampRole",
":",
"roleWithSig",
".",
"Signatures",
"=",
"r",
".",
"tufRepo",
".",
"Timestamp",
".",
"Signatures",
"\n",
"default",
":",
"if",
"!",
"data",
".",
"IsDelegation",
"(",
"role",
".",
"Name",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"tufRepo",
".",
"Targets",
"[",
"role",
".",
"Name",
"]",
";",
"ok",
"{",
"// We'll only find a signature if we've published any targets with this delegation",
"roleWithSig",
".",
"Signatures",
"=",
"r",
".",
"tufRepo",
".",
"Targets",
"[",
"role",
".",
"Name",
"]",
".",
"Signatures",
"\n",
"}",
"\n",
"}",
"\n",
"roleWithSigs",
"=",
"append",
"(",
"roleWithSigs",
",",
"roleWithSig",
")",
"\n",
"}",
"\n",
"return",
"roleWithSigs",
",",
"nil",
"\n",
"}"
] |
// ListRoles returns a list of RoleWithSignatures objects for this repo
// This represents the latest metadata for each role in this repo
|
[
"ListRoles",
"returns",
"a",
"list",
"of",
"RoleWithSignatures",
"objects",
"for",
"this",
"repo",
"This",
"represents",
"the",
"latest",
"metadata",
"for",
"each",
"role",
"in",
"this",
"repo"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/reader.go#L197-L227
|
train
|
theupdateframework/notary
|
client/reader.go
|
GetDelegationRoles
|
func (r *reader) GetDelegationRoles() ([]data.Role, error) {
// All top level delegations (ex: targets/level1) are stored exclusively in targets.json
_, ok := r.tufRepo.Targets[data.CanonicalTargetsRole]
if !ok {
return nil, store.ErrMetaNotFound{Resource: data.CanonicalTargetsRole.String()}
}
// make a copy for traversing nested delegations
allDelegations := []data.Role{}
// Define a visitor function to populate the delegations list and translate their key IDs to canonical IDs
delegationCanonicalListVisitor := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
// For the return list, update with a copy that includes canonicalKeyIDs
// These aren't validated by the validRole
canonicalDelegations, err := translateDelegationsToCanonicalIDs(tgt.Signed.Delegations)
if err != nil {
return err
}
allDelegations = append(allDelegations, canonicalDelegations...)
return nil
}
err := r.tufRepo.WalkTargets("", "", delegationCanonicalListVisitor)
if err != nil {
return nil, err
}
return allDelegations, nil
}
|
go
|
func (r *reader) GetDelegationRoles() ([]data.Role, error) {
// All top level delegations (ex: targets/level1) are stored exclusively in targets.json
_, ok := r.tufRepo.Targets[data.CanonicalTargetsRole]
if !ok {
return nil, store.ErrMetaNotFound{Resource: data.CanonicalTargetsRole.String()}
}
// make a copy for traversing nested delegations
allDelegations := []data.Role{}
// Define a visitor function to populate the delegations list and translate their key IDs to canonical IDs
delegationCanonicalListVisitor := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
// For the return list, update with a copy that includes canonicalKeyIDs
// These aren't validated by the validRole
canonicalDelegations, err := translateDelegationsToCanonicalIDs(tgt.Signed.Delegations)
if err != nil {
return err
}
allDelegations = append(allDelegations, canonicalDelegations...)
return nil
}
err := r.tufRepo.WalkTargets("", "", delegationCanonicalListVisitor)
if err != nil {
return nil, err
}
return allDelegations, nil
}
|
[
"func",
"(",
"r",
"*",
"reader",
")",
"GetDelegationRoles",
"(",
")",
"(",
"[",
"]",
"data",
".",
"Role",
",",
"error",
")",
"{",
"// All top level delegations (ex: targets/level1) are stored exclusively in targets.json",
"_",
",",
"ok",
":=",
"r",
".",
"tufRepo",
".",
"Targets",
"[",
"data",
".",
"CanonicalTargetsRole",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"store",
".",
"ErrMetaNotFound",
"{",
"Resource",
":",
"data",
".",
"CanonicalTargetsRole",
".",
"String",
"(",
")",
"}",
"\n",
"}",
"\n\n",
"// make a copy for traversing nested delegations",
"allDelegations",
":=",
"[",
"]",
"data",
".",
"Role",
"{",
"}",
"\n\n",
"// Define a visitor function to populate the delegations list and translate their key IDs to canonical IDs",
"delegationCanonicalListVisitor",
":=",
"func",
"(",
"tgt",
"*",
"data",
".",
"SignedTargets",
",",
"validRole",
"data",
".",
"DelegationRole",
")",
"interface",
"{",
"}",
"{",
"// For the return list, update with a copy that includes canonicalKeyIDs",
"// These aren't validated by the validRole",
"canonicalDelegations",
",",
"err",
":=",
"translateDelegationsToCanonicalIDs",
"(",
"tgt",
".",
"Signed",
".",
"Delegations",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"allDelegations",
"=",
"append",
"(",
"allDelegations",
",",
"canonicalDelegations",
"...",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"err",
":=",
"r",
".",
"tufRepo",
".",
"WalkTargets",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"delegationCanonicalListVisitor",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"allDelegations",
",",
"nil",
"\n",
"}"
] |
// GetDelegationRoles returns the keys and roles of the repository's delegations
// Also converts key IDs to canonical key IDs to keep consistent with signing prompts
|
[
"GetDelegationRoles",
"returns",
"the",
"keys",
"and",
"roles",
"of",
"the",
"repository",
"s",
"delegations",
"Also",
"converts",
"key",
"IDs",
"to",
"canonical",
"key",
"IDs",
"to",
"keep",
"consistent",
"with",
"signing",
"prompts"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/reader.go#L231-L257
|
train
|
theupdateframework/notary
|
cmd/notary-server/config.go
|
getRequiredGunPrefixes
|
func getRequiredGunPrefixes(configuration *viper.Viper) ([]string, error) {
prefixes := configuration.GetStringSlice("repositories.gun_prefixes")
for _, prefix := range prefixes {
p := path.Clean(strings.TrimSpace(prefix))
if p+"/" != prefix || strings.HasPrefix(p, "/") || strings.HasPrefix(p, "..") {
return nil, fmt.Errorf("invalid GUN prefix %s", prefix)
}
}
return prefixes, nil
}
|
go
|
func getRequiredGunPrefixes(configuration *viper.Viper) ([]string, error) {
prefixes := configuration.GetStringSlice("repositories.gun_prefixes")
for _, prefix := range prefixes {
p := path.Clean(strings.TrimSpace(prefix))
if p+"/" != prefix || strings.HasPrefix(p, "/") || strings.HasPrefix(p, "..") {
return nil, fmt.Errorf("invalid GUN prefix %s", prefix)
}
}
return prefixes, nil
}
|
[
"func",
"getRequiredGunPrefixes",
"(",
"configuration",
"*",
"viper",
".",
"Viper",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"prefixes",
":=",
"configuration",
".",
"GetStringSlice",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"prefix",
":=",
"range",
"prefixes",
"{",
"p",
":=",
"path",
".",
"Clean",
"(",
"strings",
".",
"TrimSpace",
"(",
"prefix",
")",
")",
"\n",
"if",
"p",
"+",
"\"",
"\"",
"!=",
"prefix",
"||",
"strings",
".",
"HasPrefix",
"(",
"p",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"HasPrefix",
"(",
"p",
",",
"\"",
"\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"prefix",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"prefixes",
",",
"nil",
"\n",
"}"
] |
// gets the required gun prefixes accepted by this server
|
[
"gets",
"the",
"required",
"gun",
"prefixes",
"accepted",
"by",
"this",
"server"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-server/config.go#L32-L41
|
train
|
theupdateframework/notary
|
cmd/notary-server/config.go
|
getAddrAndTLSConfig
|
func getAddrAndTLSConfig(configuration *viper.Viper) (string, *tls.Config, error) {
httpAddr := configuration.GetString("server.http_addr")
if httpAddr == "" {
return "", nil, fmt.Errorf("http listen address required for server")
}
tlsConfig, err := utils.ParseServerTLS(configuration, false)
if err != nil {
return "", nil, fmt.Errorf(err.Error())
}
return httpAddr, tlsConfig, nil
}
|
go
|
func getAddrAndTLSConfig(configuration *viper.Viper) (string, *tls.Config, error) {
httpAddr := configuration.GetString("server.http_addr")
if httpAddr == "" {
return "", nil, fmt.Errorf("http listen address required for server")
}
tlsConfig, err := utils.ParseServerTLS(configuration, false)
if err != nil {
return "", nil, fmt.Errorf(err.Error())
}
return httpAddr, tlsConfig, nil
}
|
[
"func",
"getAddrAndTLSConfig",
"(",
"configuration",
"*",
"viper",
".",
"Viper",
")",
"(",
"string",
",",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"httpAddr",
":=",
"configuration",
".",
"GetString",
"(",
"\"",
"\"",
")",
"\n",
"if",
"httpAddr",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"tlsConfig",
",",
"err",
":=",
"utils",
".",
"ParseServerTLS",
"(",
"configuration",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"httpAddr",
",",
"tlsConfig",
",",
"nil",
"\n",
"}"
] |
// get the address for the HTTP server, and parses the optional TLS
// configuration for the server - if no TLS configuration is specified,
// TLS is not enabled.
|
[
"get",
"the",
"address",
"for",
"the",
"HTTP",
"server",
"and",
"parses",
"the",
"optional",
"TLS",
"configuration",
"for",
"the",
"server",
"-",
"if",
"no",
"TLS",
"configuration",
"is",
"specified",
"TLS",
"is",
"not",
"enabled",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-server/config.go#L46-L57
|
train
|
theupdateframework/notary
|
cmd/notary-server/config.go
|
grpcTLS
|
func grpcTLS(configuration *viper.Viper) (*tls.Config, error) {
rootCA := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_ca_file")
clientCert := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_client_cert")
clientKey := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_client_key")
if clientCert == "" && clientKey != "" || clientCert != "" && clientKey == "" {
return nil, fmt.Errorf("either pass both client key and cert, or neither")
}
tlsConfig, err := tlsconfig.Client(tlsconfig.Options{
CAFile: rootCA,
CertFile: clientCert,
KeyFile: clientKey,
ExclusiveRootPools: true,
})
if err != nil {
return nil, fmt.Errorf(
"Unable to configure TLS to the trust service: %s", err.Error())
}
return tlsConfig, nil
}
|
go
|
func grpcTLS(configuration *viper.Viper) (*tls.Config, error) {
rootCA := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_ca_file")
clientCert := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_client_cert")
clientKey := utils.GetPathRelativeToConfig(configuration, "trust_service.tls_client_key")
if clientCert == "" && clientKey != "" || clientCert != "" && clientKey == "" {
return nil, fmt.Errorf("either pass both client key and cert, or neither")
}
tlsConfig, err := tlsconfig.Client(tlsconfig.Options{
CAFile: rootCA,
CertFile: clientCert,
KeyFile: clientKey,
ExclusiveRootPools: true,
})
if err != nil {
return nil, fmt.Errorf(
"Unable to configure TLS to the trust service: %s", err.Error())
}
return tlsConfig, nil
}
|
[
"func",
"grpcTLS",
"(",
"configuration",
"*",
"viper",
".",
"Viper",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"rootCA",
":=",
"utils",
".",
"GetPathRelativeToConfig",
"(",
"configuration",
",",
"\"",
"\"",
")",
"\n",
"clientCert",
":=",
"utils",
".",
"GetPathRelativeToConfig",
"(",
"configuration",
",",
"\"",
"\"",
")",
"\n",
"clientKey",
":=",
"utils",
".",
"GetPathRelativeToConfig",
"(",
"configuration",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"clientCert",
"==",
"\"",
"\"",
"&&",
"clientKey",
"!=",
"\"",
"\"",
"||",
"clientCert",
"!=",
"\"",
"\"",
"&&",
"clientKey",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"tlsConfig",
",",
"err",
":=",
"tlsconfig",
".",
"Client",
"(",
"tlsconfig",
".",
"Options",
"{",
"CAFile",
":",
"rootCA",
",",
"CertFile",
":",
"clientCert",
",",
"KeyFile",
":",
"clientKey",
",",
"ExclusiveRootPools",
":",
"true",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"tlsConfig",
",",
"nil",
"\n",
"}"
] |
// sets up TLS for the GRPC connection to notary-signer
|
[
"sets",
"up",
"TLS",
"for",
"the",
"GRPC",
"connection",
"to",
"notary",
"-",
"signer"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-server/config.go#L60-L80
|
train
|
theupdateframework/notary
|
cmd/notary-server/config.go
|
getStore
|
func getStore(configuration *viper.Viper, hRegister healthRegister, doBootstrap bool) (
storage.MetaStore, error) {
var store storage.MetaStore
backend := configuration.GetString("storage.backend")
logrus.Infof("Using %s backend", backend)
switch backend {
case notary.MemoryBackend:
return storage.NewMemStorage(), nil
case notary.MySQLBackend, notary.SQLiteBackend, notary.PostgresBackend:
storeConfig, err := utils.ParseSQLStorage(configuration)
if err != nil {
return nil, err
}
s, err := storage.NewSQLStorage(storeConfig.Backend, storeConfig.Source)
if err != nil {
return nil, fmt.Errorf("Error starting %s driver: %s", backend, err.Error())
}
store = *storage.NewTUFMetaStorage(s)
hRegister("DB operational", 10*time.Second, s.CheckHealth)
case notary.RethinkDBBackend:
var sess *gorethink.Session
storeConfig, err := utils.ParseRethinkDBStorage(configuration)
if err != nil {
return nil, err
}
tlsOpts := tlsconfig.Options{
CAFile: storeConfig.CA,
CertFile: storeConfig.Cert,
KeyFile: storeConfig.Key,
ExclusiveRootPools: true,
}
if doBootstrap {
sess, err = rethinkdb.AdminConnection(tlsOpts, storeConfig.Source)
} else {
sess, err = rethinkdb.UserConnection(tlsOpts, storeConfig.Source, storeConfig.Username, storeConfig.Password)
}
if err != nil {
return nil, fmt.Errorf("Error starting %s driver: %s", backend, err.Error())
}
s := storage.NewRethinkDBStorage(storeConfig.DBName, storeConfig.Username, storeConfig.Password, sess)
store = *storage.NewTUFMetaStorage(s)
hRegister("DB operational", 10*time.Second, s.CheckHealth)
default:
return nil, fmt.Errorf("%s is not a supported storage backend", backend)
}
return store, nil
}
|
go
|
func getStore(configuration *viper.Viper, hRegister healthRegister, doBootstrap bool) (
storage.MetaStore, error) {
var store storage.MetaStore
backend := configuration.GetString("storage.backend")
logrus.Infof("Using %s backend", backend)
switch backend {
case notary.MemoryBackend:
return storage.NewMemStorage(), nil
case notary.MySQLBackend, notary.SQLiteBackend, notary.PostgresBackend:
storeConfig, err := utils.ParseSQLStorage(configuration)
if err != nil {
return nil, err
}
s, err := storage.NewSQLStorage(storeConfig.Backend, storeConfig.Source)
if err != nil {
return nil, fmt.Errorf("Error starting %s driver: %s", backend, err.Error())
}
store = *storage.NewTUFMetaStorage(s)
hRegister("DB operational", 10*time.Second, s.CheckHealth)
case notary.RethinkDBBackend:
var sess *gorethink.Session
storeConfig, err := utils.ParseRethinkDBStorage(configuration)
if err != nil {
return nil, err
}
tlsOpts := tlsconfig.Options{
CAFile: storeConfig.CA,
CertFile: storeConfig.Cert,
KeyFile: storeConfig.Key,
ExclusiveRootPools: true,
}
if doBootstrap {
sess, err = rethinkdb.AdminConnection(tlsOpts, storeConfig.Source)
} else {
sess, err = rethinkdb.UserConnection(tlsOpts, storeConfig.Source, storeConfig.Username, storeConfig.Password)
}
if err != nil {
return nil, fmt.Errorf("Error starting %s driver: %s", backend, err.Error())
}
s := storage.NewRethinkDBStorage(storeConfig.DBName, storeConfig.Username, storeConfig.Password, sess)
store = *storage.NewTUFMetaStorage(s)
hRegister("DB operational", 10*time.Second, s.CheckHealth)
default:
return nil, fmt.Errorf("%s is not a supported storage backend", backend)
}
return store, nil
}
|
[
"func",
"getStore",
"(",
"configuration",
"*",
"viper",
".",
"Viper",
",",
"hRegister",
"healthRegister",
",",
"doBootstrap",
"bool",
")",
"(",
"storage",
".",
"MetaStore",
",",
"error",
")",
"{",
"var",
"store",
"storage",
".",
"MetaStore",
"\n",
"backend",
":=",
"configuration",
".",
"GetString",
"(",
"\"",
"\"",
")",
"\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"backend",
")",
"\n\n",
"switch",
"backend",
"{",
"case",
"notary",
".",
"MemoryBackend",
":",
"return",
"storage",
".",
"NewMemStorage",
"(",
")",
",",
"nil",
"\n",
"case",
"notary",
".",
"MySQLBackend",
",",
"notary",
".",
"SQLiteBackend",
",",
"notary",
".",
"PostgresBackend",
":",
"storeConfig",
",",
"err",
":=",
"utils",
".",
"ParseSQLStorage",
"(",
"configuration",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"s",
",",
"err",
":=",
"storage",
".",
"NewSQLStorage",
"(",
"storeConfig",
".",
"Backend",
",",
"storeConfig",
".",
"Source",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"backend",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"store",
"=",
"*",
"storage",
".",
"NewTUFMetaStorage",
"(",
"s",
")",
"\n",
"hRegister",
"(",
"\"",
"\"",
",",
"10",
"*",
"time",
".",
"Second",
",",
"s",
".",
"CheckHealth",
")",
"\n",
"case",
"notary",
".",
"RethinkDBBackend",
":",
"var",
"sess",
"*",
"gorethink",
".",
"Session",
"\n",
"storeConfig",
",",
"err",
":=",
"utils",
".",
"ParseRethinkDBStorage",
"(",
"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",
":=",
"storage",
".",
"NewRethinkDBStorage",
"(",
"storeConfig",
".",
"DBName",
",",
"storeConfig",
".",
"Username",
",",
"storeConfig",
".",
"Password",
",",
"sess",
")",
"\n",
"store",
"=",
"*",
"storage",
".",
"NewTUFMetaStorage",
"(",
"s",
")",
"\n",
"hRegister",
"(",
"\"",
"\"",
",",
"10",
"*",
"time",
".",
"Second",
",",
"s",
".",
"CheckHealth",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"backend",
")",
"\n",
"}",
"\n",
"return",
"store",
",",
"nil",
"\n",
"}"
] |
// parses the configuration and returns a backing store for the TUF files
|
[
"parses",
"the",
"configuration",
"and",
"returns",
"a",
"backing",
"store",
"for",
"the",
"TUF",
"files"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-server/config.go#L83-L130
|
train
|
theupdateframework/notary
|
cmd/notary-server/config.go
|
getTrustService
|
func getTrustService(configuration *viper.Viper, sFactory signerFactory,
hRegister healthRegister) (signed.CryptoService, string, error) {
switch configuration.GetString("trust_service.type") {
case "local":
logrus.Info("Using local signing service, which requires ED25519. " +
"Ignoring all other trust_service parameters, including keyAlgorithm")
return signed.NewEd25519(), data.ED25519Key, nil
case "remote":
default:
return nil, "", fmt.Errorf(
"must specify either a \"local\" or \"remote\" type for trust_service")
}
keyAlgo := configuration.GetString("trust_service.key_algorithm")
if keyAlgo != data.ED25519Key && keyAlgo != data.ECDSAKey && keyAlgo != data.RSAKey {
return nil, "", fmt.Errorf("invalid key algorithm configured: %s", keyAlgo)
}
clientTLS, err := grpcTLS(configuration)
if err != nil {
return nil, "", err
}
logrus.Info("Using remote signing service")
notarySigner, err := sFactory(
configuration.GetString("trust_service.hostname"),
configuration.GetString("trust_service.port"),
clientTLS,
)
if err != nil {
return nil, "", err
}
duration := 10 * time.Second
hRegister(
"Trust operational",
duration,
func() error {
err := notarySigner.CheckHealth(duration, notary.HealthCheckOverall)
if err != nil {
logrus.Error("Trust not fully operational: ", err.Error())
}
return err
},
)
return notarySigner, keyAlgo, nil
}
|
go
|
func getTrustService(configuration *viper.Viper, sFactory signerFactory,
hRegister healthRegister) (signed.CryptoService, string, error) {
switch configuration.GetString("trust_service.type") {
case "local":
logrus.Info("Using local signing service, which requires ED25519. " +
"Ignoring all other trust_service parameters, including keyAlgorithm")
return signed.NewEd25519(), data.ED25519Key, nil
case "remote":
default:
return nil, "", fmt.Errorf(
"must specify either a \"local\" or \"remote\" type for trust_service")
}
keyAlgo := configuration.GetString("trust_service.key_algorithm")
if keyAlgo != data.ED25519Key && keyAlgo != data.ECDSAKey && keyAlgo != data.RSAKey {
return nil, "", fmt.Errorf("invalid key algorithm configured: %s", keyAlgo)
}
clientTLS, err := grpcTLS(configuration)
if err != nil {
return nil, "", err
}
logrus.Info("Using remote signing service")
notarySigner, err := sFactory(
configuration.GetString("trust_service.hostname"),
configuration.GetString("trust_service.port"),
clientTLS,
)
if err != nil {
return nil, "", err
}
duration := 10 * time.Second
hRegister(
"Trust operational",
duration,
func() error {
err := notarySigner.CheckHealth(duration, notary.HealthCheckOverall)
if err != nil {
logrus.Error("Trust not fully operational: ", err.Error())
}
return err
},
)
return notarySigner, keyAlgo, nil
}
|
[
"func",
"getTrustService",
"(",
"configuration",
"*",
"viper",
".",
"Viper",
",",
"sFactory",
"signerFactory",
",",
"hRegister",
"healthRegister",
")",
"(",
"signed",
".",
"CryptoService",
",",
"string",
",",
"error",
")",
"{",
"switch",
"configuration",
".",
"GetString",
"(",
"\"",
"\"",
")",
"{",
"case",
"\"",
"\"",
":",
"logrus",
".",
"Info",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"return",
"signed",
".",
"NewEd25519",
"(",
")",
",",
"data",
".",
"ED25519Key",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"default",
":",
"return",
"nil",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
")",
"\n",
"}",
"\n\n",
"keyAlgo",
":=",
"configuration",
".",
"GetString",
"(",
"\"",
"\"",
")",
"\n",
"if",
"keyAlgo",
"!=",
"data",
".",
"ED25519Key",
"&&",
"keyAlgo",
"!=",
"data",
".",
"ECDSAKey",
"&&",
"keyAlgo",
"!=",
"data",
".",
"RSAKey",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyAlgo",
")",
"\n",
"}",
"\n\n",
"clientTLS",
",",
"err",
":=",
"grpcTLS",
"(",
"configuration",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"logrus",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"notarySigner",
",",
"err",
":=",
"sFactory",
"(",
"configuration",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"configuration",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"clientTLS",
",",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"duration",
":=",
"10",
"*",
"time",
".",
"Second",
"\n",
"hRegister",
"(",
"\"",
"\"",
",",
"duration",
",",
"func",
"(",
")",
"error",
"{",
"err",
":=",
"notarySigner",
".",
"CheckHealth",
"(",
"duration",
",",
"notary",
".",
"HealthCheckOverall",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Error",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
",",
")",
"\n",
"return",
"notarySigner",
",",
"keyAlgo",
",",
"nil",
"\n",
"}"
] |
// parses the configuration and determines which trust service and key algorithm
// to return
|
[
"parses",
"the",
"configuration",
"and",
"determines",
"which",
"trust",
"service",
"and",
"key",
"algorithm",
"to",
"return"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-server/config.go#L145-L194
|
train
|
theupdateframework/notary
|
trustmanager/remoteks/client.go
|
NewRemoteStore
|
func NewRemoteStore(server string, tlsConfig *tls.Config, timeout time.Duration) (*RemoteStore, error) {
cc, err := grpc.Dial(
server,
grpc.WithTransportCredentials(
credentials.NewTLS(tlsConfig),
),
grpc.WithBlock(),
)
if err != nil {
return nil, err
}
if timeout == 0 {
timeout = DefaultTimeout
}
return &RemoteStore{
client: NewStoreClient(cc),
location: server,
timeout: timeout,
}, nil
}
|
go
|
func NewRemoteStore(server string, tlsConfig *tls.Config, timeout time.Duration) (*RemoteStore, error) {
cc, err := grpc.Dial(
server,
grpc.WithTransportCredentials(
credentials.NewTLS(tlsConfig),
),
grpc.WithBlock(),
)
if err != nil {
return nil, err
}
if timeout == 0 {
timeout = DefaultTimeout
}
return &RemoteStore{
client: NewStoreClient(cc),
location: server,
timeout: timeout,
}, nil
}
|
[
"func",
"NewRemoteStore",
"(",
"server",
"string",
",",
"tlsConfig",
"*",
"tls",
".",
"Config",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"*",
"RemoteStore",
",",
"error",
")",
"{",
"cc",
",",
"err",
":=",
"grpc",
".",
"Dial",
"(",
"server",
",",
"grpc",
".",
"WithTransportCredentials",
"(",
"credentials",
".",
"NewTLS",
"(",
"tlsConfig",
")",
",",
")",
",",
"grpc",
".",
"WithBlock",
"(",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"timeout",
"==",
"0",
"{",
"timeout",
"=",
"DefaultTimeout",
"\n",
"}",
"\n",
"return",
"&",
"RemoteStore",
"{",
"client",
":",
"NewStoreClient",
"(",
"cc",
")",
",",
"location",
":",
"server",
",",
"timeout",
":",
"timeout",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewRemoteStore instantiates a RemoteStore.
|
[
"NewRemoteStore",
"instantiates",
"a",
"RemoteStore",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L32-L51
|
train
|
theupdateframework/notary
|
trustmanager/remoteks/client.go
|
getContext
|
func (s *RemoteStore) getContext() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), s.timeout)
}
|
go
|
func (s *RemoteStore) getContext() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), s.timeout)
}
|
[
"func",
"(",
"s",
"*",
"RemoteStore",
")",
"getContext",
"(",
")",
"(",
"context",
".",
"Context",
",",
"context",
".",
"CancelFunc",
")",
"{",
"return",
"context",
".",
"WithTimeout",
"(",
"context",
".",
"Background",
"(",
")",
",",
"s",
".",
"timeout",
")",
"\n",
"}"
] |
// getContext returns a context with the timeout configured at initialization
// time of the RemoteStore.
|
[
"getContext",
"returns",
"a",
"context",
"with",
"the",
"timeout",
"configured",
"at",
"initialization",
"time",
"of",
"the",
"RemoteStore",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L55-L57
|
train
|
theupdateframework/notary
|
trustmanager/remoteks/client.go
|
Set
|
func (s *RemoteStore) Set(fileName string, data []byte) error {
sm := &SetMsg{
FileName: fileName,
Data: data,
}
ctx, cancel := s.getContext()
defer cancel()
_, err := s.client.Set(ctx, sm)
return err
}
|
go
|
func (s *RemoteStore) Set(fileName string, data []byte) error {
sm := &SetMsg{
FileName: fileName,
Data: data,
}
ctx, cancel := s.getContext()
defer cancel()
_, err := s.client.Set(ctx, sm)
return err
}
|
[
"func",
"(",
"s",
"*",
"RemoteStore",
")",
"Set",
"(",
"fileName",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"sm",
":=",
"&",
"SetMsg",
"{",
"FileName",
":",
"fileName",
",",
"Data",
":",
"data",
",",
"}",
"\n",
"ctx",
",",
"cancel",
":=",
"s",
".",
"getContext",
"(",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"s",
".",
"client",
".",
"Set",
"(",
"ctx",
",",
"sm",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// Set stores the data using the provided fileName
|
[
"Set",
"stores",
"the",
"data",
"using",
"the",
"provided",
"fileName"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L60-L69
|
train
|
theupdateframework/notary
|
trustmanager/remoteks/client.go
|
Remove
|
func (s *RemoteStore) Remove(fileName string) error {
fm := &FileNameMsg{
FileName: fileName,
}
ctx, cancel := s.getContext()
defer cancel()
_, err := s.client.Remove(ctx, fm)
return err
}
|
go
|
func (s *RemoteStore) Remove(fileName string) error {
fm := &FileNameMsg{
FileName: fileName,
}
ctx, cancel := s.getContext()
defer cancel()
_, err := s.client.Remove(ctx, fm)
return err
}
|
[
"func",
"(",
"s",
"*",
"RemoteStore",
")",
"Remove",
"(",
"fileName",
"string",
")",
"error",
"{",
"fm",
":=",
"&",
"FileNameMsg",
"{",
"FileName",
":",
"fileName",
",",
"}",
"\n",
"ctx",
",",
"cancel",
":=",
"s",
".",
"getContext",
"(",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"s",
".",
"client",
".",
"Remove",
"(",
"ctx",
",",
"fm",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// Remove deletes a file from the store relative to the store's base directory.
// Paths are expected to be cleaned server side.
|
[
"Remove",
"deletes",
"a",
"file",
"from",
"the",
"store",
"relative",
"to",
"the",
"store",
"s",
"base",
"directory",
".",
"Paths",
"are",
"expected",
"to",
"be",
"cleaned",
"server",
"side",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L73-L81
|
train
|
theupdateframework/notary
|
trustmanager/remoteks/client.go
|
Get
|
func (s *RemoteStore) Get(fileName string) ([]byte, error) {
fm := &FileNameMsg{
FileName: fileName,
}
ctx, cancel := s.getContext()
defer cancel()
bm, err := s.client.Get(ctx, fm)
if err != nil {
return nil, err
}
return bm.Data, nil
}
|
go
|
func (s *RemoteStore) Get(fileName string) ([]byte, error) {
fm := &FileNameMsg{
FileName: fileName,
}
ctx, cancel := s.getContext()
defer cancel()
bm, err := s.client.Get(ctx, fm)
if err != nil {
return nil, err
}
return bm.Data, nil
}
|
[
"func",
"(",
"s",
"*",
"RemoteStore",
")",
"Get",
"(",
"fileName",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"fm",
":=",
"&",
"FileNameMsg",
"{",
"FileName",
":",
"fileName",
",",
"}",
"\n",
"ctx",
",",
"cancel",
":=",
"s",
".",
"getContext",
"(",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"bm",
",",
"err",
":=",
"s",
".",
"client",
".",
"Get",
"(",
"ctx",
",",
"fm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"bm",
".",
"Data",
",",
"nil",
"\n",
"}"
] |
// Get returns the file content found at fileName relative to the base directory
// of the file store. Paths are expected to be cleaned server side.
|
[
"Get",
"returns",
"the",
"file",
"content",
"found",
"at",
"fileName",
"relative",
"to",
"the",
"base",
"directory",
"of",
"the",
"file",
"store",
".",
"Paths",
"are",
"expected",
"to",
"be",
"cleaned",
"server",
"side",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L85-L96
|
train
|
theupdateframework/notary
|
trustmanager/remoteks/client.go
|
ListFiles
|
func (s *RemoteStore) ListFiles() []string {
logrus.Infof("listing files from %s", s.location)
ctx, cancel := s.getContext()
defer cancel()
fl, err := s.client.ListFiles(ctx, &google_protobuf.Empty{})
if err != nil {
logrus.Errorf("error listing files from %s: %s", s.location, err.Error())
return nil
}
return fl.FileNames
}
|
go
|
func (s *RemoteStore) ListFiles() []string {
logrus.Infof("listing files from %s", s.location)
ctx, cancel := s.getContext()
defer cancel()
fl, err := s.client.ListFiles(ctx, &google_protobuf.Empty{})
if err != nil {
logrus.Errorf("error listing files from %s: %s", s.location, err.Error())
return nil
}
return fl.FileNames
}
|
[
"func",
"(",
"s",
"*",
"RemoteStore",
")",
"ListFiles",
"(",
")",
"[",
"]",
"string",
"{",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"s",
".",
"location",
")",
"\n",
"ctx",
",",
"cancel",
":=",
"s",
".",
"getContext",
"(",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"fl",
",",
"err",
":=",
"s",
".",
"client",
".",
"ListFiles",
"(",
"ctx",
",",
"&",
"google_protobuf",
".",
"Empty",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
".",
"location",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"fl",
".",
"FileNames",
"\n",
"}"
] |
// ListFiles returns a list of paths relative to the base directory of the
// filestore. Any of these paths must be retrievable via the
// Storage.Get method.
|
[
"ListFiles",
"returns",
"a",
"list",
"of",
"paths",
"relative",
"to",
"the",
"base",
"directory",
"of",
"the",
"filestore",
".",
"Any",
"of",
"these",
"paths",
"must",
"be",
"retrievable",
"via",
"the",
"Storage",
".",
"Get",
"method",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/remoteks/client.go#L101-L111
|
train
|
theupdateframework/notary
|
client/client.go
|
NewRepository
|
func NewRepository(gun data.GUN, baseURL string, remoteStore store.RemoteStore, cache store.MetadataStore,
trustPinning trustpinning.TrustPinConfig, cryptoService signed.CryptoService, cl changelist.Changelist) (Repository, error) {
// Repo's remote store is either a valid remote store or an OfflineStore
if remoteStore == nil {
remoteStore = store.OfflineStore{}
}
if cache == nil {
return nil, fmt.Errorf("got an invalid cache (nil metadata store)")
}
nRepo := &repository{
gun: gun,
baseURL: baseURL,
changelist: cl,
cache: cache,
remoteStore: remoteStore,
cryptoService: cryptoService,
trustPinning: trustPinning,
LegacyVersions: 0, // By default, don't sign with legacy roles
}
return nRepo, nil
}
|
go
|
func NewRepository(gun data.GUN, baseURL string, remoteStore store.RemoteStore, cache store.MetadataStore,
trustPinning trustpinning.TrustPinConfig, cryptoService signed.CryptoService, cl changelist.Changelist) (Repository, error) {
// Repo's remote store is either a valid remote store or an OfflineStore
if remoteStore == nil {
remoteStore = store.OfflineStore{}
}
if cache == nil {
return nil, fmt.Errorf("got an invalid cache (nil metadata store)")
}
nRepo := &repository{
gun: gun,
baseURL: baseURL,
changelist: cl,
cache: cache,
remoteStore: remoteStore,
cryptoService: cryptoService,
trustPinning: trustPinning,
LegacyVersions: 0, // By default, don't sign with legacy roles
}
return nRepo, nil
}
|
[
"func",
"NewRepository",
"(",
"gun",
"data",
".",
"GUN",
",",
"baseURL",
"string",
",",
"remoteStore",
"store",
".",
"RemoteStore",
",",
"cache",
"store",
".",
"MetadataStore",
",",
"trustPinning",
"trustpinning",
".",
"TrustPinConfig",
",",
"cryptoService",
"signed",
".",
"CryptoService",
",",
"cl",
"changelist",
".",
"Changelist",
")",
"(",
"Repository",
",",
"error",
")",
"{",
"// Repo's remote store is either a valid remote store or an OfflineStore",
"if",
"remoteStore",
"==",
"nil",
"{",
"remoteStore",
"=",
"store",
".",
"OfflineStore",
"{",
"}",
"\n",
"}",
"\n\n",
"if",
"cache",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"nRepo",
":=",
"&",
"repository",
"{",
"gun",
":",
"gun",
",",
"baseURL",
":",
"baseURL",
",",
"changelist",
":",
"cl",
",",
"cache",
":",
"cache",
",",
"remoteStore",
":",
"remoteStore",
",",
"cryptoService",
":",
"cryptoService",
",",
"trustPinning",
":",
"trustPinning",
",",
"LegacyVersions",
":",
"0",
",",
"// By default, don't sign with legacy roles",
"}",
"\n\n",
"return",
"nRepo",
",",
"nil",
"\n",
"}"
] |
// NewRepository is the base method that returns a new notary repository.
// It expects an initialized cache. In case of a nil remote store, a default
// offline store is used.
|
[
"NewRepository",
"is",
"the",
"base",
"method",
"that",
"returns",
"a",
"new",
"notary",
"repository",
".",
"It",
"expects",
"an",
"initialized",
"cache",
".",
"In",
"case",
"of",
"a",
"nil",
"remote",
"store",
"a",
"default",
"offline",
"store",
"is",
"used",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L97-L121
|
train
|
theupdateframework/notary
|
client/client.go
|
ListTargets
|
func (r *repository) ListTargets(roles ...data.RoleName) ([]*TargetWithRole, error) {
if err := r.updateTUF(false); err != nil {
return nil, err
}
return NewReadOnly(r.tufRepo).ListTargets(roles...)
}
|
go
|
func (r *repository) ListTargets(roles ...data.RoleName) ([]*TargetWithRole, error) {
if err := r.updateTUF(false); err != nil {
return nil, err
}
return NewReadOnly(r.tufRepo).ListTargets(roles...)
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"ListTargets",
"(",
"roles",
"...",
"data",
".",
"RoleName",
")",
"(",
"[",
"]",
"*",
"TargetWithRole",
",",
"error",
")",
"{",
"if",
"err",
":=",
"r",
".",
"updateTUF",
"(",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"NewReadOnly",
"(",
"r",
".",
"tufRepo",
")",
".",
"ListTargets",
"(",
"roles",
"...",
")",
"\n",
"}"
] |
// ListTargets calls update first before listing targets
|
[
"ListTargets",
"calls",
"update",
"first",
"before",
"listing",
"targets"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L146-L151
|
train
|
theupdateframework/notary
|
client/client.go
|
GetTargetByName
|
func (r *repository) GetTargetByName(name string, roles ...data.RoleName) (*TargetWithRole, error) {
if err := r.updateTUF(false); err != nil {
return nil, err
}
return NewReadOnly(r.tufRepo).GetTargetByName(name, roles...)
}
|
go
|
func (r *repository) GetTargetByName(name string, roles ...data.RoleName) (*TargetWithRole, error) {
if err := r.updateTUF(false); err != nil {
return nil, err
}
return NewReadOnly(r.tufRepo).GetTargetByName(name, roles...)
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"GetTargetByName",
"(",
"name",
"string",
",",
"roles",
"...",
"data",
".",
"RoleName",
")",
"(",
"*",
"TargetWithRole",
",",
"error",
")",
"{",
"if",
"err",
":=",
"r",
".",
"updateTUF",
"(",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"NewReadOnly",
"(",
"r",
".",
"tufRepo",
")",
".",
"GetTargetByName",
"(",
"name",
",",
"roles",
"...",
")",
"\n",
"}"
] |
// GetTargetByName calls update first before getting target by name
|
[
"GetTargetByName",
"calls",
"update",
"first",
"before",
"getting",
"target",
"by",
"name"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L154-L159
|
train
|
theupdateframework/notary
|
client/client.go
|
GetAllTargetMetadataByName
|
func (r *repository) GetAllTargetMetadataByName(name string) ([]TargetSignedStruct, error) {
if err := r.updateTUF(false); err != nil {
return nil, err
}
return NewReadOnly(r.tufRepo).GetAllTargetMetadataByName(name)
}
|
go
|
func (r *repository) GetAllTargetMetadataByName(name string) ([]TargetSignedStruct, error) {
if err := r.updateTUF(false); err != nil {
return nil, err
}
return NewReadOnly(r.tufRepo).GetAllTargetMetadataByName(name)
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"GetAllTargetMetadataByName",
"(",
"name",
"string",
")",
"(",
"[",
"]",
"TargetSignedStruct",
",",
"error",
")",
"{",
"if",
"err",
":=",
"r",
".",
"updateTUF",
"(",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"NewReadOnly",
"(",
"r",
".",
"tufRepo",
")",
".",
"GetAllTargetMetadataByName",
"(",
"name",
")",
"\n\n",
"}"
] |
// GetAllTargetMetadataByName calls update first before getting targets by name
|
[
"GetAllTargetMetadataByName",
"calls",
"update",
"first",
"before",
"getting",
"targets",
"by",
"name"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L162-L168
|
train
|
theupdateframework/notary
|
client/client.go
|
ListRoles
|
func (r *repository) ListRoles() ([]RoleWithSignatures, error) {
if err := r.updateTUF(false); err != nil {
return nil, err
}
return NewReadOnly(r.tufRepo).ListRoles()
}
|
go
|
func (r *repository) ListRoles() ([]RoleWithSignatures, error) {
if err := r.updateTUF(false); err != nil {
return nil, err
}
return NewReadOnly(r.tufRepo).ListRoles()
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"ListRoles",
"(",
")",
"(",
"[",
"]",
"RoleWithSignatures",
",",
"error",
")",
"{",
"if",
"err",
":=",
"r",
".",
"updateTUF",
"(",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"NewReadOnly",
"(",
"r",
".",
"tufRepo",
")",
".",
"ListRoles",
"(",
")",
"\n",
"}"
] |
// ListRoles calls update first before getting roles
|
[
"ListRoles",
"calls",
"update",
"first",
"before",
"getting",
"roles"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L171-L176
|
train
|
theupdateframework/notary
|
client/client.go
|
GetDelegationRoles
|
func (r *repository) GetDelegationRoles() ([]data.Role, error) {
if err := r.updateTUF(false); err != nil {
return nil, err
}
return NewReadOnly(r.tufRepo).GetDelegationRoles()
}
|
go
|
func (r *repository) GetDelegationRoles() ([]data.Role, error) {
if err := r.updateTUF(false); err != nil {
return nil, err
}
return NewReadOnly(r.tufRepo).GetDelegationRoles()
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"GetDelegationRoles",
"(",
")",
"(",
"[",
"]",
"data",
".",
"Role",
",",
"error",
")",
"{",
"if",
"err",
":=",
"r",
".",
"updateTUF",
"(",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"NewReadOnly",
"(",
"r",
".",
"tufRepo",
")",
".",
"GetDelegationRoles",
"(",
")",
"\n",
"}"
] |
// GetDelegationRoles calls update first before getting all delegation roles
|
[
"GetDelegationRoles",
"calls",
"update",
"first",
"before",
"getting",
"all",
"delegation",
"roles"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L179-L184
|
train
|
theupdateframework/notary
|
client/client.go
|
NewTarget
|
func NewTarget(targetName, targetPath string, targetCustom *canonicaljson.RawMessage) (*Target, error) {
b, err := ioutil.ReadFile(targetPath)
if err != nil {
return nil, err
}
meta, err := data.NewFileMeta(bytes.NewBuffer(b), data.NotaryDefaultHashes...)
if err != nil {
return nil, err
}
return &Target{Name: targetName, Hashes: meta.Hashes, Length: meta.Length, Custom: targetCustom}, nil
}
|
go
|
func NewTarget(targetName, targetPath string, targetCustom *canonicaljson.RawMessage) (*Target, error) {
b, err := ioutil.ReadFile(targetPath)
if err != nil {
return nil, err
}
meta, err := data.NewFileMeta(bytes.NewBuffer(b), data.NotaryDefaultHashes...)
if err != nil {
return nil, err
}
return &Target{Name: targetName, Hashes: meta.Hashes, Length: meta.Length, Custom: targetCustom}, nil
}
|
[
"func",
"NewTarget",
"(",
"targetName",
",",
"targetPath",
"string",
",",
"targetCustom",
"*",
"canonicaljson",
".",
"RawMessage",
")",
"(",
"*",
"Target",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"targetPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"meta",
",",
"err",
":=",
"data",
".",
"NewFileMeta",
"(",
"bytes",
".",
"NewBuffer",
"(",
"b",
")",
",",
"data",
".",
"NotaryDefaultHashes",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"Target",
"{",
"Name",
":",
"targetName",
",",
"Hashes",
":",
"meta",
".",
"Hashes",
",",
"Length",
":",
"meta",
".",
"Length",
",",
"Custom",
":",
"targetCustom",
"}",
",",
"nil",
"\n",
"}"
] |
// NewTarget is a helper method that returns a Target
|
[
"NewTarget",
"is",
"a",
"helper",
"method",
"that",
"returns",
"a",
"Target"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L187-L199
|
train
|
theupdateframework/notary
|
client/client.go
|
rootCertKey
|
func rootCertKey(gun data.GUN, privKey data.PrivateKey) (data.PublicKey, error) {
// Hard-coded policy: the generated certificate expires in 10 years.
startTime := time.Now()
cert, err := cryptoservice.GenerateCertificate(
privKey, gun, startTime, startTime.Add(notary.Year*10))
if err != nil {
return nil, err
}
x509PublicKey := utils.CertToKey(cert)
if x509PublicKey == nil {
return nil, fmt.Errorf("cannot generate public key from private key with id: %v and algorithm: %v", privKey.ID(), privKey.Algorithm())
}
return x509PublicKey, nil
}
|
go
|
func rootCertKey(gun data.GUN, privKey data.PrivateKey) (data.PublicKey, error) {
// Hard-coded policy: the generated certificate expires in 10 years.
startTime := time.Now()
cert, err := cryptoservice.GenerateCertificate(
privKey, gun, startTime, startTime.Add(notary.Year*10))
if err != nil {
return nil, err
}
x509PublicKey := utils.CertToKey(cert)
if x509PublicKey == nil {
return nil, fmt.Errorf("cannot generate public key from private key with id: %v and algorithm: %v", privKey.ID(), privKey.Algorithm())
}
return x509PublicKey, nil
}
|
[
"func",
"rootCertKey",
"(",
"gun",
"data",
".",
"GUN",
",",
"privKey",
"data",
".",
"PrivateKey",
")",
"(",
"data",
".",
"PublicKey",
",",
"error",
")",
"{",
"// Hard-coded policy: the generated certificate expires in 10 years.",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"cert",
",",
"err",
":=",
"cryptoservice",
".",
"GenerateCertificate",
"(",
"privKey",
",",
"gun",
",",
"startTime",
",",
"startTime",
".",
"Add",
"(",
"notary",
".",
"Year",
"*",
"10",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"x509PublicKey",
":=",
"utils",
".",
"CertToKey",
"(",
"cert",
")",
"\n",
"if",
"x509PublicKey",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"privKey",
".",
"ID",
"(",
")",
",",
"privKey",
".",
"Algorithm",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"x509PublicKey",
",",
"nil",
"\n",
"}"
] |
// rootCertKey generates the corresponding certificate for the private key given the privKey and repo's GUN
|
[
"rootCertKey",
"generates",
"the",
"corresponding",
"certificate",
"for",
"the",
"private",
"key",
"given",
"the",
"privKey",
"and",
"repo",
"s",
"GUN"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L202-L217
|
train
|
theupdateframework/notary
|
client/client.go
|
initialize
|
func (r *repository) initialize(rootKeyIDs []string, rootCerts []data.PublicKey, serverManagedRoles ...data.RoleName) error {
// currently we only support server managing timestamps and snapshots, and
// nothing else - timestamps are always managed by the server, and implicit
// (do not have to be passed in as part of `serverManagedRoles`, so that
// the API of Initialize doesn't change).
var serverManagesSnapshot bool
locallyManagedKeys := []data.RoleName{
data.CanonicalTargetsRole,
data.CanonicalSnapshotRole,
// root is also locally managed, but that should have been created
// already
}
remotelyManagedKeys := []data.RoleName{data.CanonicalTimestampRole}
for _, role := range serverManagedRoles {
switch role {
case data.CanonicalTimestampRole:
continue // timestamp is already in the right place
case data.CanonicalSnapshotRole:
// because we put Snapshot last
locallyManagedKeys = []data.RoleName{data.CanonicalTargetsRole}
remotelyManagedKeys = append(
remotelyManagedKeys, data.CanonicalSnapshotRole)
serverManagesSnapshot = true
default:
return ErrInvalidRemoteRole{Role: role}
}
}
// gets valid public keys corresponding to the rootKeyIDs or generate if necessary
var publicKeys []data.PublicKey
var err error
if len(rootCerts) == 0 {
publicKeys, err = r.createNewPublicKeyFromKeyIDs(rootKeyIDs)
} else {
publicKeys, err = r.publicKeysOfKeyIDs(rootKeyIDs, rootCerts)
}
if err != nil {
return err
}
//initialize repo with public keys
rootRole, targetsRole, snapshotRole, timestampRole, err := r.initializeRoles(
publicKeys,
locallyManagedKeys,
remotelyManagedKeys,
)
if err != nil {
return err
}
r.tufRepo = tuf.NewRepo(r.GetCryptoService())
if err := r.tufRepo.InitRoot(
rootRole,
timestampRole,
snapshotRole,
targetsRole,
false,
); err != nil {
logrus.Debug("Error on InitRoot: ", err.Error())
return err
}
if _, err := r.tufRepo.InitTargets(data.CanonicalTargetsRole); err != nil {
logrus.Debug("Error on InitTargets: ", err.Error())
return err
}
if err := r.tufRepo.InitSnapshot(); err != nil {
logrus.Debug("Error on InitSnapshot: ", err.Error())
return err
}
return r.saveMetadata(serverManagesSnapshot)
}
|
go
|
func (r *repository) initialize(rootKeyIDs []string, rootCerts []data.PublicKey, serverManagedRoles ...data.RoleName) error {
// currently we only support server managing timestamps and snapshots, and
// nothing else - timestamps are always managed by the server, and implicit
// (do not have to be passed in as part of `serverManagedRoles`, so that
// the API of Initialize doesn't change).
var serverManagesSnapshot bool
locallyManagedKeys := []data.RoleName{
data.CanonicalTargetsRole,
data.CanonicalSnapshotRole,
// root is also locally managed, but that should have been created
// already
}
remotelyManagedKeys := []data.RoleName{data.CanonicalTimestampRole}
for _, role := range serverManagedRoles {
switch role {
case data.CanonicalTimestampRole:
continue // timestamp is already in the right place
case data.CanonicalSnapshotRole:
// because we put Snapshot last
locallyManagedKeys = []data.RoleName{data.CanonicalTargetsRole}
remotelyManagedKeys = append(
remotelyManagedKeys, data.CanonicalSnapshotRole)
serverManagesSnapshot = true
default:
return ErrInvalidRemoteRole{Role: role}
}
}
// gets valid public keys corresponding to the rootKeyIDs or generate if necessary
var publicKeys []data.PublicKey
var err error
if len(rootCerts) == 0 {
publicKeys, err = r.createNewPublicKeyFromKeyIDs(rootKeyIDs)
} else {
publicKeys, err = r.publicKeysOfKeyIDs(rootKeyIDs, rootCerts)
}
if err != nil {
return err
}
//initialize repo with public keys
rootRole, targetsRole, snapshotRole, timestampRole, err := r.initializeRoles(
publicKeys,
locallyManagedKeys,
remotelyManagedKeys,
)
if err != nil {
return err
}
r.tufRepo = tuf.NewRepo(r.GetCryptoService())
if err := r.tufRepo.InitRoot(
rootRole,
timestampRole,
snapshotRole,
targetsRole,
false,
); err != nil {
logrus.Debug("Error on InitRoot: ", err.Error())
return err
}
if _, err := r.tufRepo.InitTargets(data.CanonicalTargetsRole); err != nil {
logrus.Debug("Error on InitTargets: ", err.Error())
return err
}
if err := r.tufRepo.InitSnapshot(); err != nil {
logrus.Debug("Error on InitSnapshot: ", err.Error())
return err
}
return r.saveMetadata(serverManagesSnapshot)
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"initialize",
"(",
"rootKeyIDs",
"[",
"]",
"string",
",",
"rootCerts",
"[",
"]",
"data",
".",
"PublicKey",
",",
"serverManagedRoles",
"...",
"data",
".",
"RoleName",
")",
"error",
"{",
"// currently we only support server managing timestamps and snapshots, and",
"// nothing else - timestamps are always managed by the server, and implicit",
"// (do not have to be passed in as part of `serverManagedRoles`, so that",
"// the API of Initialize doesn't change).",
"var",
"serverManagesSnapshot",
"bool",
"\n",
"locallyManagedKeys",
":=",
"[",
"]",
"data",
".",
"RoleName",
"{",
"data",
".",
"CanonicalTargetsRole",
",",
"data",
".",
"CanonicalSnapshotRole",
",",
"// root is also locally managed, but that should have been created",
"// already",
"}",
"\n",
"remotelyManagedKeys",
":=",
"[",
"]",
"data",
".",
"RoleName",
"{",
"data",
".",
"CanonicalTimestampRole",
"}",
"\n",
"for",
"_",
",",
"role",
":=",
"range",
"serverManagedRoles",
"{",
"switch",
"role",
"{",
"case",
"data",
".",
"CanonicalTimestampRole",
":",
"continue",
"// timestamp is already in the right place",
"\n",
"case",
"data",
".",
"CanonicalSnapshotRole",
":",
"// because we put Snapshot last",
"locallyManagedKeys",
"=",
"[",
"]",
"data",
".",
"RoleName",
"{",
"data",
".",
"CanonicalTargetsRole",
"}",
"\n",
"remotelyManagedKeys",
"=",
"append",
"(",
"remotelyManagedKeys",
",",
"data",
".",
"CanonicalSnapshotRole",
")",
"\n",
"serverManagesSnapshot",
"=",
"true",
"\n",
"default",
":",
"return",
"ErrInvalidRemoteRole",
"{",
"Role",
":",
"role",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// gets valid public keys corresponding to the rootKeyIDs or generate if necessary",
"var",
"publicKeys",
"[",
"]",
"data",
".",
"PublicKey",
"\n",
"var",
"err",
"error",
"\n",
"if",
"len",
"(",
"rootCerts",
")",
"==",
"0",
"{",
"publicKeys",
",",
"err",
"=",
"r",
".",
"createNewPublicKeyFromKeyIDs",
"(",
"rootKeyIDs",
")",
"\n",
"}",
"else",
"{",
"publicKeys",
",",
"err",
"=",
"r",
".",
"publicKeysOfKeyIDs",
"(",
"rootKeyIDs",
",",
"rootCerts",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"//initialize repo with public keys",
"rootRole",
",",
"targetsRole",
",",
"snapshotRole",
",",
"timestampRole",
",",
"err",
":=",
"r",
".",
"initializeRoles",
"(",
"publicKeys",
",",
"locallyManagedKeys",
",",
"remotelyManagedKeys",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"r",
".",
"tufRepo",
"=",
"tuf",
".",
"NewRepo",
"(",
"r",
".",
"GetCryptoService",
"(",
")",
")",
"\n\n",
"if",
"err",
":=",
"r",
".",
"tufRepo",
".",
"InitRoot",
"(",
"rootRole",
",",
"timestampRole",
",",
"snapshotRole",
",",
"targetsRole",
",",
"false",
",",
")",
";",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"r",
".",
"tufRepo",
".",
"InitTargets",
"(",
"data",
".",
"CanonicalTargetsRole",
")",
";",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"r",
".",
"tufRepo",
".",
"InitSnapshot",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"r",
".",
"saveMetadata",
"(",
"serverManagesSnapshot",
")",
"\n",
"}"
] |
// initialize initializes the notary repository with a set of rootkeys, root certificates and roles.
|
[
"initialize",
"initializes",
"the",
"notary",
"repository",
"with",
"a",
"set",
"of",
"rootkeys",
"root",
"certificates",
"and",
"roles",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L225-L298
|
train
|
theupdateframework/notary
|
client/client.go
|
createNewPublicKeyFromKeyIDs
|
func (r *repository) createNewPublicKeyFromKeyIDs(keyIDs []string) ([]data.PublicKey, error) {
publicKeys := []data.PublicKey{}
privKeys, err := getAllPrivKeys(keyIDs, r.GetCryptoService())
if err != nil {
return nil, err
}
for _, privKey := range privKeys {
rootKey, err := rootCertKey(r.gun, privKey)
if err != nil {
return nil, err
}
publicKeys = append(publicKeys, rootKey)
}
return publicKeys, nil
}
|
go
|
func (r *repository) createNewPublicKeyFromKeyIDs(keyIDs []string) ([]data.PublicKey, error) {
publicKeys := []data.PublicKey{}
privKeys, err := getAllPrivKeys(keyIDs, r.GetCryptoService())
if err != nil {
return nil, err
}
for _, privKey := range privKeys {
rootKey, err := rootCertKey(r.gun, privKey)
if err != nil {
return nil, err
}
publicKeys = append(publicKeys, rootKey)
}
return publicKeys, nil
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"createNewPublicKeyFromKeyIDs",
"(",
"keyIDs",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"data",
".",
"PublicKey",
",",
"error",
")",
"{",
"publicKeys",
":=",
"[",
"]",
"data",
".",
"PublicKey",
"{",
"}",
"\n\n",
"privKeys",
",",
"err",
":=",
"getAllPrivKeys",
"(",
"keyIDs",
",",
"r",
".",
"GetCryptoService",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"privKey",
":=",
"range",
"privKeys",
"{",
"rootKey",
",",
"err",
":=",
"rootCertKey",
"(",
"r",
".",
"gun",
",",
"privKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"publicKeys",
"=",
"append",
"(",
"publicKeys",
",",
"rootKey",
")",
"\n",
"}",
"\n",
"return",
"publicKeys",
",",
"nil",
"\n",
"}"
] |
// createNewPublicKeyFromKeyIDs generates a set of public keys corresponding to the given list of
// key IDs existing in the repository's CryptoService.
// the public keys returned are ordered to correspond to the keyIDs
|
[
"createNewPublicKeyFromKeyIDs",
"generates",
"a",
"set",
"of",
"public",
"keys",
"corresponding",
"to",
"the",
"given",
"list",
"of",
"key",
"IDs",
"existing",
"in",
"the",
"repository",
"s",
"CryptoService",
".",
"the",
"public",
"keys",
"returned",
"are",
"ordered",
"to",
"correspond",
"to",
"the",
"keyIDs"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L303-L319
|
train
|
theupdateframework/notary
|
client/client.go
|
keyExistsInList
|
func keyExistsInList(cert data.PublicKey, ids map[string]bool) error {
pubKeyID, err := utils.CanonicalKeyID(cert)
if err != nil {
return fmt.Errorf("failed to obtain the public key id from the given certificate: %v", err)
}
if _, ok := ids[pubKeyID]; ok {
return nil
}
return errKeyNotFound{}
}
|
go
|
func keyExistsInList(cert data.PublicKey, ids map[string]bool) error {
pubKeyID, err := utils.CanonicalKeyID(cert)
if err != nil {
return fmt.Errorf("failed to obtain the public key id from the given certificate: %v", err)
}
if _, ok := ids[pubKeyID]; ok {
return nil
}
return errKeyNotFound{}
}
|
[
"func",
"keyExistsInList",
"(",
"cert",
"data",
".",
"PublicKey",
",",
"ids",
"map",
"[",
"string",
"]",
"bool",
")",
"error",
"{",
"pubKeyID",
",",
"err",
":=",
"utils",
".",
"CanonicalKeyID",
"(",
"cert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"ids",
"[",
"pubKeyID",
"]",
";",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"errKeyNotFound",
"{",
"}",
"\n",
"}"
] |
// keyExistsInList returns the id of the private key in ids that matches the public key
// otherwise return empty string
|
[
"keyExistsInList",
"returns",
"the",
"id",
"of",
"the",
"private",
"key",
"in",
"ids",
"that",
"matches",
"the",
"public",
"key",
"otherwise",
"return",
"empty",
"string"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L371-L380
|
train
|
theupdateframework/notary
|
client/client.go
|
InitializeWithCertificate
|
func (r *repository) InitializeWithCertificate(rootKeyIDs []string, rootCerts []data.PublicKey,
serverManagedRoles ...data.RoleName) error {
// If we explicitly pass in certificate(s) but not key, then look keys up using certificate
if len(rootKeyIDs) == 0 && len(rootCerts) != 0 {
rootKeyIDs = []string{}
availableRootKeyIDs := make(map[string]bool)
for _, k := range r.GetCryptoService().ListKeys(data.CanonicalRootRole) {
availableRootKeyIDs[k] = true
}
for _, cert := range rootCerts {
if err := keyExistsInList(cert, availableRootKeyIDs); err != nil {
return fmt.Errorf("error initializing repository with certificate: %v", err)
}
keyID, _ := utils.CanonicalKeyID(cert)
rootKeyIDs = append(rootKeyIDs, keyID)
}
}
return r.initialize(rootKeyIDs, rootCerts, serverManagedRoles...)
}
|
go
|
func (r *repository) InitializeWithCertificate(rootKeyIDs []string, rootCerts []data.PublicKey,
serverManagedRoles ...data.RoleName) error {
// If we explicitly pass in certificate(s) but not key, then look keys up using certificate
if len(rootKeyIDs) == 0 && len(rootCerts) != 0 {
rootKeyIDs = []string{}
availableRootKeyIDs := make(map[string]bool)
for _, k := range r.GetCryptoService().ListKeys(data.CanonicalRootRole) {
availableRootKeyIDs[k] = true
}
for _, cert := range rootCerts {
if err := keyExistsInList(cert, availableRootKeyIDs); err != nil {
return fmt.Errorf("error initializing repository with certificate: %v", err)
}
keyID, _ := utils.CanonicalKeyID(cert)
rootKeyIDs = append(rootKeyIDs, keyID)
}
}
return r.initialize(rootKeyIDs, rootCerts, serverManagedRoles...)
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"InitializeWithCertificate",
"(",
"rootKeyIDs",
"[",
"]",
"string",
",",
"rootCerts",
"[",
"]",
"data",
".",
"PublicKey",
",",
"serverManagedRoles",
"...",
"data",
".",
"RoleName",
")",
"error",
"{",
"// If we explicitly pass in certificate(s) but not key, then look keys up using certificate",
"if",
"len",
"(",
"rootKeyIDs",
")",
"==",
"0",
"&&",
"len",
"(",
"rootCerts",
")",
"!=",
"0",
"{",
"rootKeyIDs",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"availableRootKeyIDs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"r",
".",
"GetCryptoService",
"(",
")",
".",
"ListKeys",
"(",
"data",
".",
"CanonicalRootRole",
")",
"{",
"availableRootKeyIDs",
"[",
"k",
"]",
"=",
"true",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"cert",
":=",
"range",
"rootCerts",
"{",
"if",
"err",
":=",
"keyExistsInList",
"(",
"cert",
",",
"availableRootKeyIDs",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"keyID",
",",
"_",
":=",
"utils",
".",
"CanonicalKeyID",
"(",
"cert",
")",
"\n",
"rootKeyIDs",
"=",
"append",
"(",
"rootKeyIDs",
",",
"keyID",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"r",
".",
"initialize",
"(",
"rootKeyIDs",
",",
"rootCerts",
",",
"serverManagedRoles",
"...",
")",
"\n",
"}"
] |
// InitializeWithCertificate initializes the repository with root keys and their corresponding certificates
|
[
"InitializeWithCertificate",
"initializes",
"the",
"repository",
"with",
"root",
"keys",
"and",
"their",
"corresponding",
"certificates"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L383-L403
|
train
|
theupdateframework/notary
|
client/client.go
|
addChange
|
func addChange(cl changelist.Changelist, c changelist.Change, roles ...data.RoleName) error {
if len(roles) == 0 {
roles = []data.RoleName{data.CanonicalTargetsRole}
}
var changes []changelist.Change
for _, role := range roles {
// Ensure we can only add targets to the CanonicalTargetsRole,
// or a Delegation role (which is <CanonicalTargetsRole>/something else)
if role != data.CanonicalTargetsRole && !data.IsDelegation(role) && !data.IsWildDelegation(role) {
return data.ErrInvalidRole{
Role: role,
Reason: "cannot add targets to this role",
}
}
changes = append(changes, changelist.NewTUFChange(
c.Action(),
role,
c.Type(),
c.Path(),
c.Content(),
))
}
for _, c := range changes {
if err := cl.Add(c); err != nil {
return err
}
}
return nil
}
|
go
|
func addChange(cl changelist.Changelist, c changelist.Change, roles ...data.RoleName) error {
if len(roles) == 0 {
roles = []data.RoleName{data.CanonicalTargetsRole}
}
var changes []changelist.Change
for _, role := range roles {
// Ensure we can only add targets to the CanonicalTargetsRole,
// or a Delegation role (which is <CanonicalTargetsRole>/something else)
if role != data.CanonicalTargetsRole && !data.IsDelegation(role) && !data.IsWildDelegation(role) {
return data.ErrInvalidRole{
Role: role,
Reason: "cannot add targets to this role",
}
}
changes = append(changes, changelist.NewTUFChange(
c.Action(),
role,
c.Type(),
c.Path(),
c.Content(),
))
}
for _, c := range changes {
if err := cl.Add(c); err != nil {
return err
}
}
return nil
}
|
[
"func",
"addChange",
"(",
"cl",
"changelist",
".",
"Changelist",
",",
"c",
"changelist",
".",
"Change",
",",
"roles",
"...",
"data",
".",
"RoleName",
")",
"error",
"{",
"if",
"len",
"(",
"roles",
")",
"==",
"0",
"{",
"roles",
"=",
"[",
"]",
"data",
".",
"RoleName",
"{",
"data",
".",
"CanonicalTargetsRole",
"}",
"\n",
"}",
"\n\n",
"var",
"changes",
"[",
"]",
"changelist",
".",
"Change",
"\n",
"for",
"_",
",",
"role",
":=",
"range",
"roles",
"{",
"// Ensure we can only add targets to the CanonicalTargetsRole,",
"// or a Delegation role (which is <CanonicalTargetsRole>/something else)",
"if",
"role",
"!=",
"data",
".",
"CanonicalTargetsRole",
"&&",
"!",
"data",
".",
"IsDelegation",
"(",
"role",
")",
"&&",
"!",
"data",
".",
"IsWildDelegation",
"(",
"role",
")",
"{",
"return",
"data",
".",
"ErrInvalidRole",
"{",
"Role",
":",
"role",
",",
"Reason",
":",
"\"",
"\"",
",",
"}",
"\n",
"}",
"\n\n",
"changes",
"=",
"append",
"(",
"changes",
",",
"changelist",
".",
"NewTUFChange",
"(",
"c",
".",
"Action",
"(",
")",
",",
"role",
",",
"c",
".",
"Type",
"(",
")",
",",
"c",
".",
"Path",
"(",
")",
",",
"c",
".",
"Content",
"(",
")",
",",
")",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"c",
":=",
"range",
"changes",
"{",
"if",
"err",
":=",
"cl",
".",
"Add",
"(",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// adds a TUF Change template to the given roles
|
[
"adds",
"a",
"TUF",
"Change",
"template",
"to",
"the",
"given",
"roles"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L468-L499
|
train
|
theupdateframework/notary
|
client/client.go
|
AddTarget
|
func (r *repository) AddTarget(target *Target, roles ...data.RoleName) error {
if len(target.Hashes) == 0 {
return fmt.Errorf("no hashes specified for target \"%s\"", target.Name)
}
logrus.Debugf("Adding target \"%s\" with sha256 \"%x\" and size %d bytes.\n", target.Name, target.Hashes["sha256"], target.Length)
meta := data.FileMeta{Length: target.Length, Hashes: target.Hashes, Custom: target.Custom}
metaJSON, err := json.Marshal(meta)
if err != nil {
return err
}
template := changelist.NewTUFChange(
changelist.ActionCreate, "", changelist.TypeTargetsTarget,
target.Name, metaJSON)
return addChange(r.changelist, template, roles...)
}
|
go
|
func (r *repository) AddTarget(target *Target, roles ...data.RoleName) error {
if len(target.Hashes) == 0 {
return fmt.Errorf("no hashes specified for target \"%s\"", target.Name)
}
logrus.Debugf("Adding target \"%s\" with sha256 \"%x\" and size %d bytes.\n", target.Name, target.Hashes["sha256"], target.Length)
meta := data.FileMeta{Length: target.Length, Hashes: target.Hashes, Custom: target.Custom}
metaJSON, err := json.Marshal(meta)
if err != nil {
return err
}
template := changelist.NewTUFChange(
changelist.ActionCreate, "", changelist.TypeTargetsTarget,
target.Name, metaJSON)
return addChange(r.changelist, template, roles...)
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"AddTarget",
"(",
"target",
"*",
"Target",
",",
"roles",
"...",
"data",
".",
"RoleName",
")",
"error",
"{",
"if",
"len",
"(",
"target",
".",
"Hashes",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"target",
".",
"Name",
")",
"\n",
"}",
"\n",
"logrus",
".",
"Debugf",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\\n",
"\"",
",",
"target",
".",
"Name",
",",
"target",
".",
"Hashes",
"[",
"\"",
"\"",
"]",
",",
"target",
".",
"Length",
")",
"\n\n",
"meta",
":=",
"data",
".",
"FileMeta",
"{",
"Length",
":",
"target",
".",
"Length",
",",
"Hashes",
":",
"target",
".",
"Hashes",
",",
"Custom",
":",
"target",
".",
"Custom",
"}",
"\n",
"metaJSON",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"meta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"template",
":=",
"changelist",
".",
"NewTUFChange",
"(",
"changelist",
".",
"ActionCreate",
",",
"\"",
"\"",
",",
"changelist",
".",
"TypeTargetsTarget",
",",
"target",
".",
"Name",
",",
"metaJSON",
")",
"\n",
"return",
"addChange",
"(",
"r",
".",
"changelist",
",",
"template",
",",
"roles",
"...",
")",
"\n",
"}"
] |
// AddTarget creates new changelist entries to add a target to the given roles
// in the repository when the changelist gets applied at publish time.
// If roles are unspecified, the default role is "targets"
|
[
"AddTarget",
"creates",
"new",
"changelist",
"entries",
"to",
"add",
"a",
"target",
"to",
"the",
"given",
"roles",
"in",
"the",
"repository",
"when",
"the",
"changelist",
"gets",
"applied",
"at",
"publish",
"time",
".",
"If",
"roles",
"are",
"unspecified",
"the",
"default",
"role",
"is",
"targets"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L504-L520
|
train
|
theupdateframework/notary
|
client/client.go
|
RemoveTarget
|
func (r *repository) RemoveTarget(targetName string, roles ...data.RoleName) error {
logrus.Debugf("Removing target \"%s\"", targetName)
template := changelist.NewTUFChange(changelist.ActionDelete, "",
changelist.TypeTargetsTarget, targetName, nil)
return addChange(r.changelist, template, roles...)
}
|
go
|
func (r *repository) RemoveTarget(targetName string, roles ...data.RoleName) error {
logrus.Debugf("Removing target \"%s\"", targetName)
template := changelist.NewTUFChange(changelist.ActionDelete, "",
changelist.TypeTargetsTarget, targetName, nil)
return addChange(r.changelist, template, roles...)
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"RemoveTarget",
"(",
"targetName",
"string",
",",
"roles",
"...",
"data",
".",
"RoleName",
")",
"error",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"targetName",
")",
"\n",
"template",
":=",
"changelist",
".",
"NewTUFChange",
"(",
"changelist",
".",
"ActionDelete",
",",
"\"",
"\"",
",",
"changelist",
".",
"TypeTargetsTarget",
",",
"targetName",
",",
"nil",
")",
"\n",
"return",
"addChange",
"(",
"r",
".",
"changelist",
",",
"template",
",",
"roles",
"...",
")",
"\n",
"}"
] |
// RemoveTarget creates new changelist entries to remove a target from the given
// roles in the repository when the changelist gets applied at publish time.
// If roles are unspecified, the default role is "target".
|
[
"RemoveTarget",
"creates",
"new",
"changelist",
"entries",
"to",
"remove",
"a",
"target",
"from",
"the",
"given",
"roles",
"in",
"the",
"repository",
"when",
"the",
"changelist",
"gets",
"applied",
"at",
"publish",
"time",
".",
"If",
"roles",
"are",
"unspecified",
"the",
"default",
"role",
"is",
"target",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L525-L530
|
train
|
theupdateframework/notary
|
client/client.go
|
getRemoteStore
|
func (r *repository) getRemoteStore() store.RemoteStore {
if r.remoteStore != nil {
return r.remoteStore
}
r.remoteStore = &store.OfflineStore{}
return r.remoteStore
}
|
go
|
func (r *repository) getRemoteStore() store.RemoteStore {
if r.remoteStore != nil {
return r.remoteStore
}
r.remoteStore = &store.OfflineStore{}
return r.remoteStore
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"getRemoteStore",
"(",
")",
"store",
".",
"RemoteStore",
"{",
"if",
"r",
".",
"remoteStore",
"!=",
"nil",
"{",
"return",
"r",
".",
"remoteStore",
"\n",
"}",
"\n\n",
"r",
".",
"remoteStore",
"=",
"&",
"store",
".",
"OfflineStore",
"{",
"}",
"\n\n",
"return",
"r",
".",
"remoteStore",
"\n",
"}"
] |
// getRemoteStore returns the remoteStore of a repository if valid or
// or an OfflineStore otherwise
|
[
"getRemoteStore",
"returns",
"the",
"remoteStore",
"of",
"a",
"repository",
"if",
"valid",
"or",
"or",
"an",
"OfflineStore",
"otherwise"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L539-L547
|
train
|
theupdateframework/notary
|
client/client.go
|
Publish
|
func (r *repository) Publish() error {
if err := r.publish(r.changelist); err != nil {
return err
}
if err := r.changelist.Clear(""); err != nil {
// This is not a critical problem when only a single host is pushing
// but will cause weird behaviour if changelist cleanup is failing
// and there are multiple hosts writing to the repo.
logrus.Warn("Unable to clear changelist. You may want to manually delete the folder ", r.changelist.Location())
}
return nil
}
|
go
|
func (r *repository) Publish() error {
if err := r.publish(r.changelist); err != nil {
return err
}
if err := r.changelist.Clear(""); err != nil {
// This is not a critical problem when only a single host is pushing
// but will cause weird behaviour if changelist cleanup is failing
// and there are multiple hosts writing to the repo.
logrus.Warn("Unable to clear changelist. You may want to manually delete the folder ", r.changelist.Location())
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"Publish",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"r",
".",
"publish",
"(",
"r",
".",
"changelist",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"r",
".",
"changelist",
".",
"Clear",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"// This is not a critical problem when only a single host is pushing",
"// but will cause weird behaviour if changelist cleanup is failing",
"// and there are multiple hosts writing to the repo.",
"logrus",
".",
"Warn",
"(",
"\"",
"\"",
",",
"r",
".",
"changelist",
".",
"Location",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Publish pushes the local changes in signed material to the remote notary-server
// Conceptually it performs an operation similar to a `git rebase`
|
[
"Publish",
"pushes",
"the",
"local",
"changes",
"in",
"signed",
"material",
"to",
"the",
"remote",
"notary",
"-",
"server",
"Conceptually",
"it",
"performs",
"an",
"operation",
"similar",
"to",
"a",
"git",
"rebase"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L551-L562
|
train
|
theupdateframework/notary
|
client/client.go
|
publish
|
func (r *repository) publish(cl changelist.Changelist) error {
var initialPublish bool
// update first before publishing
if err := r.updateTUF(true); err != nil {
// If the remote is not aware of the repo, then this is being published
// for the first time. Try to initialize the repository before publishing.
if _, ok := err.(ErrRepositoryNotExist); ok {
err := r.bootstrapRepo()
if _, ok := err.(store.ErrMetaNotFound); ok {
logrus.Infof("No TUF data found locally or remotely - initializing repository %s for the first time", r.gun.String())
err = r.Initialize(nil)
}
if err != nil {
logrus.WithError(err).Debugf("Unable to load or initialize repository during first publish: %s", err.Error())
return err
}
// Ensure we will push the initial root and targets file. Either or
// both of the root and targets may not be marked as Dirty, since
// there may not be any changes that update them, so use a
// different boolean.
initialPublish = true
} else {
// We could not update, so we cannot publish.
logrus.Error("Could not publish Repository since we could not update: ", err.Error())
return err
}
}
// apply the changelist to the repo
if err := applyChangelist(r.tufRepo, r.invalid, cl); err != nil {
logrus.Debug("Error applying changelist")
return err
}
// these are the TUF files we will need to update, serialized as JSON before
// we send anything to remote
updatedFiles := make(map[data.RoleName][]byte)
// Fetch old keys to support old clients
legacyKeys, err := r.oldKeysForLegacyClientSupport(r.LegacyVersions, initialPublish)
if err != nil {
return err
}
// check if our root file is nearing expiry or dirty. Resign if it is. If
// root is not dirty but we are publishing for the first time, then just
// publish the existing root we have.
if err := signRootIfNecessary(updatedFiles, r.tufRepo, legacyKeys, initialPublish); err != nil {
return err
}
if err := signTargets(updatedFiles, r.tufRepo, initialPublish); err != nil {
return err
}
// if we initialized the repo while designating the server as the snapshot
// signer, then there won't be a snapshots file. However, we might now
// have a local key (if there was a rotation), so initialize one.
if r.tufRepo.Snapshot == nil {
if err := r.tufRepo.InitSnapshot(); err != nil {
return err
}
}
if snapshotJSON, err := serializeCanonicalRole(
r.tufRepo, data.CanonicalSnapshotRole, nil); err == nil {
// Only update the snapshot if we've successfully signed it.
updatedFiles[data.CanonicalSnapshotRole] = snapshotJSON
} else if signErr, ok := err.(signed.ErrInsufficientSignatures); ok && signErr.FoundKeys == 0 {
// If signing fails due to us not having the snapshot key, then
// assume the server is going to sign, and do not include any snapshot
// data.
logrus.Debugf("Client does not have the key to sign snapshot. " +
"Assuming that server should sign the snapshot.")
} else {
logrus.Debugf("Client was unable to sign the snapshot: %s", err.Error())
return err
}
remote := r.getRemoteStore()
return remote.SetMulti(data.MetadataRoleMapToStringMap(updatedFiles))
}
|
go
|
func (r *repository) publish(cl changelist.Changelist) error {
var initialPublish bool
// update first before publishing
if err := r.updateTUF(true); err != nil {
// If the remote is not aware of the repo, then this is being published
// for the first time. Try to initialize the repository before publishing.
if _, ok := err.(ErrRepositoryNotExist); ok {
err := r.bootstrapRepo()
if _, ok := err.(store.ErrMetaNotFound); ok {
logrus.Infof("No TUF data found locally or remotely - initializing repository %s for the first time", r.gun.String())
err = r.Initialize(nil)
}
if err != nil {
logrus.WithError(err).Debugf("Unable to load or initialize repository during first publish: %s", err.Error())
return err
}
// Ensure we will push the initial root and targets file. Either or
// both of the root and targets may not be marked as Dirty, since
// there may not be any changes that update them, so use a
// different boolean.
initialPublish = true
} else {
// We could not update, so we cannot publish.
logrus.Error("Could not publish Repository since we could not update: ", err.Error())
return err
}
}
// apply the changelist to the repo
if err := applyChangelist(r.tufRepo, r.invalid, cl); err != nil {
logrus.Debug("Error applying changelist")
return err
}
// these are the TUF files we will need to update, serialized as JSON before
// we send anything to remote
updatedFiles := make(map[data.RoleName][]byte)
// Fetch old keys to support old clients
legacyKeys, err := r.oldKeysForLegacyClientSupport(r.LegacyVersions, initialPublish)
if err != nil {
return err
}
// check if our root file is nearing expiry or dirty. Resign if it is. If
// root is not dirty but we are publishing for the first time, then just
// publish the existing root we have.
if err := signRootIfNecessary(updatedFiles, r.tufRepo, legacyKeys, initialPublish); err != nil {
return err
}
if err := signTargets(updatedFiles, r.tufRepo, initialPublish); err != nil {
return err
}
// if we initialized the repo while designating the server as the snapshot
// signer, then there won't be a snapshots file. However, we might now
// have a local key (if there was a rotation), so initialize one.
if r.tufRepo.Snapshot == nil {
if err := r.tufRepo.InitSnapshot(); err != nil {
return err
}
}
if snapshotJSON, err := serializeCanonicalRole(
r.tufRepo, data.CanonicalSnapshotRole, nil); err == nil {
// Only update the snapshot if we've successfully signed it.
updatedFiles[data.CanonicalSnapshotRole] = snapshotJSON
} else if signErr, ok := err.(signed.ErrInsufficientSignatures); ok && signErr.FoundKeys == 0 {
// If signing fails due to us not having the snapshot key, then
// assume the server is going to sign, and do not include any snapshot
// data.
logrus.Debugf("Client does not have the key to sign snapshot. " +
"Assuming that server should sign the snapshot.")
} else {
logrus.Debugf("Client was unable to sign the snapshot: %s", err.Error())
return err
}
remote := r.getRemoteStore()
return remote.SetMulti(data.MetadataRoleMapToStringMap(updatedFiles))
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"publish",
"(",
"cl",
"changelist",
".",
"Changelist",
")",
"error",
"{",
"var",
"initialPublish",
"bool",
"\n",
"// update first before publishing",
"if",
"err",
":=",
"r",
".",
"updateTUF",
"(",
"true",
")",
";",
"err",
"!=",
"nil",
"{",
"// If the remote is not aware of the repo, then this is being published",
"// for the first time. Try to initialize the repository before publishing.",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"ErrRepositoryNotExist",
")",
";",
"ok",
"{",
"err",
":=",
"r",
".",
"bootstrapRepo",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"store",
".",
"ErrMetaNotFound",
")",
";",
"ok",
"{",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"r",
".",
"gun",
".",
"String",
"(",
")",
")",
"\n",
"err",
"=",
"r",
".",
"Initialize",
"(",
"nil",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"WithError",
"(",
"err",
")",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Ensure we will push the initial root and targets file. Either or",
"// both of the root and targets may not be marked as Dirty, since",
"// there may not be any changes that update them, so use a",
"// different boolean.",
"initialPublish",
"=",
"true",
"\n",
"}",
"else",
"{",
"// We could not update, so we cannot publish.",
"logrus",
".",
"Error",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// apply the changelist to the repo",
"if",
"err",
":=",
"applyChangelist",
"(",
"r",
".",
"tufRepo",
",",
"r",
".",
"invalid",
",",
"cl",
")",
";",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// these are the TUF files we will need to update, serialized as JSON before",
"// we send anything to remote",
"updatedFiles",
":=",
"make",
"(",
"map",
"[",
"data",
".",
"RoleName",
"]",
"[",
"]",
"byte",
")",
"\n\n",
"// Fetch old keys to support old clients",
"legacyKeys",
",",
"err",
":=",
"r",
".",
"oldKeysForLegacyClientSupport",
"(",
"r",
".",
"LegacyVersions",
",",
"initialPublish",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// check if our root file is nearing expiry or dirty. Resign if it is. If",
"// root is not dirty but we are publishing for the first time, then just",
"// publish the existing root we have.",
"if",
"err",
":=",
"signRootIfNecessary",
"(",
"updatedFiles",
",",
"r",
".",
"tufRepo",
",",
"legacyKeys",
",",
"initialPublish",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"signTargets",
"(",
"updatedFiles",
",",
"r",
".",
"tufRepo",
",",
"initialPublish",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// if we initialized the repo while designating the server as the snapshot",
"// signer, then there won't be a snapshots file. However, we might now",
"// have a local key (if there was a rotation), so initialize one.",
"if",
"r",
".",
"tufRepo",
".",
"Snapshot",
"==",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"tufRepo",
".",
"InitSnapshot",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"snapshotJSON",
",",
"err",
":=",
"serializeCanonicalRole",
"(",
"r",
".",
"tufRepo",
",",
"data",
".",
"CanonicalSnapshotRole",
",",
"nil",
")",
";",
"err",
"==",
"nil",
"{",
"// Only update the snapshot if we've successfully signed it.",
"updatedFiles",
"[",
"data",
".",
"CanonicalSnapshotRole",
"]",
"=",
"snapshotJSON",
"\n",
"}",
"else",
"if",
"signErr",
",",
"ok",
":=",
"err",
".",
"(",
"signed",
".",
"ErrInsufficientSignatures",
")",
";",
"ok",
"&&",
"signErr",
".",
"FoundKeys",
"==",
"0",
"{",
"// If signing fails due to us not having the snapshot key, then",
"// assume the server is going to sign, and do not include any snapshot",
"// data.",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"remote",
":=",
"r",
".",
"getRemoteStore",
"(",
")",
"\n\n",
"return",
"remote",
".",
"SetMulti",
"(",
"data",
".",
"MetadataRoleMapToStringMap",
"(",
"updatedFiles",
")",
")",
"\n",
"}"
] |
// publish pushes the changes in the given changelist to the remote notary-server
// Conceptually it performs an operation similar to a `git rebase`
|
[
"publish",
"pushes",
"the",
"changes",
"in",
"the",
"given",
"changelist",
"to",
"the",
"remote",
"notary",
"-",
"server",
"Conceptually",
"it",
"performs",
"an",
"operation",
"similar",
"to",
"a",
"git",
"rebase"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L566-L649
|
train
|
theupdateframework/notary
|
client/client.go
|
getOldRootPublicKeys
|
func getOldRootPublicKeys(root *data.SignedRoot) data.KeyList {
rootRole, err := root.BuildBaseRole(data.CanonicalRootRole)
if err != nil {
return nil
}
return rootRole.ListKeys()
}
|
go
|
func getOldRootPublicKeys(root *data.SignedRoot) data.KeyList {
rootRole, err := root.BuildBaseRole(data.CanonicalRootRole)
if err != nil {
return nil
}
return rootRole.ListKeys()
}
|
[
"func",
"getOldRootPublicKeys",
"(",
"root",
"*",
"data",
".",
"SignedRoot",
")",
"data",
".",
"KeyList",
"{",
"rootRole",
",",
"err",
":=",
"root",
".",
"BuildBaseRole",
"(",
"data",
".",
"CanonicalRootRole",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"rootRole",
".",
"ListKeys",
"(",
")",
"\n",
"}"
] |
// get all the saved previous roles keys < the current root version
|
[
"get",
"all",
"the",
"saved",
"previous",
"roles",
"keys",
"<",
"the",
"current",
"root",
"version"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L743-L749
|
train
|
theupdateframework/notary
|
client/client.go
|
saveMetadata
|
func (r *repository) saveMetadata(ignoreSnapshot bool) error {
logrus.Debugf("Saving changes to Trusted Collection.")
rootJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalRootRole, nil)
if err != nil {
return err
}
err = r.cache.Set(data.CanonicalRootRole.String(), rootJSON)
if err != nil {
return err
}
targetsToSave := make(map[data.RoleName][]byte)
for t := range r.tufRepo.Targets {
signedTargets, err := r.tufRepo.SignTargets(t, data.DefaultExpires(data.CanonicalTargetsRole))
if err != nil {
return err
}
targetsJSON, err := json.Marshal(signedTargets)
if err != nil {
return err
}
targetsToSave[t] = targetsJSON
}
for role, blob := range targetsToSave {
// If the parent directory does not exist, the cache.Set will create it
r.cache.Set(role.String(), blob)
}
if ignoreSnapshot {
return nil
}
snapshotJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalSnapshotRole, nil)
if err != nil {
return err
}
return r.cache.Set(data.CanonicalSnapshotRole.String(), snapshotJSON)
}
|
go
|
func (r *repository) saveMetadata(ignoreSnapshot bool) error {
logrus.Debugf("Saving changes to Trusted Collection.")
rootJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalRootRole, nil)
if err != nil {
return err
}
err = r.cache.Set(data.CanonicalRootRole.String(), rootJSON)
if err != nil {
return err
}
targetsToSave := make(map[data.RoleName][]byte)
for t := range r.tufRepo.Targets {
signedTargets, err := r.tufRepo.SignTargets(t, data.DefaultExpires(data.CanonicalTargetsRole))
if err != nil {
return err
}
targetsJSON, err := json.Marshal(signedTargets)
if err != nil {
return err
}
targetsToSave[t] = targetsJSON
}
for role, blob := range targetsToSave {
// If the parent directory does not exist, the cache.Set will create it
r.cache.Set(role.String(), blob)
}
if ignoreSnapshot {
return nil
}
snapshotJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalSnapshotRole, nil)
if err != nil {
return err
}
return r.cache.Set(data.CanonicalSnapshotRole.String(), snapshotJSON)
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"saveMetadata",
"(",
"ignoreSnapshot",
"bool",
")",
"error",
"{",
"logrus",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n\n",
"rootJSON",
",",
"err",
":=",
"serializeCanonicalRole",
"(",
"r",
".",
"tufRepo",
",",
"data",
".",
"CanonicalRootRole",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"r",
".",
"cache",
".",
"Set",
"(",
"data",
".",
"CanonicalRootRole",
".",
"String",
"(",
")",
",",
"rootJSON",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"targetsToSave",
":=",
"make",
"(",
"map",
"[",
"data",
".",
"RoleName",
"]",
"[",
"]",
"byte",
")",
"\n",
"for",
"t",
":=",
"range",
"r",
".",
"tufRepo",
".",
"Targets",
"{",
"signedTargets",
",",
"err",
":=",
"r",
".",
"tufRepo",
".",
"SignTargets",
"(",
"t",
",",
"data",
".",
"DefaultExpires",
"(",
"data",
".",
"CanonicalTargetsRole",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"targetsJSON",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"signedTargets",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"targetsToSave",
"[",
"t",
"]",
"=",
"targetsJSON",
"\n",
"}",
"\n\n",
"for",
"role",
",",
"blob",
":=",
"range",
"targetsToSave",
"{",
"// If the parent directory does not exist, the cache.Set will create it",
"r",
".",
"cache",
".",
"Set",
"(",
"role",
".",
"String",
"(",
")",
",",
"blob",
")",
"\n",
"}",
"\n\n",
"if",
"ignoreSnapshot",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"snapshotJSON",
",",
"err",
":=",
"serializeCanonicalRole",
"(",
"r",
".",
"tufRepo",
",",
"data",
".",
"CanonicalSnapshotRole",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"r",
".",
"cache",
".",
"Set",
"(",
"data",
".",
"CanonicalSnapshotRole",
".",
"String",
"(",
")",
",",
"snapshotJSON",
")",
"\n",
"}"
] |
// saveMetadata saves contents of r.tufRepo onto the local disk, creating
// signatures as necessary, possibly prompting for passphrases.
|
[
"saveMetadata",
"saves",
"contents",
"of",
"r",
".",
"tufRepo",
"onto",
"the",
"local",
"disk",
"creating",
"signatures",
"as",
"necessary",
"possibly",
"prompting",
"for",
"passphrases",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L801-L841
|
train
|
theupdateframework/notary
|
client/client.go
|
pubKeyListForRotation
|
func (r *repository) pubKeyListForRotation(role data.RoleName, serverManaged bool, newKeys []string) (pubKeyList data.KeyList, err error) {
var pubKey data.PublicKey
// If server manages the key being rotated, request a rotation and return the new key
if serverManaged {
remote := r.getRemoteStore()
pubKey, err = rotateRemoteKey(role, remote)
pubKeyList = make(data.KeyList, 0, 1)
pubKeyList = append(pubKeyList, pubKey)
if err != nil {
return nil, fmt.Errorf("unable to rotate remote key: %s", err)
}
return pubKeyList, nil
}
// If no new keys are passed in, we generate one
if len(newKeys) == 0 {
pubKeyList = make(data.KeyList, 0, 1)
pubKey, err = r.GetCryptoService().Create(role, r.gun, data.ECDSAKey)
pubKeyList = append(pubKeyList, pubKey)
}
if err != nil {
return nil, fmt.Errorf("unable to generate key: %s", err)
}
// If a list of keys to rotate to are provided, we add those
if len(newKeys) > 0 {
pubKeyList = make(data.KeyList, 0, len(newKeys))
for _, keyID := range newKeys {
pubKey = r.GetCryptoService().GetKey(keyID)
if pubKey == nil {
return nil, fmt.Errorf("unable to find key: %s", keyID)
}
pubKeyList = append(pubKeyList, pubKey)
}
}
// Convert to certs (for root keys)
if pubKeyList, err = r.pubKeysToCerts(role, pubKeyList); err != nil {
return nil, err
}
return pubKeyList, nil
}
|
go
|
func (r *repository) pubKeyListForRotation(role data.RoleName, serverManaged bool, newKeys []string) (pubKeyList data.KeyList, err error) {
var pubKey data.PublicKey
// If server manages the key being rotated, request a rotation and return the new key
if serverManaged {
remote := r.getRemoteStore()
pubKey, err = rotateRemoteKey(role, remote)
pubKeyList = make(data.KeyList, 0, 1)
pubKeyList = append(pubKeyList, pubKey)
if err != nil {
return nil, fmt.Errorf("unable to rotate remote key: %s", err)
}
return pubKeyList, nil
}
// If no new keys are passed in, we generate one
if len(newKeys) == 0 {
pubKeyList = make(data.KeyList, 0, 1)
pubKey, err = r.GetCryptoService().Create(role, r.gun, data.ECDSAKey)
pubKeyList = append(pubKeyList, pubKey)
}
if err != nil {
return nil, fmt.Errorf("unable to generate key: %s", err)
}
// If a list of keys to rotate to are provided, we add those
if len(newKeys) > 0 {
pubKeyList = make(data.KeyList, 0, len(newKeys))
for _, keyID := range newKeys {
pubKey = r.GetCryptoService().GetKey(keyID)
if pubKey == nil {
return nil, fmt.Errorf("unable to find key: %s", keyID)
}
pubKeyList = append(pubKeyList, pubKey)
}
}
// Convert to certs (for root keys)
if pubKeyList, err = r.pubKeysToCerts(role, pubKeyList); err != nil {
return nil, err
}
return pubKeyList, nil
}
|
[
"func",
"(",
"r",
"*",
"repository",
")",
"pubKeyListForRotation",
"(",
"role",
"data",
".",
"RoleName",
",",
"serverManaged",
"bool",
",",
"newKeys",
"[",
"]",
"string",
")",
"(",
"pubKeyList",
"data",
".",
"KeyList",
",",
"err",
"error",
")",
"{",
"var",
"pubKey",
"data",
".",
"PublicKey",
"\n\n",
"// If server manages the key being rotated, request a rotation and return the new key",
"if",
"serverManaged",
"{",
"remote",
":=",
"r",
".",
"getRemoteStore",
"(",
")",
"\n",
"pubKey",
",",
"err",
"=",
"rotateRemoteKey",
"(",
"role",
",",
"remote",
")",
"\n",
"pubKeyList",
"=",
"make",
"(",
"data",
".",
"KeyList",
",",
"0",
",",
"1",
")",
"\n",
"pubKeyList",
"=",
"append",
"(",
"pubKeyList",
",",
"pubKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"pubKeyList",
",",
"nil",
"\n",
"}",
"\n\n",
"// If no new keys are passed in, we generate one",
"if",
"len",
"(",
"newKeys",
")",
"==",
"0",
"{",
"pubKeyList",
"=",
"make",
"(",
"data",
".",
"KeyList",
",",
"0",
",",
"1",
")",
"\n",
"pubKey",
",",
"err",
"=",
"r",
".",
"GetCryptoService",
"(",
")",
".",
"Create",
"(",
"role",
",",
"r",
".",
"gun",
",",
"data",
".",
"ECDSAKey",
")",
"\n",
"pubKeyList",
"=",
"append",
"(",
"pubKeyList",
",",
"pubKey",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// If a list of keys to rotate to are provided, we add those",
"if",
"len",
"(",
"newKeys",
")",
">",
"0",
"{",
"pubKeyList",
"=",
"make",
"(",
"data",
".",
"KeyList",
",",
"0",
",",
"len",
"(",
"newKeys",
")",
")",
"\n",
"for",
"_",
",",
"keyID",
":=",
"range",
"newKeys",
"{",
"pubKey",
"=",
"r",
".",
"GetCryptoService",
"(",
")",
".",
"GetKey",
"(",
"keyID",
")",
"\n",
"if",
"pubKey",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyID",
")",
"\n",
"}",
"\n",
"pubKeyList",
"=",
"append",
"(",
"pubKeyList",
",",
"pubKey",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Convert to certs (for root keys)",
"if",
"pubKeyList",
",",
"err",
"=",
"r",
".",
"pubKeysToCerts",
"(",
"role",
",",
"pubKeyList",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"pubKeyList",
",",
"nil",
"\n",
"}"
] |
// Given a set of new keys to rotate to and a set of keys to drop, returns the list of current keys to use
|
[
"Given",
"a",
"set",
"of",
"new",
"keys",
"to",
"rotate",
"to",
"and",
"a",
"set",
"of",
"keys",
"to",
"drop",
"returns",
"the",
"list",
"of",
"current",
"keys",
"to",
"use"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L866-L909
|
train
|
theupdateframework/notary
|
client/client.go
|
DeleteTrustData
|
func DeleteTrustData(baseDir string, gun data.GUN, URL string, rt http.RoundTripper, deleteRemote bool) error {
localRepo := filepath.Join(baseDir, tufDir, filepath.FromSlash(gun.String()))
// Remove the tufRepoPath directory, which includes local TUF metadata files and changelist information
if err := os.RemoveAll(localRepo); err != nil {
return fmt.Errorf("error clearing TUF repo data: %v", err)
}
// Note that this will require admin permission for the gun in the roundtripper
if deleteRemote {
remote, err := getRemoteStore(URL, gun, rt)
if err != nil {
logrus.Errorf("unable to instantiate a remote store: %v", err)
return err
}
if err := remote.RemoveAll(); err != nil {
return err
}
}
return nil
}
|
go
|
func DeleteTrustData(baseDir string, gun data.GUN, URL string, rt http.RoundTripper, deleteRemote bool) error {
localRepo := filepath.Join(baseDir, tufDir, filepath.FromSlash(gun.String()))
// Remove the tufRepoPath directory, which includes local TUF metadata files and changelist information
if err := os.RemoveAll(localRepo); err != nil {
return fmt.Errorf("error clearing TUF repo data: %v", err)
}
// Note that this will require admin permission for the gun in the roundtripper
if deleteRemote {
remote, err := getRemoteStore(URL, gun, rt)
if err != nil {
logrus.Errorf("unable to instantiate a remote store: %v", err)
return err
}
if err := remote.RemoveAll(); err != nil {
return err
}
}
return nil
}
|
[
"func",
"DeleteTrustData",
"(",
"baseDir",
"string",
",",
"gun",
"data",
".",
"GUN",
",",
"URL",
"string",
",",
"rt",
"http",
".",
"RoundTripper",
",",
"deleteRemote",
"bool",
")",
"error",
"{",
"localRepo",
":=",
"filepath",
".",
"Join",
"(",
"baseDir",
",",
"tufDir",
",",
"filepath",
".",
"FromSlash",
"(",
"gun",
".",
"String",
"(",
")",
")",
")",
"\n",
"// Remove the tufRepoPath directory, which includes local TUF metadata files and changelist information",
"if",
"err",
":=",
"os",
".",
"RemoveAll",
"(",
"localRepo",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// Note that this will require admin permission for the gun in the roundtripper",
"if",
"deleteRemote",
"{",
"remote",
",",
"err",
":=",
"getRemoteStore",
"(",
"URL",
",",
"gun",
",",
"rt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"remote",
".",
"RemoveAll",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteTrustData removes the trust data stored for this repo in the TUF cache on the client side
// Note that we will not delete any private key material from local storage
|
[
"DeleteTrustData",
"removes",
"the",
"trust",
"data",
"stored",
"for",
"this",
"repo",
"in",
"the",
"TUF",
"cache",
"on",
"the",
"client",
"side",
"Note",
"that",
"we",
"will",
"not",
"delete",
"any",
"private",
"key",
"material",
"from",
"local",
"storage"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/client.go#L974-L992
|
train
|
theupdateframework/notary
|
tuf/tuf.go
|
NewRepo
|
func NewRepo(cryptoService signed.CryptoService) *Repo {
return &Repo{
Targets: make(map[data.RoleName]*data.SignedTargets),
cryptoService: cryptoService,
}
}
|
go
|
func NewRepo(cryptoService signed.CryptoService) *Repo {
return &Repo{
Targets: make(map[data.RoleName]*data.SignedTargets),
cryptoService: cryptoService,
}
}
|
[
"func",
"NewRepo",
"(",
"cryptoService",
"signed",
".",
"CryptoService",
")",
"*",
"Repo",
"{",
"return",
"&",
"Repo",
"{",
"Targets",
":",
"make",
"(",
"map",
"[",
"data",
".",
"RoleName",
"]",
"*",
"data",
".",
"SignedTargets",
")",
",",
"cryptoService",
":",
"cryptoService",
",",
"}",
"\n",
"}"
] |
// NewRepo initializes a Repo instance with a CryptoService.
// If the Repo will only be used for reading, the CryptoService
// can be nil.
|
[
"NewRepo",
"initializes",
"a",
"Repo",
"instance",
"with",
"a",
"CryptoService",
".",
"If",
"the",
"Repo",
"will",
"only",
"be",
"used",
"for",
"reading",
"the",
"CryptoService",
"can",
"be",
"nil",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L76-L81
|
train
|
theupdateframework/notary
|
tuf/tuf.go
|
AddBaseKeys
|
func (tr *Repo) AddBaseKeys(role data.RoleName, keys ...data.PublicKey) error {
if tr.Root == nil {
return ErrNotLoaded{Role: data.CanonicalRootRole}
}
ids := []string{}
for _, k := range keys {
// Store only the public portion
tr.Root.Signed.Keys[k.ID()] = k
tr.Root.Signed.Roles[role].KeyIDs = append(tr.Root.Signed.Roles[role].KeyIDs, k.ID())
ids = append(ids, k.ID())
}
tr.Root.Dirty = true
// also, whichever role was switched out needs to be re-signed
// root has already been marked dirty.
switch role {
case data.CanonicalSnapshotRole:
if tr.Snapshot != nil {
tr.Snapshot.Dirty = true
}
case data.CanonicalTargetsRole:
if target, ok := tr.Targets[data.CanonicalTargetsRole]; ok {
target.Dirty = true
}
case data.CanonicalTimestampRole:
if tr.Timestamp != nil {
tr.Timestamp.Dirty = true
}
}
return nil
}
|
go
|
func (tr *Repo) AddBaseKeys(role data.RoleName, keys ...data.PublicKey) error {
if tr.Root == nil {
return ErrNotLoaded{Role: data.CanonicalRootRole}
}
ids := []string{}
for _, k := range keys {
// Store only the public portion
tr.Root.Signed.Keys[k.ID()] = k
tr.Root.Signed.Roles[role].KeyIDs = append(tr.Root.Signed.Roles[role].KeyIDs, k.ID())
ids = append(ids, k.ID())
}
tr.Root.Dirty = true
// also, whichever role was switched out needs to be re-signed
// root has already been marked dirty.
switch role {
case data.CanonicalSnapshotRole:
if tr.Snapshot != nil {
tr.Snapshot.Dirty = true
}
case data.CanonicalTargetsRole:
if target, ok := tr.Targets[data.CanonicalTargetsRole]; ok {
target.Dirty = true
}
case data.CanonicalTimestampRole:
if tr.Timestamp != nil {
tr.Timestamp.Dirty = true
}
}
return nil
}
|
[
"func",
"(",
"tr",
"*",
"Repo",
")",
"AddBaseKeys",
"(",
"role",
"data",
".",
"RoleName",
",",
"keys",
"...",
"data",
".",
"PublicKey",
")",
"error",
"{",
"if",
"tr",
".",
"Root",
"==",
"nil",
"{",
"return",
"ErrNotLoaded",
"{",
"Role",
":",
"data",
".",
"CanonicalRootRole",
"}",
"\n",
"}",
"\n",
"ids",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"keys",
"{",
"// Store only the public portion",
"tr",
".",
"Root",
".",
"Signed",
".",
"Keys",
"[",
"k",
".",
"ID",
"(",
")",
"]",
"=",
"k",
"\n",
"tr",
".",
"Root",
".",
"Signed",
".",
"Roles",
"[",
"role",
"]",
".",
"KeyIDs",
"=",
"append",
"(",
"tr",
".",
"Root",
".",
"Signed",
".",
"Roles",
"[",
"role",
"]",
".",
"KeyIDs",
",",
"k",
".",
"ID",
"(",
")",
")",
"\n",
"ids",
"=",
"append",
"(",
"ids",
",",
"k",
".",
"ID",
"(",
")",
")",
"\n",
"}",
"\n",
"tr",
".",
"Root",
".",
"Dirty",
"=",
"true",
"\n\n",
"// also, whichever role was switched out needs to be re-signed",
"// root has already been marked dirty.",
"switch",
"role",
"{",
"case",
"data",
".",
"CanonicalSnapshotRole",
":",
"if",
"tr",
".",
"Snapshot",
"!=",
"nil",
"{",
"tr",
".",
"Snapshot",
".",
"Dirty",
"=",
"true",
"\n",
"}",
"\n",
"case",
"data",
".",
"CanonicalTargetsRole",
":",
"if",
"target",
",",
"ok",
":=",
"tr",
".",
"Targets",
"[",
"data",
".",
"CanonicalTargetsRole",
"]",
";",
"ok",
"{",
"target",
".",
"Dirty",
"=",
"true",
"\n",
"}",
"\n",
"case",
"data",
".",
"CanonicalTimestampRole",
":",
"if",
"tr",
".",
"Timestamp",
"!=",
"nil",
"{",
"tr",
".",
"Timestamp",
".",
"Dirty",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// AddBaseKeys is used to add keys to the role in root.json
|
[
"AddBaseKeys",
"is",
"used",
"to",
"add",
"keys",
"to",
"the",
"role",
"in",
"root",
".",
"json"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L84-L114
|
train
|
theupdateframework/notary
|
tuf/tuf.go
|
ReplaceBaseKeys
|
func (tr *Repo) ReplaceBaseKeys(role data.RoleName, keys ...data.PublicKey) error {
r, err := tr.GetBaseRole(role)
if err != nil {
return err
}
err = tr.RemoveBaseKeys(role, r.ListKeyIDs()...)
if err != nil {
return err
}
return tr.AddBaseKeys(role, keys...)
}
|
go
|
func (tr *Repo) ReplaceBaseKeys(role data.RoleName, keys ...data.PublicKey) error {
r, err := tr.GetBaseRole(role)
if err != nil {
return err
}
err = tr.RemoveBaseKeys(role, r.ListKeyIDs()...)
if err != nil {
return err
}
return tr.AddBaseKeys(role, keys...)
}
|
[
"func",
"(",
"tr",
"*",
"Repo",
")",
"ReplaceBaseKeys",
"(",
"role",
"data",
".",
"RoleName",
",",
"keys",
"...",
"data",
".",
"PublicKey",
")",
"error",
"{",
"r",
",",
"err",
":=",
"tr",
".",
"GetBaseRole",
"(",
"role",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"tr",
".",
"RemoveBaseKeys",
"(",
"role",
",",
"r",
".",
"ListKeyIDs",
"(",
")",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"tr",
".",
"AddBaseKeys",
"(",
"role",
",",
"keys",
"...",
")",
"\n",
"}"
] |
// ReplaceBaseKeys is used to replace all keys for the given role with the new keys
|
[
"ReplaceBaseKeys",
"is",
"used",
"to",
"replace",
"all",
"keys",
"for",
"the",
"given",
"role",
"with",
"the",
"new",
"keys"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L117-L127
|
train
|
theupdateframework/notary
|
tuf/tuf.go
|
RemoveBaseKeys
|
func (tr *Repo) RemoveBaseKeys(role data.RoleName, keyIDs ...string) error {
if tr.Root == nil {
return ErrNotLoaded{Role: data.CanonicalRootRole}
}
var keep []string
toDelete := make(map[string]struct{})
emptyStruct := struct{}{}
// remove keys from specified role
for _, k := range keyIDs {
toDelete[k] = emptyStruct
}
oldKeyIDs := tr.Root.Signed.Roles[role].KeyIDs
for _, rk := range oldKeyIDs {
if _, ok := toDelete[rk]; !ok {
keep = append(keep, rk)
}
}
tr.Root.Signed.Roles[role].KeyIDs = keep
// also, whichever role had keys removed needs to be re-signed
// root has already been marked dirty.
tr.markRoleDirty(role)
// determine which keys are no longer in use by any roles
for roleName, r := range tr.Root.Signed.Roles {
if roleName == role {
continue
}
for _, rk := range r.KeyIDs {
if _, ok := toDelete[rk]; ok {
delete(toDelete, rk)
}
}
}
// Remove keys no longer in use by any roles, except for root keys.
// Root private keys must be kept in tr.cryptoService to be able to sign
// for rotation, and root certificates must be kept in tr.Root.SignedKeys
// because we are not necessarily storing them elsewhere (tuf.Repo does not
// depend on certs.Manager, that is an upper layer), and without storing
// the certificates in their x509 form we are not able to do the
// util.CanonicalKeyID conversion.
if role != data.CanonicalRootRole {
for k := range toDelete {
delete(tr.Root.Signed.Keys, k)
tr.cryptoService.RemoveKey(k)
}
}
tr.Root.Dirty = true
return nil
}
|
go
|
func (tr *Repo) RemoveBaseKeys(role data.RoleName, keyIDs ...string) error {
if tr.Root == nil {
return ErrNotLoaded{Role: data.CanonicalRootRole}
}
var keep []string
toDelete := make(map[string]struct{})
emptyStruct := struct{}{}
// remove keys from specified role
for _, k := range keyIDs {
toDelete[k] = emptyStruct
}
oldKeyIDs := tr.Root.Signed.Roles[role].KeyIDs
for _, rk := range oldKeyIDs {
if _, ok := toDelete[rk]; !ok {
keep = append(keep, rk)
}
}
tr.Root.Signed.Roles[role].KeyIDs = keep
// also, whichever role had keys removed needs to be re-signed
// root has already been marked dirty.
tr.markRoleDirty(role)
// determine which keys are no longer in use by any roles
for roleName, r := range tr.Root.Signed.Roles {
if roleName == role {
continue
}
for _, rk := range r.KeyIDs {
if _, ok := toDelete[rk]; ok {
delete(toDelete, rk)
}
}
}
// Remove keys no longer in use by any roles, except for root keys.
// Root private keys must be kept in tr.cryptoService to be able to sign
// for rotation, and root certificates must be kept in tr.Root.SignedKeys
// because we are not necessarily storing them elsewhere (tuf.Repo does not
// depend on certs.Manager, that is an upper layer), and without storing
// the certificates in their x509 form we are not able to do the
// util.CanonicalKeyID conversion.
if role != data.CanonicalRootRole {
for k := range toDelete {
delete(tr.Root.Signed.Keys, k)
tr.cryptoService.RemoveKey(k)
}
}
tr.Root.Dirty = true
return nil
}
|
[
"func",
"(",
"tr",
"*",
"Repo",
")",
"RemoveBaseKeys",
"(",
"role",
"data",
".",
"RoleName",
",",
"keyIDs",
"...",
"string",
")",
"error",
"{",
"if",
"tr",
".",
"Root",
"==",
"nil",
"{",
"return",
"ErrNotLoaded",
"{",
"Role",
":",
"data",
".",
"CanonicalRootRole",
"}",
"\n",
"}",
"\n",
"var",
"keep",
"[",
"]",
"string",
"\n",
"toDelete",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"emptyStruct",
":=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"// remove keys from specified role",
"for",
"_",
",",
"k",
":=",
"range",
"keyIDs",
"{",
"toDelete",
"[",
"k",
"]",
"=",
"emptyStruct",
"\n",
"}",
"\n\n",
"oldKeyIDs",
":=",
"tr",
".",
"Root",
".",
"Signed",
".",
"Roles",
"[",
"role",
"]",
".",
"KeyIDs",
"\n",
"for",
"_",
",",
"rk",
":=",
"range",
"oldKeyIDs",
"{",
"if",
"_",
",",
"ok",
":=",
"toDelete",
"[",
"rk",
"]",
";",
"!",
"ok",
"{",
"keep",
"=",
"append",
"(",
"keep",
",",
"rk",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"tr",
".",
"Root",
".",
"Signed",
".",
"Roles",
"[",
"role",
"]",
".",
"KeyIDs",
"=",
"keep",
"\n\n",
"// also, whichever role had keys removed needs to be re-signed",
"// root has already been marked dirty.",
"tr",
".",
"markRoleDirty",
"(",
"role",
")",
"\n\n",
"// determine which keys are no longer in use by any roles",
"for",
"roleName",
",",
"r",
":=",
"range",
"tr",
".",
"Root",
".",
"Signed",
".",
"Roles",
"{",
"if",
"roleName",
"==",
"role",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"rk",
":=",
"range",
"r",
".",
"KeyIDs",
"{",
"if",
"_",
",",
"ok",
":=",
"toDelete",
"[",
"rk",
"]",
";",
"ok",
"{",
"delete",
"(",
"toDelete",
",",
"rk",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Remove keys no longer in use by any roles, except for root keys.",
"// Root private keys must be kept in tr.cryptoService to be able to sign",
"// for rotation, and root certificates must be kept in tr.Root.SignedKeys",
"// because we are not necessarily storing them elsewhere (tuf.Repo does not",
"// depend on certs.Manager, that is an upper layer), and without storing",
"// the certificates in their x509 form we are not able to do the",
"// util.CanonicalKeyID conversion.",
"if",
"role",
"!=",
"data",
".",
"CanonicalRootRole",
"{",
"for",
"k",
":=",
"range",
"toDelete",
"{",
"delete",
"(",
"tr",
".",
"Root",
".",
"Signed",
".",
"Keys",
",",
"k",
")",
"\n",
"tr",
".",
"cryptoService",
".",
"RemoveKey",
"(",
"k",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"tr",
".",
"Root",
".",
"Dirty",
"=",
"true",
"\n",
"return",
"nil",
"\n",
"}"
] |
// RemoveBaseKeys is used to remove keys from the roles in root.json
|
[
"RemoveBaseKeys",
"is",
"used",
"to",
"remove",
"keys",
"from",
"the",
"roles",
"in",
"root",
".",
"json"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L130-L183
|
train
|
theupdateframework/notary
|
tuf/tuf.go
|
GetBaseRole
|
func (tr *Repo) GetBaseRole(name data.RoleName) (data.BaseRole, error) {
if !data.ValidRole(name) {
return data.BaseRole{}, data.ErrInvalidRole{Role: name, Reason: "invalid base role name"}
}
if tr.Root == nil {
return data.BaseRole{}, ErrNotLoaded{data.CanonicalRootRole}
}
// Find the role data public keys for the base role from TUF metadata
baseRole, err := tr.Root.BuildBaseRole(name)
if err != nil {
return data.BaseRole{}, err
}
return baseRole, nil
}
|
go
|
func (tr *Repo) GetBaseRole(name data.RoleName) (data.BaseRole, error) {
if !data.ValidRole(name) {
return data.BaseRole{}, data.ErrInvalidRole{Role: name, Reason: "invalid base role name"}
}
if tr.Root == nil {
return data.BaseRole{}, ErrNotLoaded{data.CanonicalRootRole}
}
// Find the role data public keys for the base role from TUF metadata
baseRole, err := tr.Root.BuildBaseRole(name)
if err != nil {
return data.BaseRole{}, err
}
return baseRole, nil
}
|
[
"func",
"(",
"tr",
"*",
"Repo",
")",
"GetBaseRole",
"(",
"name",
"data",
".",
"RoleName",
")",
"(",
"data",
".",
"BaseRole",
",",
"error",
")",
"{",
"if",
"!",
"data",
".",
"ValidRole",
"(",
"name",
")",
"{",
"return",
"data",
".",
"BaseRole",
"{",
"}",
",",
"data",
".",
"ErrInvalidRole",
"{",
"Role",
":",
"name",
",",
"Reason",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"if",
"tr",
".",
"Root",
"==",
"nil",
"{",
"return",
"data",
".",
"BaseRole",
"{",
"}",
",",
"ErrNotLoaded",
"{",
"data",
".",
"CanonicalRootRole",
"}",
"\n",
"}",
"\n",
"// Find the role data public keys for the base role from TUF metadata",
"baseRole",
",",
"err",
":=",
"tr",
".",
"Root",
".",
"BuildBaseRole",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"data",
".",
"BaseRole",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"baseRole",
",",
"nil",
"\n",
"}"
] |
// GetBaseRole gets a base role from this repo's metadata
|
[
"GetBaseRole",
"gets",
"a",
"base",
"role",
"from",
"this",
"repo",
"s",
"metadata"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L203-L217
|
train
|
theupdateframework/notary
|
tuf/tuf.go
|
GetDelegationRole
|
func (tr *Repo) GetDelegationRole(name data.RoleName) (data.DelegationRole, error) {
if !data.IsDelegation(name) {
return data.DelegationRole{}, data.ErrInvalidRole{Role: name, Reason: "invalid delegation name"}
}
if tr.Root == nil {
return data.DelegationRole{}, ErrNotLoaded{data.CanonicalRootRole}
}
_, ok := tr.Root.Signed.Roles[data.CanonicalTargetsRole]
if !ok {
return data.DelegationRole{}, ErrNotLoaded{data.CanonicalTargetsRole}
}
// Traverse target metadata, down to delegation itself
// Get all public keys for the base role from TUF metadata
_, ok = tr.Targets[data.CanonicalTargetsRole]
if !ok {
return data.DelegationRole{}, ErrNotLoaded{data.CanonicalTargetsRole}
}
// Start with top level roles in targets. Walk the chain of ancestors
// until finding the desired role, or we run out of targets files to search.
var foundRole *data.DelegationRole
buildDelegationRoleVisitor := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
// Try to find the delegation and build a DelegationRole structure
for _, role := range tgt.Signed.Delegations.Roles {
if role.Name == name {
delgRole, err := tgt.BuildDelegationRole(name)
if err != nil {
return err
}
// Check all public key certificates in the role for expiry
// Currently we do not reject expired delegation keys but warn if they might expire soon or have already
for _, pubKey := range delgRole.Keys {
certFromKey, err := utils.LoadCertFromPEM(pubKey.Public())
if err != nil {
continue
}
//Don't check the delegation certificate expiry once added, use the TUF role expiry instead
if err := utils.ValidateCertificate(certFromKey, false); err != nil {
return err
}
}
foundRole = &delgRole
return StopWalk{}
}
}
return nil
}
// Walk to the parent of this delegation, since that is where its role metadata exists
err := tr.WalkTargets("", name.Parent(), buildDelegationRoleVisitor)
if err != nil {
return data.DelegationRole{}, err
}
// We never found the delegation. In the context of this repo it is considered
// invalid. N.B. it may be that it existed at one point but an ancestor has since
// been modified/removed.
if foundRole == nil {
return data.DelegationRole{}, data.ErrInvalidRole{Role: name, Reason: "delegation does not exist"}
}
return *foundRole, nil
}
|
go
|
func (tr *Repo) GetDelegationRole(name data.RoleName) (data.DelegationRole, error) {
if !data.IsDelegation(name) {
return data.DelegationRole{}, data.ErrInvalidRole{Role: name, Reason: "invalid delegation name"}
}
if tr.Root == nil {
return data.DelegationRole{}, ErrNotLoaded{data.CanonicalRootRole}
}
_, ok := tr.Root.Signed.Roles[data.CanonicalTargetsRole]
if !ok {
return data.DelegationRole{}, ErrNotLoaded{data.CanonicalTargetsRole}
}
// Traverse target metadata, down to delegation itself
// Get all public keys for the base role from TUF metadata
_, ok = tr.Targets[data.CanonicalTargetsRole]
if !ok {
return data.DelegationRole{}, ErrNotLoaded{data.CanonicalTargetsRole}
}
// Start with top level roles in targets. Walk the chain of ancestors
// until finding the desired role, or we run out of targets files to search.
var foundRole *data.DelegationRole
buildDelegationRoleVisitor := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
// Try to find the delegation and build a DelegationRole structure
for _, role := range tgt.Signed.Delegations.Roles {
if role.Name == name {
delgRole, err := tgt.BuildDelegationRole(name)
if err != nil {
return err
}
// Check all public key certificates in the role for expiry
// Currently we do not reject expired delegation keys but warn if they might expire soon or have already
for _, pubKey := range delgRole.Keys {
certFromKey, err := utils.LoadCertFromPEM(pubKey.Public())
if err != nil {
continue
}
//Don't check the delegation certificate expiry once added, use the TUF role expiry instead
if err := utils.ValidateCertificate(certFromKey, false); err != nil {
return err
}
}
foundRole = &delgRole
return StopWalk{}
}
}
return nil
}
// Walk to the parent of this delegation, since that is where its role metadata exists
err := tr.WalkTargets("", name.Parent(), buildDelegationRoleVisitor)
if err != nil {
return data.DelegationRole{}, err
}
// We never found the delegation. In the context of this repo it is considered
// invalid. N.B. it may be that it existed at one point but an ancestor has since
// been modified/removed.
if foundRole == nil {
return data.DelegationRole{}, data.ErrInvalidRole{Role: name, Reason: "delegation does not exist"}
}
return *foundRole, nil
}
|
[
"func",
"(",
"tr",
"*",
"Repo",
")",
"GetDelegationRole",
"(",
"name",
"data",
".",
"RoleName",
")",
"(",
"data",
".",
"DelegationRole",
",",
"error",
")",
"{",
"if",
"!",
"data",
".",
"IsDelegation",
"(",
"name",
")",
"{",
"return",
"data",
".",
"DelegationRole",
"{",
"}",
",",
"data",
".",
"ErrInvalidRole",
"{",
"Role",
":",
"name",
",",
"Reason",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"if",
"tr",
".",
"Root",
"==",
"nil",
"{",
"return",
"data",
".",
"DelegationRole",
"{",
"}",
",",
"ErrNotLoaded",
"{",
"data",
".",
"CanonicalRootRole",
"}",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"tr",
".",
"Root",
".",
"Signed",
".",
"Roles",
"[",
"data",
".",
"CanonicalTargetsRole",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"data",
".",
"DelegationRole",
"{",
"}",
",",
"ErrNotLoaded",
"{",
"data",
".",
"CanonicalTargetsRole",
"}",
"\n",
"}",
"\n",
"// Traverse target metadata, down to delegation itself",
"// Get all public keys for the base role from TUF metadata",
"_",
",",
"ok",
"=",
"tr",
".",
"Targets",
"[",
"data",
".",
"CanonicalTargetsRole",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"data",
".",
"DelegationRole",
"{",
"}",
",",
"ErrNotLoaded",
"{",
"data",
".",
"CanonicalTargetsRole",
"}",
"\n",
"}",
"\n\n",
"// Start with top level roles in targets. Walk the chain of ancestors",
"// until finding the desired role, or we run out of targets files to search.",
"var",
"foundRole",
"*",
"data",
".",
"DelegationRole",
"\n",
"buildDelegationRoleVisitor",
":=",
"func",
"(",
"tgt",
"*",
"data",
".",
"SignedTargets",
",",
"validRole",
"data",
".",
"DelegationRole",
")",
"interface",
"{",
"}",
"{",
"// Try to find the delegation and build a DelegationRole structure",
"for",
"_",
",",
"role",
":=",
"range",
"tgt",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
"{",
"if",
"role",
".",
"Name",
"==",
"name",
"{",
"delgRole",
",",
"err",
":=",
"tgt",
".",
"BuildDelegationRole",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Check all public key certificates in the role for expiry",
"// Currently we do not reject expired delegation keys but warn if they might expire soon or have already",
"for",
"_",
",",
"pubKey",
":=",
"range",
"delgRole",
".",
"Keys",
"{",
"certFromKey",
",",
"err",
":=",
"utils",
".",
"LoadCertFromPEM",
"(",
"pubKey",
".",
"Public",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"//Don't check the delegation certificate expiry once added, use the TUF role expiry instead",
"if",
"err",
":=",
"utils",
".",
"ValidateCertificate",
"(",
"certFromKey",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"foundRole",
"=",
"&",
"delgRole",
"\n",
"return",
"StopWalk",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Walk to the parent of this delegation, since that is where its role metadata exists",
"err",
":=",
"tr",
".",
"WalkTargets",
"(",
"\"",
"\"",
",",
"name",
".",
"Parent",
"(",
")",
",",
"buildDelegationRoleVisitor",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"data",
".",
"DelegationRole",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"// We never found the delegation. In the context of this repo it is considered",
"// invalid. N.B. it may be that it existed at one point but an ancestor has since",
"// been modified/removed.",
"if",
"foundRole",
"==",
"nil",
"{",
"return",
"data",
".",
"DelegationRole",
"{",
"}",
",",
"data",
".",
"ErrInvalidRole",
"{",
"Role",
":",
"name",
",",
"Reason",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n\n",
"return",
"*",
"foundRole",
",",
"nil",
"\n",
"}"
] |
// GetDelegationRole gets a delegation role from this repo's metadata, walking from the targets role down to the delegation itself
|
[
"GetDelegationRole",
"gets",
"a",
"delegation",
"role",
"from",
"this",
"repo",
"s",
"metadata",
"walking",
"from",
"the",
"targets",
"role",
"down",
"to",
"the",
"delegation",
"itself"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L220-L282
|
train
|
theupdateframework/notary
|
tuf/tuf.go
|
GetAllLoadedRoles
|
func (tr *Repo) GetAllLoadedRoles() []*data.Role {
var res []*data.Role
if tr.Root == nil {
// if root isn't loaded, we should consider we have no loaded roles because we can't
// trust any other state that might be present
return res
}
for name, rr := range tr.Root.Signed.Roles {
res = append(res, &data.Role{
RootRole: *rr,
Name: name,
})
}
for _, delegate := range tr.Targets {
for _, r := range delegate.Signed.Delegations.Roles {
res = append(res, r)
}
}
return res
}
|
go
|
func (tr *Repo) GetAllLoadedRoles() []*data.Role {
var res []*data.Role
if tr.Root == nil {
// if root isn't loaded, we should consider we have no loaded roles because we can't
// trust any other state that might be present
return res
}
for name, rr := range tr.Root.Signed.Roles {
res = append(res, &data.Role{
RootRole: *rr,
Name: name,
})
}
for _, delegate := range tr.Targets {
for _, r := range delegate.Signed.Delegations.Roles {
res = append(res, r)
}
}
return res
}
|
[
"func",
"(",
"tr",
"*",
"Repo",
")",
"GetAllLoadedRoles",
"(",
")",
"[",
"]",
"*",
"data",
".",
"Role",
"{",
"var",
"res",
"[",
"]",
"*",
"data",
".",
"Role",
"\n",
"if",
"tr",
".",
"Root",
"==",
"nil",
"{",
"// if root isn't loaded, we should consider we have no loaded roles because we can't",
"// trust any other state that might be present",
"return",
"res",
"\n",
"}",
"\n",
"for",
"name",
",",
"rr",
":=",
"range",
"tr",
".",
"Root",
".",
"Signed",
".",
"Roles",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"&",
"data",
".",
"Role",
"{",
"RootRole",
":",
"*",
"rr",
",",
"Name",
":",
"name",
",",
"}",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"delegate",
":=",
"range",
"tr",
".",
"Targets",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"delegate",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
"{",
"res",
"=",
"append",
"(",
"res",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] |
// GetAllLoadedRoles returns a list of all role entries loaded in this TUF repo, could be empty
|
[
"GetAllLoadedRoles",
"returns",
"a",
"list",
"of",
"all",
"role",
"entries",
"loaded",
"in",
"this",
"TUF",
"repo",
"could",
"be",
"empty"
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L285-L304
|
train
|
theupdateframework/notary
|
tuf/tuf.go
|
delegationUpdateVisitor
|
func delegationUpdateVisitor(roleName data.RoleName, addKeys data.KeyList, removeKeys, addPaths, removePaths []string, clearAllPaths bool, newThreshold int) walkVisitorFunc {
return func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
var err error
// Validate the changes underneath this restricted validRole for adding paths, reject invalid path additions
if len(addPaths) != len(data.RestrictDelegationPathPrefixes(validRole.Paths, addPaths)) {
return data.ErrInvalidRole{Role: roleName, Reason: "invalid paths to add to role"}
}
// Try to find the delegation and amend it using our changelist
var delgRole *data.Role
for _, role := range tgt.Signed.Delegations.Roles {
if role.Name == roleName {
// Make a copy and operate on this role until we validate the changes
keyIDCopy := make([]string, len(role.KeyIDs))
copy(keyIDCopy, role.KeyIDs)
pathsCopy := make([]string, len(role.Paths))
copy(pathsCopy, role.Paths)
delgRole = &data.Role{
RootRole: data.RootRole{
KeyIDs: keyIDCopy,
Threshold: role.Threshold,
},
Name: role.Name,
Paths: pathsCopy,
}
delgRole.RemovePaths(removePaths)
if clearAllPaths {
delgRole.Paths = []string{}
}
delgRole.AddPaths(addPaths)
delgRole.RemoveKeys(removeKeys)
break
}
}
// We didn't find the role earlier, so create it.
if addKeys == nil {
addKeys = data.KeyList{} // initialize to empty list if necessary so calling .IDs() below won't panic
}
if delgRole == nil {
delgRole, err = data.NewRole(roleName, newThreshold, addKeys.IDs(), addPaths)
if err != nil {
return err
}
}
// Add the key IDs to the role and the keys themselves to the parent
for _, k := range addKeys {
if !utils.StrSliceContains(delgRole.KeyIDs, k.ID()) {
delgRole.KeyIDs = append(delgRole.KeyIDs, k.ID())
}
}
// Make sure we have a valid role still
if len(delgRole.KeyIDs) < delgRole.Threshold {
logrus.Warnf("role %s has fewer keys than its threshold of %d; it will not be usable until keys are added to it", delgRole.Name, delgRole.Threshold)
}
// NOTE: this closure CANNOT error after this point, as we've committed to editing the SignedTargets metadata in the repo object.
// Any errors related to updating this delegation must occur before this point.
// If all of our changes were valid, we should edit the actual SignedTargets to match our copy
for _, k := range addKeys {
tgt.Signed.Delegations.Keys[k.ID()] = k
}
foundAt := utils.FindRoleIndex(tgt.Signed.Delegations.Roles, delgRole.Name)
if foundAt < 0 {
tgt.Signed.Delegations.Roles = append(tgt.Signed.Delegations.Roles, delgRole)
} else {
tgt.Signed.Delegations.Roles[foundAt] = delgRole
}
tgt.Dirty = true
utils.RemoveUnusedKeys(tgt)
return StopWalk{}
}
}
|
go
|
func delegationUpdateVisitor(roleName data.RoleName, addKeys data.KeyList, removeKeys, addPaths, removePaths []string, clearAllPaths bool, newThreshold int) walkVisitorFunc {
return func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
var err error
// Validate the changes underneath this restricted validRole for adding paths, reject invalid path additions
if len(addPaths) != len(data.RestrictDelegationPathPrefixes(validRole.Paths, addPaths)) {
return data.ErrInvalidRole{Role: roleName, Reason: "invalid paths to add to role"}
}
// Try to find the delegation and amend it using our changelist
var delgRole *data.Role
for _, role := range tgt.Signed.Delegations.Roles {
if role.Name == roleName {
// Make a copy and operate on this role until we validate the changes
keyIDCopy := make([]string, len(role.KeyIDs))
copy(keyIDCopy, role.KeyIDs)
pathsCopy := make([]string, len(role.Paths))
copy(pathsCopy, role.Paths)
delgRole = &data.Role{
RootRole: data.RootRole{
KeyIDs: keyIDCopy,
Threshold: role.Threshold,
},
Name: role.Name,
Paths: pathsCopy,
}
delgRole.RemovePaths(removePaths)
if clearAllPaths {
delgRole.Paths = []string{}
}
delgRole.AddPaths(addPaths)
delgRole.RemoveKeys(removeKeys)
break
}
}
// We didn't find the role earlier, so create it.
if addKeys == nil {
addKeys = data.KeyList{} // initialize to empty list if necessary so calling .IDs() below won't panic
}
if delgRole == nil {
delgRole, err = data.NewRole(roleName, newThreshold, addKeys.IDs(), addPaths)
if err != nil {
return err
}
}
// Add the key IDs to the role and the keys themselves to the parent
for _, k := range addKeys {
if !utils.StrSliceContains(delgRole.KeyIDs, k.ID()) {
delgRole.KeyIDs = append(delgRole.KeyIDs, k.ID())
}
}
// Make sure we have a valid role still
if len(delgRole.KeyIDs) < delgRole.Threshold {
logrus.Warnf("role %s has fewer keys than its threshold of %d; it will not be usable until keys are added to it", delgRole.Name, delgRole.Threshold)
}
// NOTE: this closure CANNOT error after this point, as we've committed to editing the SignedTargets metadata in the repo object.
// Any errors related to updating this delegation must occur before this point.
// If all of our changes were valid, we should edit the actual SignedTargets to match our copy
for _, k := range addKeys {
tgt.Signed.Delegations.Keys[k.ID()] = k
}
foundAt := utils.FindRoleIndex(tgt.Signed.Delegations.Roles, delgRole.Name)
if foundAt < 0 {
tgt.Signed.Delegations.Roles = append(tgt.Signed.Delegations.Roles, delgRole)
} else {
tgt.Signed.Delegations.Roles[foundAt] = delgRole
}
tgt.Dirty = true
utils.RemoveUnusedKeys(tgt)
return StopWalk{}
}
}
|
[
"func",
"delegationUpdateVisitor",
"(",
"roleName",
"data",
".",
"RoleName",
",",
"addKeys",
"data",
".",
"KeyList",
",",
"removeKeys",
",",
"addPaths",
",",
"removePaths",
"[",
"]",
"string",
",",
"clearAllPaths",
"bool",
",",
"newThreshold",
"int",
")",
"walkVisitorFunc",
"{",
"return",
"func",
"(",
"tgt",
"*",
"data",
".",
"SignedTargets",
",",
"validRole",
"data",
".",
"DelegationRole",
")",
"interface",
"{",
"}",
"{",
"var",
"err",
"error",
"\n",
"// Validate the changes underneath this restricted validRole for adding paths, reject invalid path additions",
"if",
"len",
"(",
"addPaths",
")",
"!=",
"len",
"(",
"data",
".",
"RestrictDelegationPathPrefixes",
"(",
"validRole",
".",
"Paths",
",",
"addPaths",
")",
")",
"{",
"return",
"data",
".",
"ErrInvalidRole",
"{",
"Role",
":",
"roleName",
",",
"Reason",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"// Try to find the delegation and amend it using our changelist",
"var",
"delgRole",
"*",
"data",
".",
"Role",
"\n",
"for",
"_",
",",
"role",
":=",
"range",
"tgt",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
"{",
"if",
"role",
".",
"Name",
"==",
"roleName",
"{",
"// Make a copy and operate on this role until we validate the changes",
"keyIDCopy",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"role",
".",
"KeyIDs",
")",
")",
"\n",
"copy",
"(",
"keyIDCopy",
",",
"role",
".",
"KeyIDs",
")",
"\n",
"pathsCopy",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"role",
".",
"Paths",
")",
")",
"\n",
"copy",
"(",
"pathsCopy",
",",
"role",
".",
"Paths",
")",
"\n",
"delgRole",
"=",
"&",
"data",
".",
"Role",
"{",
"RootRole",
":",
"data",
".",
"RootRole",
"{",
"KeyIDs",
":",
"keyIDCopy",
",",
"Threshold",
":",
"role",
".",
"Threshold",
",",
"}",
",",
"Name",
":",
"role",
".",
"Name",
",",
"Paths",
":",
"pathsCopy",
",",
"}",
"\n",
"delgRole",
".",
"RemovePaths",
"(",
"removePaths",
")",
"\n",
"if",
"clearAllPaths",
"{",
"delgRole",
".",
"Paths",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"delgRole",
".",
"AddPaths",
"(",
"addPaths",
")",
"\n",
"delgRole",
".",
"RemoveKeys",
"(",
"removeKeys",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"// We didn't find the role earlier, so create it.",
"if",
"addKeys",
"==",
"nil",
"{",
"addKeys",
"=",
"data",
".",
"KeyList",
"{",
"}",
"// initialize to empty list if necessary so calling .IDs() below won't panic",
"\n",
"}",
"\n",
"if",
"delgRole",
"==",
"nil",
"{",
"delgRole",
",",
"err",
"=",
"data",
".",
"NewRole",
"(",
"roleName",
",",
"newThreshold",
",",
"addKeys",
".",
"IDs",
"(",
")",
",",
"addPaths",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"}",
"\n",
"// Add the key IDs to the role and the keys themselves to the parent",
"for",
"_",
",",
"k",
":=",
"range",
"addKeys",
"{",
"if",
"!",
"utils",
".",
"StrSliceContains",
"(",
"delgRole",
".",
"KeyIDs",
",",
"k",
".",
"ID",
"(",
")",
")",
"{",
"delgRole",
".",
"KeyIDs",
"=",
"append",
"(",
"delgRole",
".",
"KeyIDs",
",",
"k",
".",
"ID",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Make sure we have a valid role still",
"if",
"len",
"(",
"delgRole",
".",
"KeyIDs",
")",
"<",
"delgRole",
".",
"Threshold",
"{",
"logrus",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"delgRole",
".",
"Name",
",",
"delgRole",
".",
"Threshold",
")",
"\n",
"}",
"\n",
"// NOTE: this closure CANNOT error after this point, as we've committed to editing the SignedTargets metadata in the repo object.",
"// Any errors related to updating this delegation must occur before this point.",
"// If all of our changes were valid, we should edit the actual SignedTargets to match our copy",
"for",
"_",
",",
"k",
":=",
"range",
"addKeys",
"{",
"tgt",
".",
"Signed",
".",
"Delegations",
".",
"Keys",
"[",
"k",
".",
"ID",
"(",
")",
"]",
"=",
"k",
"\n",
"}",
"\n",
"foundAt",
":=",
"utils",
".",
"FindRoleIndex",
"(",
"tgt",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
",",
"delgRole",
".",
"Name",
")",
"\n",
"if",
"foundAt",
"<",
"0",
"{",
"tgt",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
"=",
"append",
"(",
"tgt",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
",",
"delgRole",
")",
"\n",
"}",
"else",
"{",
"tgt",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
"[",
"foundAt",
"]",
"=",
"delgRole",
"\n",
"}",
"\n",
"tgt",
".",
"Dirty",
"=",
"true",
"\n",
"utils",
".",
"RemoveUnusedKeys",
"(",
"tgt",
")",
"\n",
"return",
"StopWalk",
"{",
"}",
"\n",
"}",
"\n",
"}"
] |
// Walk to parent, and either create or update this delegation. We can only create a new delegation if we're given keys
// Ensure all updates are valid, by checking against parent ancestor paths and ensuring the keys meet the role threshold.
|
[
"Walk",
"to",
"parent",
"and",
"either",
"create",
"or",
"update",
"this",
"delegation",
".",
"We",
"can",
"only",
"create",
"a",
"new",
"delegation",
"if",
"we",
"re",
"given",
"keys",
"Ensure",
"all",
"updates",
"are",
"valid",
"by",
"checking",
"against",
"parent",
"ancestor",
"paths",
"and",
"ensuring",
"the",
"keys",
"meet",
"the",
"role",
"threshold",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L308-L378
|
train
|
theupdateframework/notary
|
tuf/tuf.go
|
UpdateDelegationPaths
|
func (tr *Repo) UpdateDelegationPaths(roleName data.RoleName, addPaths, removePaths []string, clearPaths bool) error {
if !data.IsDelegation(roleName) {
return data.ErrInvalidRole{Role: roleName, Reason: "not a valid delegated role"}
}
parent := roleName.Parent()
if err := tr.VerifyCanSign(parent); err != nil {
return err
}
// check the parent role's metadata
_, ok := tr.Targets[parent]
if !ok { // the parent targetfile may not exist yet
// if not, this is an error because a delegation must exist to edit only paths
return data.ErrInvalidRole{Role: roleName, Reason: "no valid delegated role exists"}
}
// Walk to the parent of this delegation, since that is where its role metadata exists
// We do not have to verify that the walker reached its desired role in this scenario
// since we've already done another walk to the parent role in VerifyCanSign
err := tr.WalkTargets("", parent, delegationUpdateVisitor(roleName, data.KeyList{}, []string{}, addPaths, removePaths, clearPaths, notary.MinThreshold))
if err != nil {
return err
}
return nil
}
|
go
|
func (tr *Repo) UpdateDelegationPaths(roleName data.RoleName, addPaths, removePaths []string, clearPaths bool) error {
if !data.IsDelegation(roleName) {
return data.ErrInvalidRole{Role: roleName, Reason: "not a valid delegated role"}
}
parent := roleName.Parent()
if err := tr.VerifyCanSign(parent); err != nil {
return err
}
// check the parent role's metadata
_, ok := tr.Targets[parent]
if !ok { // the parent targetfile may not exist yet
// if not, this is an error because a delegation must exist to edit only paths
return data.ErrInvalidRole{Role: roleName, Reason: "no valid delegated role exists"}
}
// Walk to the parent of this delegation, since that is where its role metadata exists
// We do not have to verify that the walker reached its desired role in this scenario
// since we've already done another walk to the parent role in VerifyCanSign
err := tr.WalkTargets("", parent, delegationUpdateVisitor(roleName, data.KeyList{}, []string{}, addPaths, removePaths, clearPaths, notary.MinThreshold))
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"tr",
"*",
"Repo",
")",
"UpdateDelegationPaths",
"(",
"roleName",
"data",
".",
"RoleName",
",",
"addPaths",
",",
"removePaths",
"[",
"]",
"string",
",",
"clearPaths",
"bool",
")",
"error",
"{",
"if",
"!",
"data",
".",
"IsDelegation",
"(",
"roleName",
")",
"{",
"return",
"data",
".",
"ErrInvalidRole",
"{",
"Role",
":",
"roleName",
",",
"Reason",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"parent",
":=",
"roleName",
".",
"Parent",
"(",
")",
"\n\n",
"if",
"err",
":=",
"tr",
".",
"VerifyCanSign",
"(",
"parent",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// check the parent role's metadata",
"_",
",",
"ok",
":=",
"tr",
".",
"Targets",
"[",
"parent",
"]",
"\n",
"if",
"!",
"ok",
"{",
"// the parent targetfile may not exist yet",
"// if not, this is an error because a delegation must exist to edit only paths",
"return",
"data",
".",
"ErrInvalidRole",
"{",
"Role",
":",
"roleName",
",",
"Reason",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n\n",
"// Walk to the parent of this delegation, since that is where its role metadata exists",
"// We do not have to verify that the walker reached its desired role in this scenario",
"// since we've already done another walk to the parent role in VerifyCanSign",
"err",
":=",
"tr",
".",
"WalkTargets",
"(",
"\"",
"\"",
",",
"parent",
",",
"delegationUpdateVisitor",
"(",
"roleName",
",",
"data",
".",
"KeyList",
"{",
"}",
",",
"[",
"]",
"string",
"{",
"}",
",",
"addPaths",
",",
"removePaths",
",",
"clearPaths",
",",
"notary",
".",
"MinThreshold",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UpdateDelegationPaths updates the appropriate delegation's paths.
// It is not allowed to create a new delegation.
|
[
"UpdateDelegationPaths",
"updates",
"the",
"appropriate",
"delegation",
"s",
"paths",
".",
"It",
"is",
"not",
"allowed",
"to",
"create",
"a",
"new",
"delegation",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L482-L507
|
train
|
theupdateframework/notary
|
tuf/tuf.go
|
DeleteDelegation
|
func (tr *Repo) DeleteDelegation(roleName data.RoleName) error {
if !data.IsDelegation(roleName) {
return data.ErrInvalidRole{Role: roleName, Reason: "not a valid delegated role"}
}
parent := roleName.Parent()
if err := tr.VerifyCanSign(parent); err != nil {
return err
}
// delete delegated data from Targets map and Snapshot - if they don't
// exist, these are no-op
delete(tr.Targets, roleName)
tr.Snapshot.DeleteMeta(roleName)
p, ok := tr.Targets[parent]
if !ok {
// if there is no parent metadata (the role exists though), then this
// is as good as done.
return nil
}
foundAt := utils.FindRoleIndex(p.Signed.Delegations.Roles, roleName)
if foundAt >= 0 {
var roles []*data.Role
// slice out deleted role
roles = append(roles, p.Signed.Delegations.Roles[:foundAt]...)
if foundAt+1 < len(p.Signed.Delegations.Roles) {
roles = append(roles, p.Signed.Delegations.Roles[foundAt+1:]...)
}
p.Signed.Delegations.Roles = roles
utils.RemoveUnusedKeys(p)
p.Dirty = true
} // if the role wasn't found, it's a good as deleted
return nil
}
|
go
|
func (tr *Repo) DeleteDelegation(roleName data.RoleName) error {
if !data.IsDelegation(roleName) {
return data.ErrInvalidRole{Role: roleName, Reason: "not a valid delegated role"}
}
parent := roleName.Parent()
if err := tr.VerifyCanSign(parent); err != nil {
return err
}
// delete delegated data from Targets map and Snapshot - if they don't
// exist, these are no-op
delete(tr.Targets, roleName)
tr.Snapshot.DeleteMeta(roleName)
p, ok := tr.Targets[parent]
if !ok {
// if there is no parent metadata (the role exists though), then this
// is as good as done.
return nil
}
foundAt := utils.FindRoleIndex(p.Signed.Delegations.Roles, roleName)
if foundAt >= 0 {
var roles []*data.Role
// slice out deleted role
roles = append(roles, p.Signed.Delegations.Roles[:foundAt]...)
if foundAt+1 < len(p.Signed.Delegations.Roles) {
roles = append(roles, p.Signed.Delegations.Roles[foundAt+1:]...)
}
p.Signed.Delegations.Roles = roles
utils.RemoveUnusedKeys(p)
p.Dirty = true
} // if the role wasn't found, it's a good as deleted
return nil
}
|
[
"func",
"(",
"tr",
"*",
"Repo",
")",
"DeleteDelegation",
"(",
"roleName",
"data",
".",
"RoleName",
")",
"error",
"{",
"if",
"!",
"data",
".",
"IsDelegation",
"(",
"roleName",
")",
"{",
"return",
"data",
".",
"ErrInvalidRole",
"{",
"Role",
":",
"roleName",
",",
"Reason",
":",
"\"",
"\"",
"}",
"\n",
"}",
"\n\n",
"parent",
":=",
"roleName",
".",
"Parent",
"(",
")",
"\n",
"if",
"err",
":=",
"tr",
".",
"VerifyCanSign",
"(",
"parent",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// delete delegated data from Targets map and Snapshot - if they don't",
"// exist, these are no-op",
"delete",
"(",
"tr",
".",
"Targets",
",",
"roleName",
")",
"\n",
"tr",
".",
"Snapshot",
".",
"DeleteMeta",
"(",
"roleName",
")",
"\n\n",
"p",
",",
"ok",
":=",
"tr",
".",
"Targets",
"[",
"parent",
"]",
"\n",
"if",
"!",
"ok",
"{",
"// if there is no parent metadata (the role exists though), then this",
"// is as good as done.",
"return",
"nil",
"\n",
"}",
"\n\n",
"foundAt",
":=",
"utils",
".",
"FindRoleIndex",
"(",
"p",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
",",
"roleName",
")",
"\n\n",
"if",
"foundAt",
">=",
"0",
"{",
"var",
"roles",
"[",
"]",
"*",
"data",
".",
"Role",
"\n",
"// slice out deleted role",
"roles",
"=",
"append",
"(",
"roles",
",",
"p",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
"[",
":",
"foundAt",
"]",
"...",
")",
"\n",
"if",
"foundAt",
"+",
"1",
"<",
"len",
"(",
"p",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
")",
"{",
"roles",
"=",
"append",
"(",
"roles",
",",
"p",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
"[",
"foundAt",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"p",
".",
"Signed",
".",
"Delegations",
".",
"Roles",
"=",
"roles",
"\n\n",
"utils",
".",
"RemoveUnusedKeys",
"(",
"p",
")",
"\n\n",
"p",
".",
"Dirty",
"=",
"true",
"\n",
"}",
"// if the role wasn't found, it's a good as deleted",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteDelegation removes a delegated targets role from its parent
// targets object. It also deletes the delegation from the snapshot.
// DeleteDelegation will only make use of the role Name field.
|
[
"DeleteDelegation",
"removes",
"a",
"delegated",
"targets",
"role",
"from",
"its",
"parent",
"targets",
"object",
".",
"It",
"also",
"deletes",
"the",
"delegation",
"from",
"the",
"snapshot",
".",
"DeleteDelegation",
"will",
"only",
"make",
"use",
"of",
"the",
"role",
"Name",
"field",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L512-L551
|
train
|
theupdateframework/notary
|
tuf/tuf.go
|
InitRoot
|
func (tr *Repo) InitRoot(root, timestamp, snapshot, targets data.BaseRole, consistent bool) error {
rootRoles := make(map[data.RoleName]*data.RootRole)
rootKeys := make(map[string]data.PublicKey)
for _, r := range []data.BaseRole{root, timestamp, snapshot, targets} {
rootRoles[r.Name] = &data.RootRole{
Threshold: r.Threshold,
KeyIDs: r.ListKeyIDs(),
}
for kid, k := range r.Keys {
rootKeys[kid] = k
}
}
r, err := data.NewRoot(rootKeys, rootRoles, consistent)
if err != nil {
return err
}
tr.Root = r
tr.originalRootRole = root
return nil
}
|
go
|
func (tr *Repo) InitRoot(root, timestamp, snapshot, targets data.BaseRole, consistent bool) error {
rootRoles := make(map[data.RoleName]*data.RootRole)
rootKeys := make(map[string]data.PublicKey)
for _, r := range []data.BaseRole{root, timestamp, snapshot, targets} {
rootRoles[r.Name] = &data.RootRole{
Threshold: r.Threshold,
KeyIDs: r.ListKeyIDs(),
}
for kid, k := range r.Keys {
rootKeys[kid] = k
}
}
r, err := data.NewRoot(rootKeys, rootRoles, consistent)
if err != nil {
return err
}
tr.Root = r
tr.originalRootRole = root
return nil
}
|
[
"func",
"(",
"tr",
"*",
"Repo",
")",
"InitRoot",
"(",
"root",
",",
"timestamp",
",",
"snapshot",
",",
"targets",
"data",
".",
"BaseRole",
",",
"consistent",
"bool",
")",
"error",
"{",
"rootRoles",
":=",
"make",
"(",
"map",
"[",
"data",
".",
"RoleName",
"]",
"*",
"data",
".",
"RootRole",
")",
"\n",
"rootKeys",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"data",
".",
"PublicKey",
")",
"\n\n",
"for",
"_",
",",
"r",
":=",
"range",
"[",
"]",
"data",
".",
"BaseRole",
"{",
"root",
",",
"timestamp",
",",
"snapshot",
",",
"targets",
"}",
"{",
"rootRoles",
"[",
"r",
".",
"Name",
"]",
"=",
"&",
"data",
".",
"RootRole",
"{",
"Threshold",
":",
"r",
".",
"Threshold",
",",
"KeyIDs",
":",
"r",
".",
"ListKeyIDs",
"(",
")",
",",
"}",
"\n",
"for",
"kid",
",",
"k",
":=",
"range",
"r",
".",
"Keys",
"{",
"rootKeys",
"[",
"kid",
"]",
"=",
"k",
"\n",
"}",
"\n",
"}",
"\n",
"r",
",",
"err",
":=",
"data",
".",
"NewRoot",
"(",
"rootKeys",
",",
"rootRoles",
",",
"consistent",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"tr",
".",
"Root",
"=",
"r",
"\n",
"tr",
".",
"originalRootRole",
"=",
"root",
"\n",
"return",
"nil",
"\n",
"}"
] |
// InitRoot initializes an empty root file with the 4 core roles passed to the
// method, and the consistent flag.
|
[
"InitRoot",
"initializes",
"an",
"empty",
"root",
"file",
"with",
"the",
"4",
"core",
"roles",
"passed",
"to",
"the",
"method",
"and",
"the",
"consistent",
"flag",
"."
] |
8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5
|
https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/tuf.go#L555-L575
|
train
|
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.