repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
theupdateframework/notary | server/storage/sqldb.go | translateOldVersionError | func translateOldVersionError(err error) error {
switch err := err.(type) {
case *mysql.MySQLError:
// https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
// 1022 = Can't write; duplicate key in table '%s'
// 1062 = Duplicate entry '%s' for key %d
if err.Number == 1022 || err.Number == 1062 {
return ErrOldVersion{}
}
}
return err
} | go | func translateOldVersionError(err error) error {
switch err := err.(type) {
case *mysql.MySQLError:
// https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
// 1022 = Can't write; duplicate key in table '%s'
// 1062 = Duplicate entry '%s' for key %d
if err.Number == 1022 || err.Number == 1062 {
return ErrOldVersion{}
}
}
return err
} | [
"func",
"translateOldVersionError",
"(",
"err",
"error",
")",
"error",
"{",
"switch",
"err",
":=",
"err",
".",
"(",
"type",
")",
"{",
"case",
"*",
"mysql",
".",
"MySQLError",
":",
"if",
"err",
".",
"Number",
"==",
"1022",
"||",
"err",
".",
"Number",
... | // translateOldVersionError captures DB errors, and attempts to translate
// duplicate entry - currently only supports MySQL and Sqlite3 | [
"translateOldVersionError",
"captures",
"DB",
"errors",
"and",
"attempts",
"to",
"translate",
"duplicate",
"entry",
"-",
"currently",
"only",
"supports",
"MySQL",
"and",
"Sqlite3"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L35-L46 | train |
theupdateframework/notary | server/storage/sqldb.go | UpdateCurrent | func (db *SQLStorage) UpdateCurrent(gun data.GUN, update MetaUpdate) error {
// ensure we're not inserting an immediately old version - can't use the
// struct, because that only works with non-zero values, and Version
// can be 0.
exists := db.Where("gun = ? and role = ? and version >= ?",
gun.String(), update.Role.String(), update.Version).First(&TUFFile{})
if !exists.RecordNotFound() {
return ErrOldVersion{}
}
// only take out the transaction once we're about to start writing
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
checksum := sha256.Sum256(update.Data)
hexChecksum := hex.EncodeToString(checksum[:])
if err := func() error {
// write new TUFFile entry
if err = translateOldVersionError(tx.Create(&TUFFile{
Gun: gun.String(),
Role: update.Role.String(),
Version: update.Version,
SHA256: hexChecksum,
Data: update.Data,
}).Error); err != nil {
return err
}
// If we're publishing a timestamp, update the changefeed as this is
// technically an new version of the TUF repo
if update.Role == data.CanonicalTimestampRole {
if err := db.writeChangefeed(tx, gun, update.Version, hexChecksum); err != nil {
return err
}
}
return nil
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | go | func (db *SQLStorage) UpdateCurrent(gun data.GUN, update MetaUpdate) error {
// ensure we're not inserting an immediately old version - can't use the
// struct, because that only works with non-zero values, and Version
// can be 0.
exists := db.Where("gun = ? and role = ? and version >= ?",
gun.String(), update.Role.String(), update.Version).First(&TUFFile{})
if !exists.RecordNotFound() {
return ErrOldVersion{}
}
// only take out the transaction once we're about to start writing
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
checksum := sha256.Sum256(update.Data)
hexChecksum := hex.EncodeToString(checksum[:])
if err := func() error {
// write new TUFFile entry
if err = translateOldVersionError(tx.Create(&TUFFile{
Gun: gun.String(),
Role: update.Role.String(),
Version: update.Version,
SHA256: hexChecksum,
Data: update.Data,
}).Error); err != nil {
return err
}
// If we're publishing a timestamp, update the changefeed as this is
// technically an new version of the TUF repo
if update.Role == data.CanonicalTimestampRole {
if err := db.writeChangefeed(tx, gun, update.Version, hexChecksum); err != nil {
return err
}
}
return nil
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"UpdateCurrent",
"(",
"gun",
"data",
".",
"GUN",
",",
"update",
"MetaUpdate",
")",
"error",
"{",
"exists",
":=",
"db",
".",
"Where",
"(",
"\"gun = ? and role = ? and version >= ?\"",
",",
"gun",
".",
"String",
"(",
... | // UpdateCurrent updates a single TUF. | [
"UpdateCurrent",
"updates",
"a",
"single",
"TUF",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L49-L93 | train |
theupdateframework/notary | server/storage/sqldb.go | UpdateMany | func (db *SQLStorage) UpdateMany(gun data.GUN, updates []MetaUpdate) error {
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
var (
query *gorm.DB
added = make(map[uint]bool)
)
if err := func() error {
for _, update := range updates {
// This looks like the same logic as UpdateCurrent, but if we just
// called, version ordering in the updates list must be enforced
// (you cannot insert the version 2 before version 1). And we do
// not care about monotonic ordering in the updates.
query = db.Where("gun = ? and role = ? and version >= ?",
gun.String(), update.Role.String(), update.Version).First(&TUFFile{})
if !query.RecordNotFound() {
return ErrOldVersion{}
}
var row TUFFile
checksum := sha256.Sum256(update.Data)
hexChecksum := hex.EncodeToString(checksum[:])
query = tx.Where(map[string]interface{}{
"gun": gun.String(),
"role": update.Role.String(),
"version": update.Version,
}).Attrs("data", update.Data).Attrs("sha256", hexChecksum).FirstOrCreate(&row)
if query.Error != nil {
return translateOldVersionError(query.Error)
}
// it's previously been added, which means it's a duplicate entry
// in the same transaction
if _, ok := added[row.ID]; ok {
return ErrOldVersion{}
}
if update.Role == data.CanonicalTimestampRole {
if err := db.writeChangefeed(tx, gun, update.Version, hexChecksum); err != nil {
return err
}
}
added[row.ID] = true
}
return nil
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | go | func (db *SQLStorage) UpdateMany(gun data.GUN, updates []MetaUpdate) error {
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
var (
query *gorm.DB
added = make(map[uint]bool)
)
if err := func() error {
for _, update := range updates {
// This looks like the same logic as UpdateCurrent, but if we just
// called, version ordering in the updates list must be enforced
// (you cannot insert the version 2 before version 1). And we do
// not care about monotonic ordering in the updates.
query = db.Where("gun = ? and role = ? and version >= ?",
gun.String(), update.Role.String(), update.Version).First(&TUFFile{})
if !query.RecordNotFound() {
return ErrOldVersion{}
}
var row TUFFile
checksum := sha256.Sum256(update.Data)
hexChecksum := hex.EncodeToString(checksum[:])
query = tx.Where(map[string]interface{}{
"gun": gun.String(),
"role": update.Role.String(),
"version": update.Version,
}).Attrs("data", update.Data).Attrs("sha256", hexChecksum).FirstOrCreate(&row)
if query.Error != nil {
return translateOldVersionError(query.Error)
}
// it's previously been added, which means it's a duplicate entry
// in the same transaction
if _, ok := added[row.ID]; ok {
return ErrOldVersion{}
}
if update.Role == data.CanonicalTimestampRole {
if err := db.writeChangefeed(tx, gun, update.Version, hexChecksum); err != nil {
return err
}
}
added[row.ID] = true
}
return nil
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"UpdateMany",
"(",
"gun",
"data",
".",
"GUN",
",",
"updates",
"[",
"]",
"MetaUpdate",
")",
"error",
"{",
"tx",
",",
"rb",
",",
"err",
":=",
"db",
".",
"getTransaction",
"(",
")",
"\n",
"if",
"err",
"!=",
... | // UpdateMany atomically updates many TUF records in a single transaction | [
"UpdateMany",
"atomically",
"updates",
"many",
"TUF",
"records",
"in",
"a",
"single",
"transaction"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L115-L166 | train |
theupdateframework/notary | server/storage/sqldb.go | GetCurrent | func (db *SQLStorage) GetCurrent(gun data.GUN, tufRole data.RoleName) (*time.Time, []byte, error) {
var row TUFFile
q := db.Select("updated_at, data").Where(
&TUFFile{Gun: gun.String(), Role: tufRole.String()}).Order("version desc").Limit(1).First(&row)
if err := isReadErr(q, row); err != nil {
return nil, nil, err
}
return &(row.UpdatedAt), row.Data, nil
} | go | func (db *SQLStorage) GetCurrent(gun data.GUN, tufRole data.RoleName) (*time.Time, []byte, error) {
var row TUFFile
q := db.Select("updated_at, data").Where(
&TUFFile{Gun: gun.String(), Role: tufRole.String()}).Order("version desc").Limit(1).First(&row)
if err := isReadErr(q, row); err != nil {
return nil, nil, err
}
return &(row.UpdatedAt), row.Data, nil
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"GetCurrent",
"(",
"gun",
"data",
".",
"GUN",
",",
"tufRole",
"data",
".",
"RoleName",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"row",
"TUFFile",
"\n",
"q... | // GetCurrent gets a specific TUF record | [
"GetCurrent",
"gets",
"a",
"specific",
"TUF",
"record"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L179-L187 | train |
theupdateframework/notary | server/storage/sqldb.go | GetChecksum | func (db *SQLStorage) GetChecksum(gun data.GUN, tufRole data.RoleName, checksum string) (*time.Time, []byte, error) {
var row TUFFile
q := db.Select("created_at, data").Where(
&TUFFile{
Gun: gun.String(),
Role: tufRole.String(),
SHA256: checksum,
},
).First(&row)
if err := isReadErr(q, row); err != nil {
return nil, nil, err
}
return &(row.CreatedAt), row.Data, nil
} | go | func (db *SQLStorage) GetChecksum(gun data.GUN, tufRole data.RoleName, checksum string) (*time.Time, []byte, error) {
var row TUFFile
q := db.Select("created_at, data").Where(
&TUFFile{
Gun: gun.String(),
Role: tufRole.String(),
SHA256: checksum,
},
).First(&row)
if err := isReadErr(q, row); err != nil {
return nil, nil, err
}
return &(row.CreatedAt), row.Data, nil
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"GetChecksum",
"(",
"gun",
"data",
".",
"GUN",
",",
"tufRole",
"data",
".",
"RoleName",
",",
"checksum",
"string",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
... | // GetChecksum gets a specific TUF record by its hex checksum | [
"GetChecksum",
"gets",
"a",
"specific",
"TUF",
"record",
"by",
"its",
"hex",
"checksum"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L190-L203 | train |
theupdateframework/notary | server/storage/sqldb.go | Delete | func (db *SQLStorage) Delete(gun data.GUN) error {
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
if err := func() error {
res := tx.Unscoped().Where(&TUFFile{Gun: gun.String()}).Delete(TUFFile{})
if err := res.Error; err != nil {
return err
}
// if there weren't actually any records for the GUN, don't write
// a deletion change record.
if res.RowsAffected == 0 {
return nil
}
c := &SQLChange{
GUN: gun.String(),
Category: changeCategoryDeletion,
}
return tx.Create(c).Error
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | go | func (db *SQLStorage) Delete(gun data.GUN) error {
tx, rb, err := db.getTransaction()
if err != nil {
return err
}
if err := func() error {
res := tx.Unscoped().Where(&TUFFile{Gun: gun.String()}).Delete(TUFFile{})
if err := res.Error; err != nil {
return err
}
// if there weren't actually any records for the GUN, don't write
// a deletion change record.
if res.RowsAffected == 0 {
return nil
}
c := &SQLChange{
GUN: gun.String(),
Category: changeCategoryDeletion,
}
return tx.Create(c).Error
}(); err != nil {
return rb(err)
}
return tx.Commit().Error
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"Delete",
"(",
"gun",
"data",
".",
"GUN",
")",
"error",
"{",
"tx",
",",
"rb",
",",
"err",
":=",
"db",
".",
"getTransaction",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"... | // Delete deletes all the records for a specific GUN - we have to do a hard delete using Unscoped
// otherwise we can't insert for that GUN again | [
"Delete",
"deletes",
"all",
"the",
"records",
"for",
"a",
"specific",
"GUN",
"-",
"we",
"have",
"to",
"do",
"a",
"hard",
"delete",
"using",
"Unscoped",
"otherwise",
"we",
"can",
"t",
"insert",
"for",
"that",
"GUN",
"again"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L232-L256 | train |
theupdateframework/notary | server/storage/sqldb.go | CheckHealth | func (db *SQLStorage) CheckHealth() error {
tableOk := db.HasTable(&TUFFile{})
if db.Error != nil {
return db.Error
}
if !tableOk {
return fmt.Errorf(
"Cannot access table: %s", TUFFile{}.TableName())
}
return nil
} | go | func (db *SQLStorage) CheckHealth() error {
tableOk := db.HasTable(&TUFFile{})
if db.Error != nil {
return db.Error
}
if !tableOk {
return fmt.Errorf(
"Cannot access table: %s", TUFFile{}.TableName())
}
return nil
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"CheckHealth",
"(",
")",
"error",
"{",
"tableOk",
":=",
"db",
".",
"HasTable",
"(",
"&",
"TUFFile",
"{",
"}",
")",
"\n",
"if",
"db",
".",
"Error",
"!=",
"nil",
"{",
"return",
"db",
".",
"Error",
"\n",
"}... | // CheckHealth asserts that the tuf_files table is present | [
"CheckHealth",
"asserts",
"that",
"the",
"tuf_files",
"table",
"is",
"present"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L259-L269 | train |
theupdateframework/notary | server/storage/sqldb.go | GetChanges | func (db *SQLStorage) GetChanges(changeID string, records int, filterName string) ([]Change, error) {
var (
changes []Change
query = &db.DB
id int64
err error
)
if changeID == "" {
id = 0
} else {
id, err = strconv.ParseInt(changeID, 10, 32)
if err != nil {
return nil, ErrBadQuery{msg: fmt.Sprintf("change ID expected to be integer, provided ID was: %s", changeID)}
}
}
// do what I mean, not what I said, i.e. if I passed a negative number for the ID
// it's assumed I mean "start from latest and go backwards"
reversed := id < 0
if records < 0 {
reversed = true
records = -records
}
if filterName != "" {
query = query.Where("gun = ?", filterName)
}
if reversed {
if id > 0 {
// only set the id check if we're not starting from "latest"
query = query.Where("id < ?", id)
}
query = query.Order("id desc")
} else {
query = query.Where("id > ?", id).Order("id asc")
}
res := query.Limit(records).Find(&changes)
if res.Error != nil {
return nil, res.Error
}
if reversed {
// results are currently newest to oldest, should be oldest to newest
for i, j := 0, len(changes)-1; i < j; i, j = i+1, j-1 {
changes[i], changes[j] = changes[j], changes[i]
}
}
return changes, nil
} | go | func (db *SQLStorage) GetChanges(changeID string, records int, filterName string) ([]Change, error) {
var (
changes []Change
query = &db.DB
id int64
err error
)
if changeID == "" {
id = 0
} else {
id, err = strconv.ParseInt(changeID, 10, 32)
if err != nil {
return nil, ErrBadQuery{msg: fmt.Sprintf("change ID expected to be integer, provided ID was: %s", changeID)}
}
}
// do what I mean, not what I said, i.e. if I passed a negative number for the ID
// it's assumed I mean "start from latest and go backwards"
reversed := id < 0
if records < 0 {
reversed = true
records = -records
}
if filterName != "" {
query = query.Where("gun = ?", filterName)
}
if reversed {
if id > 0 {
// only set the id check if we're not starting from "latest"
query = query.Where("id < ?", id)
}
query = query.Order("id desc")
} else {
query = query.Where("id > ?", id).Order("id asc")
}
res := query.Limit(records).Find(&changes)
if res.Error != nil {
return nil, res.Error
}
if reversed {
// results are currently newest to oldest, should be oldest to newest
for i, j := 0, len(changes)-1; i < j; i, j = i+1, j-1 {
changes[i], changes[j] = changes[j], changes[i]
}
}
return changes, nil
} | [
"func",
"(",
"db",
"*",
"SQLStorage",
")",
"GetChanges",
"(",
"changeID",
"string",
",",
"records",
"int",
",",
"filterName",
"string",
")",
"(",
"[",
"]",
"Change",
",",
"error",
")",
"{",
"var",
"(",
"changes",
"[",
"]",
"Change",
"\n",
"query",
"=... | // GetChanges returns up to pageSize changes starting from changeID. | [
"GetChanges",
"returns",
"up",
"to",
"pageSize",
"changes",
"starting",
"from",
"changeID",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/sqldb.go#L272-L322 | train |
theupdateframework/notary | cmd/notary-signer/config.go | setUpCryptoservices | func setUpCryptoservices(configuration *viper.Viper, allowedBackends []string, doBootstrap bool) (
signer.CryptoServiceIndex, error) {
backend := configuration.GetString("storage.backend")
if !tufutils.StrSliceContains(allowedBackends, backend) {
return nil, fmt.Errorf("%s is not an allowed backend, must be one of: %s", backend, allowedBackends)
}
var keyService signed.CryptoService
switch backend {
case notary.MemoryBackend:
keyService = cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(
passphrase.ConstantRetriever("memory-db-ignore")))
case notary.RethinkDBBackend:
var sess *gorethink.Session
storeConfig, err := utils.ParseRethinkDBStorage(configuration)
if err != nil {
return nil, err
}
defaultAlias, err := getDefaultAlias(configuration)
if err != nil {
return nil, err
}
tlsOpts := tlsconfig.Options{
CAFile: storeConfig.CA,
CertFile: storeConfig.Cert,
KeyFile: storeConfig.Key,
ExclusiveRootPools: true,
}
if doBootstrap {
sess, err = rethinkdb.AdminConnection(tlsOpts, storeConfig.Source)
} else {
sess, err = rethinkdb.UserConnection(tlsOpts, storeConfig.Source, storeConfig.Username, storeConfig.Password)
}
if err != nil {
return nil, fmt.Errorf("Error starting %s driver: %s", backend, err.Error())
}
s := keydbstore.NewRethinkDBKeyStore(storeConfig.DBName, storeConfig.Username, storeConfig.Password, passphraseRetriever, defaultAlias, sess)
health.RegisterPeriodicFunc("DB operational", time.Minute, s.CheckHealth)
if doBootstrap {
keyService = s
} else {
keyService = keydbstore.NewCachedKeyService(s)
}
case notary.MySQLBackend, notary.SQLiteBackend, notary.PostgresBackend:
storeConfig, err := utils.ParseSQLStorage(configuration)
if err != nil {
return nil, err
}
defaultAlias, err := getDefaultAlias(configuration)
if err != nil {
return nil, err
}
dbStore, err := keydbstore.NewSQLKeyDBStore(
passphraseRetriever, defaultAlias, storeConfig.Backend, storeConfig.Source)
if err != nil {
return nil, fmt.Errorf("failed to create a new keydbstore: %v", err)
}
health.RegisterPeriodicFunc(
"DB operational", time.Minute, dbStore.HealthCheck)
keyService = keydbstore.NewCachedKeyService(dbStore)
}
if doBootstrap {
err := bootstrap(keyService)
if err != nil {
logrus.Fatal(err.Error())
}
os.Exit(0)
}
cryptoServices := make(signer.CryptoServiceIndex)
cryptoServices[data.ED25519Key] = keyService
cryptoServices[data.ECDSAKey] = keyService
return cryptoServices, nil
} | go | func setUpCryptoservices(configuration *viper.Viper, allowedBackends []string, doBootstrap bool) (
signer.CryptoServiceIndex, error) {
backend := configuration.GetString("storage.backend")
if !tufutils.StrSliceContains(allowedBackends, backend) {
return nil, fmt.Errorf("%s is not an allowed backend, must be one of: %s", backend, allowedBackends)
}
var keyService signed.CryptoService
switch backend {
case notary.MemoryBackend:
keyService = cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(
passphrase.ConstantRetriever("memory-db-ignore")))
case notary.RethinkDBBackend:
var sess *gorethink.Session
storeConfig, err := utils.ParseRethinkDBStorage(configuration)
if err != nil {
return nil, err
}
defaultAlias, err := getDefaultAlias(configuration)
if err != nil {
return nil, err
}
tlsOpts := tlsconfig.Options{
CAFile: storeConfig.CA,
CertFile: storeConfig.Cert,
KeyFile: storeConfig.Key,
ExclusiveRootPools: true,
}
if doBootstrap {
sess, err = rethinkdb.AdminConnection(tlsOpts, storeConfig.Source)
} else {
sess, err = rethinkdb.UserConnection(tlsOpts, storeConfig.Source, storeConfig.Username, storeConfig.Password)
}
if err != nil {
return nil, fmt.Errorf("Error starting %s driver: %s", backend, err.Error())
}
s := keydbstore.NewRethinkDBKeyStore(storeConfig.DBName, storeConfig.Username, storeConfig.Password, passphraseRetriever, defaultAlias, sess)
health.RegisterPeriodicFunc("DB operational", time.Minute, s.CheckHealth)
if doBootstrap {
keyService = s
} else {
keyService = keydbstore.NewCachedKeyService(s)
}
case notary.MySQLBackend, notary.SQLiteBackend, notary.PostgresBackend:
storeConfig, err := utils.ParseSQLStorage(configuration)
if err != nil {
return nil, err
}
defaultAlias, err := getDefaultAlias(configuration)
if err != nil {
return nil, err
}
dbStore, err := keydbstore.NewSQLKeyDBStore(
passphraseRetriever, defaultAlias, storeConfig.Backend, storeConfig.Source)
if err != nil {
return nil, fmt.Errorf("failed to create a new keydbstore: %v", err)
}
health.RegisterPeriodicFunc(
"DB operational", time.Minute, dbStore.HealthCheck)
keyService = keydbstore.NewCachedKeyService(dbStore)
}
if doBootstrap {
err := bootstrap(keyService)
if err != nil {
logrus.Fatal(err.Error())
}
os.Exit(0)
}
cryptoServices := make(signer.CryptoServiceIndex)
cryptoServices[data.ED25519Key] = keyService
cryptoServices[data.ECDSAKey] = keyService
return cryptoServices, nil
} | [
"func",
"setUpCryptoservices",
"(",
"configuration",
"*",
"viper",
".",
"Viper",
",",
"allowedBackends",
"[",
"]",
"string",
",",
"doBootstrap",
"bool",
")",
"(",
"signer",
".",
"CryptoServiceIndex",
",",
"error",
")",
"{",
"backend",
":=",
"configuration",
".... | // Reads the configuration file for storage setup, and sets up the cryptoservice
// mapping | [
"Reads",
"the",
"configuration",
"file",
"for",
"storage",
"setup",
"and",
"sets",
"up",
"the",
"cryptoservice",
"mapping"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-signer/config.go#L103-L180 | train |
theupdateframework/notary | cmd/notary-signer/config.go | setupGRPCServer | func setupGRPCServer(signerConfig signer.Config) (*grpc.Server, net.Listener, error) {
//RPC server setup
kms := &api.KeyManagementServer{
CryptoServices: signerConfig.CryptoServices,
}
ss := &api.SignerServer{
CryptoServices: signerConfig.CryptoServices,
}
hs := ghealth.NewServer()
lis, err := net.Listen("tcp", signerConfig.GRPCAddr)
if err != nil {
return nil, nil, fmt.Errorf("grpc server failed to listen on %s: %v",
signerConfig.GRPCAddr, err)
}
creds := credentials.NewTLS(signerConfig.TLSConfig)
opts := []grpc.ServerOption{grpc.Creds(creds)}
grpcServer := grpc.NewServer(opts...)
pb.RegisterKeyManagementServer(grpcServer, kms)
pb.RegisterSignerServer(grpcServer, ss)
healthpb.RegisterHealthServer(grpcServer, hs)
// Set status for both of the grpc service "KeyManagement" and "Signer", these are
// the only two we have at present, if we add more grpc service in the future,
// we should add a new line for that service here as well.
hs.SetServingStatus(notary.HealthCheckKeyManagement, healthpb.HealthCheckResponse_SERVING)
hs.SetServingStatus(notary.HealthCheckSigner, healthpb.HealthCheckResponse_SERVING)
return grpcServer, lis, nil
} | go | func setupGRPCServer(signerConfig signer.Config) (*grpc.Server, net.Listener, error) {
//RPC server setup
kms := &api.KeyManagementServer{
CryptoServices: signerConfig.CryptoServices,
}
ss := &api.SignerServer{
CryptoServices: signerConfig.CryptoServices,
}
hs := ghealth.NewServer()
lis, err := net.Listen("tcp", signerConfig.GRPCAddr)
if err != nil {
return nil, nil, fmt.Errorf("grpc server failed to listen on %s: %v",
signerConfig.GRPCAddr, err)
}
creds := credentials.NewTLS(signerConfig.TLSConfig)
opts := []grpc.ServerOption{grpc.Creds(creds)}
grpcServer := grpc.NewServer(opts...)
pb.RegisterKeyManagementServer(grpcServer, kms)
pb.RegisterSignerServer(grpcServer, ss)
healthpb.RegisterHealthServer(grpcServer, hs)
// Set status for both of the grpc service "KeyManagement" and "Signer", these are
// the only two we have at present, if we add more grpc service in the future,
// we should add a new line for that service here as well.
hs.SetServingStatus(notary.HealthCheckKeyManagement, healthpb.HealthCheckResponse_SERVING)
hs.SetServingStatus(notary.HealthCheckSigner, healthpb.HealthCheckResponse_SERVING)
return grpcServer, lis, nil
} | [
"func",
"setupGRPCServer",
"(",
"signerConfig",
"signer",
".",
"Config",
")",
"(",
"*",
"grpc",
".",
"Server",
",",
"net",
".",
"Listener",
",",
"error",
")",
"{",
"kms",
":=",
"&",
"api",
".",
"KeyManagementServer",
"{",
"CryptoServices",
":",
"signerConf... | // set up the GRPC server | [
"set",
"up",
"the",
"GRPC",
"server"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary-signer/config.go#L197-L229 | train |
theupdateframework/notary | trustpinning/certs.go | validRootIntCerts | func validRootIntCerts(allIntCerts map[string][]*x509.Certificate) map[string][]*x509.Certificate {
validIntCerts := make(map[string][]*x509.Certificate)
// Go through every leaf cert ID, and build its valid intermediate certificate list
for leafID, intCertList := range allIntCerts {
for _, intCert := range intCertList {
if err := utils.ValidateCertificate(intCert, true); err != nil {
continue
}
validIntCerts[leafID] = append(validIntCerts[leafID], intCert)
}
}
return validIntCerts
} | go | func validRootIntCerts(allIntCerts map[string][]*x509.Certificate) map[string][]*x509.Certificate {
validIntCerts := make(map[string][]*x509.Certificate)
// Go through every leaf cert ID, and build its valid intermediate certificate list
for leafID, intCertList := range allIntCerts {
for _, intCert := range intCertList {
if err := utils.ValidateCertificate(intCert, true); err != nil {
continue
}
validIntCerts[leafID] = append(validIntCerts[leafID], intCert)
}
}
return validIntCerts
} | [
"func",
"validRootIntCerts",
"(",
"allIntCerts",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
"{",
"validIntCerts",
":=",
"make",
"(",
"map",
"[",
"stri... | // validRootIntCerts filters the passed in structure of intermediate certificates to only include non-expired, non-sha1 certificates
// Note that this "validity" alone does not imply any measure of trust. | [
"validRootIntCerts",
"filters",
"the",
"passed",
"in",
"structure",
"of",
"intermediate",
"certificates",
"to",
"only",
"include",
"non",
"-",
"expired",
"non",
"-",
"sha1",
"certificates",
"Note",
"that",
"this",
"validity",
"alone",
"does",
"not",
"imply",
"an... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustpinning/certs.go#L227-L241 | train |
theupdateframework/notary | trustpinning/certs.go | parseAllCerts | func parseAllCerts(signedRoot *data.SignedRoot) (map[string]*x509.Certificate, map[string][]*x509.Certificate) {
if signedRoot == nil {
return nil, nil
}
leafCerts := make(map[string]*x509.Certificate)
intCerts := make(map[string][]*x509.Certificate)
// Before we loop through all root keys available, make sure any exist
rootRoles, ok := signedRoot.Signed.Roles[data.CanonicalRootRole]
if !ok {
logrus.Debugf("tried to parse certificates from invalid root signed data")
return nil, nil
}
logrus.Debugf("found the following root keys: %v", rootRoles.KeyIDs)
// Iterate over every keyID for the root role inside of roots.json
for _, keyID := range rootRoles.KeyIDs {
// check that the key exists in the signed root keys map
key, ok := signedRoot.Signed.Keys[keyID]
if !ok {
logrus.Debugf("error while getting data for keyID: %s", keyID)
continue
}
// Decode all the x509 certificates that were bundled with this
// Specific root key
decodedCerts, err := utils.LoadCertBundleFromPEM(key.Public())
if err != nil {
logrus.Debugf("error while parsing root certificate with keyID: %s, %v", keyID, err)
continue
}
// Get all non-CA certificates in the decoded certificates
leafCertList := utils.GetLeafCerts(decodedCerts)
// If we got no leaf certificates or we got more than one, fail
if len(leafCertList) != 1 {
logrus.Debugf("invalid chain due to leaf certificate missing or too many leaf certificates for keyID: %s", keyID)
continue
}
// If we found a leaf certificate, assert that the cert bundle started with a leaf
if decodedCerts[0].IsCA {
logrus.Debugf("invalid chain due to leaf certificate not being first certificate for keyID: %s", keyID)
continue
}
// Get the ID of the leaf certificate
leafCert := leafCertList[0]
// Store the leaf cert in the map
leafCerts[key.ID()] = leafCert
// Get all the remainder certificates marked as a CA to be used as intermediates
intermediateCerts := utils.GetIntermediateCerts(decodedCerts)
intCerts[key.ID()] = intermediateCerts
}
return leafCerts, intCerts
} | go | func parseAllCerts(signedRoot *data.SignedRoot) (map[string]*x509.Certificate, map[string][]*x509.Certificate) {
if signedRoot == nil {
return nil, nil
}
leafCerts := make(map[string]*x509.Certificate)
intCerts := make(map[string][]*x509.Certificate)
// Before we loop through all root keys available, make sure any exist
rootRoles, ok := signedRoot.Signed.Roles[data.CanonicalRootRole]
if !ok {
logrus.Debugf("tried to parse certificates from invalid root signed data")
return nil, nil
}
logrus.Debugf("found the following root keys: %v", rootRoles.KeyIDs)
// Iterate over every keyID for the root role inside of roots.json
for _, keyID := range rootRoles.KeyIDs {
// check that the key exists in the signed root keys map
key, ok := signedRoot.Signed.Keys[keyID]
if !ok {
logrus.Debugf("error while getting data for keyID: %s", keyID)
continue
}
// Decode all the x509 certificates that were bundled with this
// Specific root key
decodedCerts, err := utils.LoadCertBundleFromPEM(key.Public())
if err != nil {
logrus.Debugf("error while parsing root certificate with keyID: %s, %v", keyID, err)
continue
}
// Get all non-CA certificates in the decoded certificates
leafCertList := utils.GetLeafCerts(decodedCerts)
// If we got no leaf certificates or we got more than one, fail
if len(leafCertList) != 1 {
logrus.Debugf("invalid chain due to leaf certificate missing or too many leaf certificates for keyID: %s", keyID)
continue
}
// If we found a leaf certificate, assert that the cert bundle started with a leaf
if decodedCerts[0].IsCA {
logrus.Debugf("invalid chain due to leaf certificate not being first certificate for keyID: %s", keyID)
continue
}
// Get the ID of the leaf certificate
leafCert := leafCertList[0]
// Store the leaf cert in the map
leafCerts[key.ID()] = leafCert
// Get all the remainder certificates marked as a CA to be used as intermediates
intermediateCerts := utils.GetIntermediateCerts(decodedCerts)
intCerts[key.ID()] = intermediateCerts
}
return leafCerts, intCerts
} | [
"func",
"parseAllCerts",
"(",
"signedRoot",
"*",
"data",
".",
"SignedRoot",
")",
"(",
"map",
"[",
"string",
"]",
"*",
"x509",
".",
"Certificate",
",",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"x509",
".",
"Certificate",
")",
"{",
"if",
"signedRoot",
... | // parseAllCerts returns two maps, one with all of the leafCertificates and one
// with all the intermediate certificates found in signedRoot | [
"parseAllCerts",
"returns",
"two",
"maps",
"one",
"with",
"all",
"of",
"the",
"leafCertificates",
"and",
"one",
"with",
"all",
"the",
"intermediate",
"certificates",
"found",
"in",
"signedRoot"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustpinning/certs.go#L245-L304 | train |
theupdateframework/notary | storage/memorystore.go | NewMemoryStore | func NewMemoryStore(seed map[data.RoleName][]byte) *MemoryStore {
var (
consistent = make(map[string][]byte)
initial = make(map[string][]byte)
)
// add all seed meta to consistent
for name, d := range seed {
checksum := sha256.Sum256(d)
path := utils.ConsistentName(name.String(), checksum[:])
initial[name.String()] = d
consistent[path] = d
}
return &MemoryStore{
data: initial,
consistent: consistent,
}
} | go | func NewMemoryStore(seed map[data.RoleName][]byte) *MemoryStore {
var (
consistent = make(map[string][]byte)
initial = make(map[string][]byte)
)
// add all seed meta to consistent
for name, d := range seed {
checksum := sha256.Sum256(d)
path := utils.ConsistentName(name.String(), checksum[:])
initial[name.String()] = d
consistent[path] = d
}
return &MemoryStore{
data: initial,
consistent: consistent,
}
} | [
"func",
"NewMemoryStore",
"(",
"seed",
"map",
"[",
"data",
".",
"RoleName",
"]",
"[",
"]",
"byte",
")",
"*",
"MemoryStore",
"{",
"var",
"(",
"consistent",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"\n",
"initial",
"=",
"ma... | // NewMemoryStore returns a MetadataStore that operates entirely in memory.
// Very useful for testing | [
"NewMemoryStore",
"returns",
"a",
"MetadataStore",
"that",
"operates",
"entirely",
"in",
"memory",
".",
"Very",
"useful",
"for",
"testing"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L15-L32 | train |
theupdateframework/notary | storage/memorystore.go | GetSized | func (m MemoryStore) GetSized(name string, size int64) ([]byte, error) {
d, ok := m.data[name]
if ok {
if size == NoSizeLimit {
size = notary.MaxDownloadSize
}
if int64(len(d)) < size {
return d, nil
}
return d[:size], nil
}
d, ok = m.consistent[name]
if ok {
if int64(len(d)) < size {
return d, nil
}
return d[:size], nil
}
return nil, ErrMetaNotFound{Resource: name}
} | go | func (m MemoryStore) GetSized(name string, size int64) ([]byte, error) {
d, ok := m.data[name]
if ok {
if size == NoSizeLimit {
size = notary.MaxDownloadSize
}
if int64(len(d)) < size {
return d, nil
}
return d[:size], nil
}
d, ok = m.consistent[name]
if ok {
if int64(len(d)) < size {
return d, nil
}
return d[:size], nil
}
return nil, ErrMetaNotFound{Resource: name}
} | [
"func",
"(",
"m",
"MemoryStore",
")",
"GetSized",
"(",
"name",
"string",
",",
"size",
"int64",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"d",
",",
"ok",
":=",
"m",
".",
"data",
"[",
"name",
"]",
"\n",
"if",
"ok",
"{",
"if",
"size",
... | // GetSized returns up to size bytes of data references by name.
// If size is "NoSizeLimit", this corresponds to "infinite," but we cut off at a
// predefined threshold "notary.MaxDownloadSize", as we will always know the
// size for everything but a timestamp and sometimes a root,
// neither of which should be exceptionally large | [
"GetSized",
"returns",
"up",
"to",
"size",
"bytes",
"of",
"data",
"references",
"by",
"name",
".",
"If",
"size",
"is",
"NoSizeLimit",
"this",
"corresponds",
"to",
"infinite",
"but",
"we",
"cut",
"off",
"at",
"a",
"predefined",
"threshold",
"notary",
".",
"... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L46-L65 | train |
theupdateframework/notary | storage/memorystore.go | Get | func (m MemoryStore) Get(name string) ([]byte, error) {
if d, ok := m.data[name]; ok {
return d, nil
}
if d, ok := m.consistent[name]; ok {
return d, nil
}
return nil, ErrMetaNotFound{Resource: name}
} | go | func (m MemoryStore) Get(name string) ([]byte, error) {
if d, ok := m.data[name]; ok {
return d, nil
}
if d, ok := m.consistent[name]; ok {
return d, nil
}
return nil, ErrMetaNotFound{Resource: name}
} | [
"func",
"(",
"m",
"MemoryStore",
")",
"Get",
"(",
"name",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"d",
",",
"ok",
":=",
"m",
".",
"data",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"d",
",",
"nil",
"\n",
"}",
"\... | // Get returns the data associated with name | [
"Get",
"returns",
"the",
"data",
"associated",
"with",
"name"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L68-L76 | train |
theupdateframework/notary | storage/memorystore.go | Set | func (m *MemoryStore) Set(name string, meta []byte) error {
m.data[name] = meta
parsedMeta := &data.SignedMeta{}
err := json.Unmarshal(meta, parsedMeta)
if err == nil {
// no parse error means this is metadata and not a key, so store by version
version := parsedMeta.Signed.Version
versionedName := fmt.Sprintf("%d.%s", version, name)
m.data[versionedName] = meta
}
checksum := sha256.Sum256(meta)
path := utils.ConsistentName(name, checksum[:])
m.consistent[path] = meta
return nil
} | go | func (m *MemoryStore) Set(name string, meta []byte) error {
m.data[name] = meta
parsedMeta := &data.SignedMeta{}
err := json.Unmarshal(meta, parsedMeta)
if err == nil {
// no parse error means this is metadata and not a key, so store by version
version := parsedMeta.Signed.Version
versionedName := fmt.Sprintf("%d.%s", version, name)
m.data[versionedName] = meta
}
checksum := sha256.Sum256(meta)
path := utils.ConsistentName(name, checksum[:])
m.consistent[path] = meta
return nil
} | [
"func",
"(",
"m",
"*",
"MemoryStore",
")",
"Set",
"(",
"name",
"string",
",",
"meta",
"[",
"]",
"byte",
")",
"error",
"{",
"m",
".",
"data",
"[",
"name",
"]",
"=",
"meta",
"\n",
"parsedMeta",
":=",
"&",
"data",
".",
"SignedMeta",
"{",
"}",
"\n",
... | // Set sets the metadata value for the given name | [
"Set",
"sets",
"the",
"metadata",
"value",
"for",
"the",
"given",
"name"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L79-L95 | train |
theupdateframework/notary | storage/memorystore.go | SetMulti | func (m *MemoryStore) SetMulti(metas map[string][]byte) error {
for role, blob := range metas {
m.Set(role, blob)
}
return nil
} | go | func (m *MemoryStore) SetMulti(metas map[string][]byte) error {
for role, blob := range metas {
m.Set(role, blob)
}
return nil
} | [
"func",
"(",
"m",
"*",
"MemoryStore",
")",
"SetMulti",
"(",
"metas",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"error",
"{",
"for",
"role",
",",
"blob",
":=",
"range",
"metas",
"{",
"m",
".",
"Set",
"(",
"role",
",",
"blob",
")",
"\n",
... | // SetMulti sets multiple pieces of metadata for multiple names
// in a single operation. | [
"SetMulti",
"sets",
"multiple",
"pieces",
"of",
"metadata",
"for",
"multiple",
"names",
"in",
"a",
"single",
"operation",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L99-L104 | train |
theupdateframework/notary | storage/memorystore.go | ListFiles | func (m *MemoryStore) ListFiles() []string {
names := make([]string, 0, len(m.data))
for n := range m.data {
names = append(names, n)
}
return names
} | go | func (m *MemoryStore) ListFiles() []string {
names := make([]string, 0, len(m.data))
for n := range m.data {
names = append(names, n)
}
return names
} | [
"func",
"(",
"m",
"*",
"MemoryStore",
")",
"ListFiles",
"(",
")",
"[",
"]",
"string",
"{",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"m",
".",
"data",
")",
")",
"\n",
"for",
"n",
":=",
"range",
"m",
".",
"data... | // ListFiles returns a list of all files. The names returned should be
// usable with Get directly, with no modification. | [
"ListFiles",
"returns",
"a",
"list",
"of",
"all",
"files",
".",
"The",
"names",
"returned",
"should",
"be",
"usable",
"with",
"Get",
"directly",
"with",
"no",
"modification",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/memorystore.go#L131-L137 | train |
theupdateframework/notary | server/storage/tuf_store.go | NewTUFMetaStorage | func NewTUFMetaStorage(m MetaStore) *TUFMetaStorage {
return &TUFMetaStorage{
MetaStore: m,
cachedMeta: make(map[string]*storedMeta),
}
} | go | func NewTUFMetaStorage(m MetaStore) *TUFMetaStorage {
return &TUFMetaStorage{
MetaStore: m,
cachedMeta: make(map[string]*storedMeta),
}
} | [
"func",
"NewTUFMetaStorage",
"(",
"m",
"MetaStore",
")",
"*",
"TUFMetaStorage",
"{",
"return",
"&",
"TUFMetaStorage",
"{",
"MetaStore",
":",
"m",
",",
"cachedMeta",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"storedMeta",
")",
",",
"}",
"\n",
"}"
... | // NewTUFMetaStorage instantiates a TUFMetaStorage instance | [
"NewTUFMetaStorage",
"instantiates",
"a",
"TUFMetaStorage",
"instance"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/tuf_store.go#L23-L28 | train |
theupdateframework/notary | server/storage/tuf_store.go | GetCurrent | func (tms TUFMetaStorage) GetCurrent(gun data.GUN, tufRole data.RoleName) (*time.Time, []byte, error) {
timestampTime, timestampJSON, err := tms.MetaStore.GetCurrent(gun, data.CanonicalTimestampRole)
if err != nil {
return nil, nil, err
}
// If we wanted data for the timestamp role, we're done here
if tufRole == data.CanonicalTimestampRole {
return timestampTime, timestampJSON, nil
}
// If we want to lookup another role, walk to it via current timestamp --> snapshot by checksum --> desired role
timestampMeta := &data.SignedTimestamp{}
if err := json.Unmarshal(timestampJSON, timestampMeta); err != nil {
return nil, nil, fmt.Errorf("could not parse current timestamp")
}
snapshotChecksums, err := timestampMeta.GetSnapshot()
if err != nil || snapshotChecksums == nil {
return nil, nil, fmt.Errorf("could not retrieve latest snapshot checksum")
}
snapshotSHA256Bytes, ok := snapshotChecksums.Hashes[notary.SHA256]
if !ok {
return nil, nil, fmt.Errorf("could not retrieve latest snapshot sha256")
}
snapshotSHA256Hex := hex.EncodeToString(snapshotSHA256Bytes[:])
// Check the cache if we have our snapshot data
var snapshotTime *time.Time
var snapshotJSON []byte
if cachedSnapshotData, ok := tms.cachedMeta[snapshotSHA256Hex]; ok {
snapshotTime = cachedSnapshotData.createupdate
snapshotJSON = cachedSnapshotData.data
} else {
// Get the snapshot from the underlying store by checksum if it isn't cached yet
snapshotTime, snapshotJSON, err = tms.GetChecksum(gun, data.CanonicalSnapshotRole, snapshotSHA256Hex)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[snapshotSHA256Hex] = &storedMeta{data: snapshotJSON, createupdate: snapshotTime}
}
// If we wanted data for the snapshot role, we're done here
if tufRole == data.CanonicalSnapshotRole {
return snapshotTime, snapshotJSON, nil
}
// If it's a different role, we should have the checksum in snapshot metadata, and we can use it to GetChecksum()
snapshotMeta := &data.SignedSnapshot{}
if err := json.Unmarshal(snapshotJSON, snapshotMeta); err != nil {
return nil, nil, fmt.Errorf("could not parse current snapshot")
}
roleMeta, err := snapshotMeta.GetMeta(tufRole)
if err != nil {
return nil, nil, err
}
roleSHA256Bytes, ok := roleMeta.Hashes[notary.SHA256]
if !ok {
return nil, nil, fmt.Errorf("could not retrieve latest %s sha256", tufRole)
}
roleSHA256Hex := hex.EncodeToString(roleSHA256Bytes[:])
// check if we can retrieve this data from cache
if cachedRoleData, ok := tms.cachedMeta[roleSHA256Hex]; ok {
return cachedRoleData.createupdate, cachedRoleData.data, nil
}
roleTime, roleJSON, err := tms.MetaStore.GetChecksum(gun, tufRole, roleSHA256Hex)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[roleSHA256Hex] = &storedMeta{data: roleJSON, createupdate: roleTime}
return roleTime, roleJSON, nil
} | go | func (tms TUFMetaStorage) GetCurrent(gun data.GUN, tufRole data.RoleName) (*time.Time, []byte, error) {
timestampTime, timestampJSON, err := tms.MetaStore.GetCurrent(gun, data.CanonicalTimestampRole)
if err != nil {
return nil, nil, err
}
// If we wanted data for the timestamp role, we're done here
if tufRole == data.CanonicalTimestampRole {
return timestampTime, timestampJSON, nil
}
// If we want to lookup another role, walk to it via current timestamp --> snapshot by checksum --> desired role
timestampMeta := &data.SignedTimestamp{}
if err := json.Unmarshal(timestampJSON, timestampMeta); err != nil {
return nil, nil, fmt.Errorf("could not parse current timestamp")
}
snapshotChecksums, err := timestampMeta.GetSnapshot()
if err != nil || snapshotChecksums == nil {
return nil, nil, fmt.Errorf("could not retrieve latest snapshot checksum")
}
snapshotSHA256Bytes, ok := snapshotChecksums.Hashes[notary.SHA256]
if !ok {
return nil, nil, fmt.Errorf("could not retrieve latest snapshot sha256")
}
snapshotSHA256Hex := hex.EncodeToString(snapshotSHA256Bytes[:])
// Check the cache if we have our snapshot data
var snapshotTime *time.Time
var snapshotJSON []byte
if cachedSnapshotData, ok := tms.cachedMeta[snapshotSHA256Hex]; ok {
snapshotTime = cachedSnapshotData.createupdate
snapshotJSON = cachedSnapshotData.data
} else {
// Get the snapshot from the underlying store by checksum if it isn't cached yet
snapshotTime, snapshotJSON, err = tms.GetChecksum(gun, data.CanonicalSnapshotRole, snapshotSHA256Hex)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[snapshotSHA256Hex] = &storedMeta{data: snapshotJSON, createupdate: snapshotTime}
}
// If we wanted data for the snapshot role, we're done here
if tufRole == data.CanonicalSnapshotRole {
return snapshotTime, snapshotJSON, nil
}
// If it's a different role, we should have the checksum in snapshot metadata, and we can use it to GetChecksum()
snapshotMeta := &data.SignedSnapshot{}
if err := json.Unmarshal(snapshotJSON, snapshotMeta); err != nil {
return nil, nil, fmt.Errorf("could not parse current snapshot")
}
roleMeta, err := snapshotMeta.GetMeta(tufRole)
if err != nil {
return nil, nil, err
}
roleSHA256Bytes, ok := roleMeta.Hashes[notary.SHA256]
if !ok {
return nil, nil, fmt.Errorf("could not retrieve latest %s sha256", tufRole)
}
roleSHA256Hex := hex.EncodeToString(roleSHA256Bytes[:])
// check if we can retrieve this data from cache
if cachedRoleData, ok := tms.cachedMeta[roleSHA256Hex]; ok {
return cachedRoleData.createupdate, cachedRoleData.data, nil
}
roleTime, roleJSON, err := tms.MetaStore.GetChecksum(gun, tufRole, roleSHA256Hex)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[roleSHA256Hex] = &storedMeta{data: roleJSON, createupdate: roleTime}
return roleTime, roleJSON, nil
} | [
"func",
"(",
"tms",
"TUFMetaStorage",
")",
"GetCurrent",
"(",
"gun",
"data",
".",
"GUN",
",",
"tufRole",
"data",
".",
"RoleName",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"timestampTime",
",",
"timestampJSON",
... | // GetCurrent gets a specific TUF record, by walking from the current Timestamp to other metadata by checksum | [
"GetCurrent",
"gets",
"a",
"specific",
"TUF",
"record",
"by",
"walking",
"from",
"the",
"current",
"Timestamp",
"to",
"other",
"metadata",
"by",
"checksum"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/tuf_store.go#L36-L107 | train |
theupdateframework/notary | server/storage/tuf_store.go | GetChecksum | func (tms TUFMetaStorage) GetChecksum(gun data.GUN, tufRole data.RoleName, checksum string) (*time.Time, []byte, error) {
if cachedRoleData, ok := tms.cachedMeta[checksum]; ok {
return cachedRoleData.createupdate, cachedRoleData.data, nil
}
roleTime, roleJSON, err := tms.MetaStore.GetChecksum(gun, tufRole, checksum)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[checksum] = &storedMeta{data: roleJSON, createupdate: roleTime}
return roleTime, roleJSON, nil
} | go | func (tms TUFMetaStorage) GetChecksum(gun data.GUN, tufRole data.RoleName, checksum string) (*time.Time, []byte, error) {
if cachedRoleData, ok := tms.cachedMeta[checksum]; ok {
return cachedRoleData.createupdate, cachedRoleData.data, nil
}
roleTime, roleJSON, err := tms.MetaStore.GetChecksum(gun, tufRole, checksum)
if err != nil {
return nil, nil, err
}
// cache for subsequent lookups
tms.cachedMeta[checksum] = &storedMeta{data: roleJSON, createupdate: roleTime}
return roleTime, roleJSON, nil
} | [
"func",
"(",
"tms",
"TUFMetaStorage",
")",
"GetChecksum",
"(",
"gun",
"data",
".",
"GUN",
",",
"tufRole",
"data",
".",
"RoleName",
",",
"checksum",
"string",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"... | // GetChecksum gets a specific TUF record by checksum, also checking the internal cache | [
"GetChecksum",
"gets",
"a",
"specific",
"TUF",
"record",
"by",
"checksum",
"also",
"checking",
"the",
"internal",
"cache"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/tuf_store.go#L110-L121 | train |
theupdateframework/notary | server/storage/tuf_store.go | Bootstrap | func (tms TUFMetaStorage) Bootstrap() error {
if s, ok := tms.MetaStore.(storage.Bootstrapper); ok {
return s.Bootstrap()
}
return fmt.Errorf("store does not support bootstrapping")
} | go | func (tms TUFMetaStorage) Bootstrap() error {
if s, ok := tms.MetaStore.(storage.Bootstrapper); ok {
return s.Bootstrap()
}
return fmt.Errorf("store does not support bootstrapping")
} | [
"func",
"(",
"tms",
"TUFMetaStorage",
")",
"Bootstrap",
"(",
")",
"error",
"{",
"if",
"s",
",",
"ok",
":=",
"tms",
".",
"MetaStore",
".",
"(",
"storage",
".",
"Bootstrapper",
")",
";",
"ok",
"{",
"return",
"s",
".",
"Bootstrap",
"(",
")",
"\n",
"}"... | // Bootstrap the store with tables if possible | [
"Bootstrap",
"the",
"store",
"with",
"tables",
"if",
"possible"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/tuf_store.go#L124-L129 | train |
theupdateframework/notary | signer/keydbstore/cachedcryptoservice.go | NewCachedKeyService | func NewCachedKeyService(baseKeyService signed.CryptoService) signed.CryptoService {
return &cachedKeyService{
CryptoService: baseKeyService,
lock: &sync.RWMutex{},
cachedKeys: make(map[string]*cachedKey),
}
} | go | func NewCachedKeyService(baseKeyService signed.CryptoService) signed.CryptoService {
return &cachedKeyService{
CryptoService: baseKeyService,
lock: &sync.RWMutex{},
cachedKeys: make(map[string]*cachedKey),
}
} | [
"func",
"NewCachedKeyService",
"(",
"baseKeyService",
"signed",
".",
"CryptoService",
")",
"signed",
".",
"CryptoService",
"{",
"return",
"&",
"cachedKeyService",
"{",
"CryptoService",
":",
"baseKeyService",
",",
"lock",
":",
"&",
"sync",
".",
"RWMutex",
"{",
"}... | // NewCachedKeyService returns a new signed.CryptoService that includes caching | [
"NewCachedKeyService",
"returns",
"a",
"new",
"signed",
".",
"CryptoService",
"that",
"includes",
"caching"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/cachedcryptoservice.go#L22-L28 | train |
theupdateframework/notary | cmd/notary/delegations.go | delegationsList | func (d *delegationCommander) delegationsList(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
cmd.Usage()
return fmt.Errorf(
"Please provide a Global Unique Name as an argument to list")
}
config, err := d.configGetter()
if err != nil {
return err
}
gun := data.GUN(args[0])
rt, err := getTransport(config, gun, readOnly)
if err != nil {
return err
}
trustPin, err := getTrustPinning(config)
if err != nil {
return err
}
// initialize repo with transport to get latest state of the world before listing delegations
nRepo, err := notaryclient.NewFileCachedRepository(
config.GetString("trust_dir"), gun, getRemoteTrustServer(config), rt, d.retriever, trustPin)
if err != nil {
return err
}
delegationRoles, err := nRepo.GetDelegationRoles()
if err != nil {
return fmt.Errorf("Error retrieving delegation roles for repository %s: %v", gun, err)
}
cmd.Println("")
prettyPrintRoles(delegationRoles, cmd.OutOrStdout(), "delegations")
cmd.Println("")
return nil
} | go | func (d *delegationCommander) delegationsList(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
cmd.Usage()
return fmt.Errorf(
"Please provide a Global Unique Name as an argument to list")
}
config, err := d.configGetter()
if err != nil {
return err
}
gun := data.GUN(args[0])
rt, err := getTransport(config, gun, readOnly)
if err != nil {
return err
}
trustPin, err := getTrustPinning(config)
if err != nil {
return err
}
// initialize repo with transport to get latest state of the world before listing delegations
nRepo, err := notaryclient.NewFileCachedRepository(
config.GetString("trust_dir"), gun, getRemoteTrustServer(config), rt, d.retriever, trustPin)
if err != nil {
return err
}
delegationRoles, err := nRepo.GetDelegationRoles()
if err != nil {
return fmt.Errorf("Error retrieving delegation roles for repository %s: %v", gun, err)
}
cmd.Println("")
prettyPrintRoles(delegationRoles, cmd.OutOrStdout(), "delegations")
cmd.Println("")
return nil
} | [
"func",
"(",
"d",
"*",
"delegationCommander",
")",
"delegationsList",
"(",
"cmd",
"*",
"cobra",
".",
"Command",
",",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
"{",
"cmd",
".",
"Usage",
"(",
")",
"\n",
... | // delegationsList lists all the delegations for a particular GUN | [
"delegationsList",
"lists",
"all",
"the",
"delegations",
"for",
"a",
"particular",
"GUN"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/delegations.go#L131-L171 | train |
theupdateframework/notary | cmd/notary/delegations.go | delegationRemove | func (d *delegationCommander) delegationRemove(cmd *cobra.Command, args []string) error {
config, gun, role, keyIDs, err := delegationAddInput(d, cmd, args)
if err != nil {
return err
}
trustPin, err := getTrustPinning(config)
if err != nil {
return err
}
// no online operations are performed by add so the transport argument
// should be nil
nRepo, err := notaryclient.NewFileCachedRepository(
config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, d.retriever, trustPin)
if err != nil {
return err
}
if d.removeAll {
cmd.Println("\nAre you sure you want to remove all data for this delegation? (yes/no)")
// Ask for confirmation before force removing delegation
if !d.forceYes {
confirmed := askConfirm(os.Stdin)
if !confirmed {
fatalf("Aborting action.")
}
} else {
cmd.Println("Confirmed `yes` from flag")
}
// Delete the entire delegation
err = nRepo.RemoveDelegationRole(role)
if err != nil {
return fmt.Errorf("failed to remove delegation: %v", err)
}
} else {
if d.allPaths {
err = nRepo.ClearDelegationPaths(role)
if err != nil {
return fmt.Errorf("failed to remove delegation: %v", err)
}
}
// Remove any keys or paths that we passed in
err = nRepo.RemoveDelegationKeysAndPaths(role, keyIDs, d.paths)
if err != nil {
return fmt.Errorf("failed to remove delegation: %v", err)
}
}
delegationRemoveOutput(cmd, d, gun, role, keyIDs)
return maybeAutoPublish(cmd, d.autoPublish, gun, config, d.retriever)
} | go | func (d *delegationCommander) delegationRemove(cmd *cobra.Command, args []string) error {
config, gun, role, keyIDs, err := delegationAddInput(d, cmd, args)
if err != nil {
return err
}
trustPin, err := getTrustPinning(config)
if err != nil {
return err
}
// no online operations are performed by add so the transport argument
// should be nil
nRepo, err := notaryclient.NewFileCachedRepository(
config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, d.retriever, trustPin)
if err != nil {
return err
}
if d.removeAll {
cmd.Println("\nAre you sure you want to remove all data for this delegation? (yes/no)")
// Ask for confirmation before force removing delegation
if !d.forceYes {
confirmed := askConfirm(os.Stdin)
if !confirmed {
fatalf("Aborting action.")
}
} else {
cmd.Println("Confirmed `yes` from flag")
}
// Delete the entire delegation
err = nRepo.RemoveDelegationRole(role)
if err != nil {
return fmt.Errorf("failed to remove delegation: %v", err)
}
} else {
if d.allPaths {
err = nRepo.ClearDelegationPaths(role)
if err != nil {
return fmt.Errorf("failed to remove delegation: %v", err)
}
}
// Remove any keys or paths that we passed in
err = nRepo.RemoveDelegationKeysAndPaths(role, keyIDs, d.paths)
if err != nil {
return fmt.Errorf("failed to remove delegation: %v", err)
}
}
delegationRemoveOutput(cmd, d, gun, role, keyIDs)
return maybeAutoPublish(cmd, d.autoPublish, gun, config, d.retriever)
} | [
"func",
"(",
"d",
"*",
"delegationCommander",
")",
"delegationRemove",
"(",
"cmd",
"*",
"cobra",
".",
"Command",
",",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"config",
",",
"gun",
",",
"role",
",",
"keyIDs",
",",
"err",
":=",
"delegationAddInput",... | // delegationRemove removes a public key from a specific role in a GUN | [
"delegationRemove",
"removes",
"a",
"public",
"key",
"from",
"a",
"specific",
"role",
"in",
"a",
"GUN"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/delegations.go#L174-L226 | train |
theupdateframework/notary | cmd/notary/delegations.go | delegationAdd | func (d *delegationCommander) delegationAdd(cmd *cobra.Command, args []string) error {
// We must have at least the gun and role name, and at least one key or path (or the --all-paths flag) to add
if len(args) < 2 || len(args) < 3 && d.paths == nil && !d.allPaths {
cmd.Usage()
return fmt.Errorf("must specify the Global Unique Name and the role of the delegation along with the public key certificate paths and/or a list of paths to add")
}
config, err := d.configGetter()
if err != nil {
return err
}
gun := data.GUN(args[0])
role := data.RoleName(args[1])
pubKeys, err := ingestPublicKeys(args)
if err != nil {
return err
}
checkAllPaths(d)
trustPin, err := getTrustPinning(config)
if err != nil {
return err
}
// no online operations are performed by add so the transport argument
// should be nil
nRepo, err := notaryclient.NewFileCachedRepository(
config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, d.retriever, trustPin)
if err != nil {
return err
}
// Add the delegation to the repository
err = nRepo.AddDelegation(role, pubKeys, d.paths)
if err != nil {
return fmt.Errorf("failed to create delegation: %v", err)
}
// Make keyID slice for better CLI print
pubKeyIDs := []string{}
for _, pubKey := range pubKeys {
pubKeyID, err := utils.CanonicalKeyID(pubKey)
if err != nil {
return err
}
pubKeyIDs = append(pubKeyIDs, pubKeyID)
}
cmd.Println("")
addingItems := ""
if len(pubKeyIDs) > 0 {
addingItems = addingItems + fmt.Sprintf("with keys %s, ", pubKeyIDs)
}
if d.paths != nil || d.allPaths {
addingItems = addingItems + fmt.Sprintf(
"with paths [%s], ",
strings.Join(prettyPaths(d.paths), "\n"),
)
}
cmd.Printf(
"Addition of delegation role %s %sto repository \"%s\" staged for next publish.\n",
role, addingItems, gun)
cmd.Println("")
return maybeAutoPublish(cmd, d.autoPublish, gun, config, d.retriever)
} | go | func (d *delegationCommander) delegationAdd(cmd *cobra.Command, args []string) error {
// We must have at least the gun and role name, and at least one key or path (or the --all-paths flag) to add
if len(args) < 2 || len(args) < 3 && d.paths == nil && !d.allPaths {
cmd.Usage()
return fmt.Errorf("must specify the Global Unique Name and the role of the delegation along with the public key certificate paths and/or a list of paths to add")
}
config, err := d.configGetter()
if err != nil {
return err
}
gun := data.GUN(args[0])
role := data.RoleName(args[1])
pubKeys, err := ingestPublicKeys(args)
if err != nil {
return err
}
checkAllPaths(d)
trustPin, err := getTrustPinning(config)
if err != nil {
return err
}
// no online operations are performed by add so the transport argument
// should be nil
nRepo, err := notaryclient.NewFileCachedRepository(
config.GetString("trust_dir"), gun, getRemoteTrustServer(config), nil, d.retriever, trustPin)
if err != nil {
return err
}
// Add the delegation to the repository
err = nRepo.AddDelegation(role, pubKeys, d.paths)
if err != nil {
return fmt.Errorf("failed to create delegation: %v", err)
}
// Make keyID slice for better CLI print
pubKeyIDs := []string{}
for _, pubKey := range pubKeys {
pubKeyID, err := utils.CanonicalKeyID(pubKey)
if err != nil {
return err
}
pubKeyIDs = append(pubKeyIDs, pubKeyID)
}
cmd.Println("")
addingItems := ""
if len(pubKeyIDs) > 0 {
addingItems = addingItems + fmt.Sprintf("with keys %s, ", pubKeyIDs)
}
if d.paths != nil || d.allPaths {
addingItems = addingItems + fmt.Sprintf(
"with paths [%s], ",
strings.Join(prettyPaths(d.paths), "\n"),
)
}
cmd.Printf(
"Addition of delegation role %s %sto repository \"%s\" staged for next publish.\n",
role, addingItems, gun)
cmd.Println("")
return maybeAutoPublish(cmd, d.autoPublish, gun, config, d.retriever)
} | [
"func",
"(",
"d",
"*",
"delegationCommander",
")",
"delegationAdd",
"(",
"cmd",
"*",
"cobra",
".",
"Command",
",",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"len",
"(",
"args",
")",
"<",
"2",
"||",
"len",
"(",
"args",
")",
"<",
"3",
"&... | // delegationAdd creates a new delegation by adding a public key from a certificate to a specific role in a GUN | [
"delegationAdd",
"creates",
"a",
"new",
"delegation",
"by",
"adding",
"a",
"public",
"key",
"from",
"a",
"certificate",
"to",
"a",
"specific",
"role",
"in",
"a",
"GUN"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cmd/notary/delegations.go#L288-L356 | train |
theupdateframework/notary | tuf/signed/ed25519.go | AddKey | func (e *Ed25519) AddKey(role data.RoleName, gun data.GUN, k data.PrivateKey) error {
e.addKey(role, k)
return nil
} | go | func (e *Ed25519) AddKey(role data.RoleName, gun data.GUN, k data.PrivateKey) error {
e.addKey(role, k)
return nil
} | [
"func",
"(",
"e",
"*",
"Ed25519",
")",
"AddKey",
"(",
"role",
"data",
".",
"RoleName",
",",
"gun",
"data",
".",
"GUN",
",",
"k",
"data",
".",
"PrivateKey",
")",
"error",
"{",
"e",
".",
"addKey",
"(",
"role",
",",
"k",
")",
"\n",
"return",
"nil",
... | // AddKey allows you to add a private key | [
"AddKey",
"allows",
"you",
"to",
"add",
"a",
"private",
"key"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L31-L34 | train |
theupdateframework/notary | tuf/signed/ed25519.go | addKey | func (e *Ed25519) addKey(role data.RoleName, k data.PrivateKey) {
e.keys[k.ID()] = edCryptoKey{
role: role,
privKey: k,
}
} | go | func (e *Ed25519) addKey(role data.RoleName, k data.PrivateKey) {
e.keys[k.ID()] = edCryptoKey{
role: role,
privKey: k,
}
} | [
"func",
"(",
"e",
"*",
"Ed25519",
")",
"addKey",
"(",
"role",
"data",
".",
"RoleName",
",",
"k",
"data",
".",
"PrivateKey",
")",
"{",
"e",
".",
"keys",
"[",
"k",
".",
"ID",
"(",
")",
"]",
"=",
"edCryptoKey",
"{",
"role",
":",
"role",
",",
"priv... | // addKey allows you to add a private key | [
"addKey",
"allows",
"you",
"to",
"add",
"a",
"private",
"key"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L37-L42 | train |
theupdateframework/notary | tuf/signed/ed25519.go | RemoveKey | func (e *Ed25519) RemoveKey(keyID string) error {
delete(e.keys, keyID)
return nil
} | go | func (e *Ed25519) RemoveKey(keyID string) error {
delete(e.keys, keyID)
return nil
} | [
"func",
"(",
"e",
"*",
"Ed25519",
")",
"RemoveKey",
"(",
"keyID",
"string",
")",
"error",
"{",
"delete",
"(",
"e",
".",
"keys",
",",
"keyID",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // RemoveKey deletes a key from the signer | [
"RemoveKey",
"deletes",
"a",
"key",
"from",
"the",
"signer"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L45-L48 | train |
theupdateframework/notary | tuf/signed/ed25519.go | ListKeys | func (e *Ed25519) ListKeys(role data.RoleName) []string {
keyIDs := make([]string, 0, len(e.keys))
for id, edCryptoKey := range e.keys {
if edCryptoKey.role == role {
keyIDs = append(keyIDs, id)
}
}
return keyIDs
} | go | func (e *Ed25519) ListKeys(role data.RoleName) []string {
keyIDs := make([]string, 0, len(e.keys))
for id, edCryptoKey := range e.keys {
if edCryptoKey.role == role {
keyIDs = append(keyIDs, id)
}
}
return keyIDs
} | [
"func",
"(",
"e",
"*",
"Ed25519",
")",
"ListKeys",
"(",
"role",
"data",
".",
"RoleName",
")",
"[",
"]",
"string",
"{",
"keyIDs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"e",
".",
"keys",
")",
")",
"\n",
"for",
"id",
... | // ListKeys returns the list of keys IDs for the role | [
"ListKeys",
"returns",
"the",
"list",
"of",
"keys",
"IDs",
"for",
"the",
"role"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L51-L59 | train |
theupdateframework/notary | tuf/signed/ed25519.go | ListAllKeys | func (e *Ed25519) ListAllKeys() map[string]data.RoleName {
keys := make(map[string]data.RoleName)
for id, edKey := range e.keys {
keys[id] = edKey.role
}
return keys
} | go | func (e *Ed25519) ListAllKeys() map[string]data.RoleName {
keys := make(map[string]data.RoleName)
for id, edKey := range e.keys {
keys[id] = edKey.role
}
return keys
} | [
"func",
"(",
"e",
"*",
"Ed25519",
")",
"ListAllKeys",
"(",
")",
"map",
"[",
"string",
"]",
"data",
".",
"RoleName",
"{",
"keys",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"data",
".",
"RoleName",
")",
"\n",
"for",
"id",
",",
"edKey",
":=",
"r... | // ListAllKeys returns the map of keys IDs to role | [
"ListAllKeys",
"returns",
"the",
"map",
"of",
"keys",
"IDs",
"to",
"role"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L62-L68 | train |
theupdateframework/notary | tuf/signed/ed25519.go | Create | func (e *Ed25519) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) {
if algorithm != data.ED25519Key {
return nil, errors.New("only ED25519 supported by this cryptoservice")
}
private, err := utils.GenerateED25519Key(rand.Reader)
if err != nil {
return nil, err
}
e.addKey(role, private)
return data.PublicKeyFromPrivate(private), nil
} | go | func (e *Ed25519) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) {
if algorithm != data.ED25519Key {
return nil, errors.New("only ED25519 supported by this cryptoservice")
}
private, err := utils.GenerateED25519Key(rand.Reader)
if err != nil {
return nil, err
}
e.addKey(role, private)
return data.PublicKeyFromPrivate(private), nil
} | [
"func",
"(",
"e",
"*",
"Ed25519",
")",
"Create",
"(",
"role",
"data",
".",
"RoleName",
",",
"gun",
"data",
".",
"GUN",
",",
"algorithm",
"string",
")",
"(",
"data",
".",
"PublicKey",
",",
"error",
")",
"{",
"if",
"algorithm",
"!=",
"data",
".",
"ED... | // Create generates a new key and returns the public part | [
"Create",
"generates",
"a",
"new",
"key",
"and",
"returns",
"the",
"public",
"part"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L71-L83 | train |
theupdateframework/notary | tuf/signed/ed25519.go | PublicKeys | func (e *Ed25519) PublicKeys(keyIDs ...string) (map[string]data.PublicKey, error) {
k := make(map[string]data.PublicKey)
for _, keyID := range keyIDs {
if edKey, ok := e.keys[keyID]; ok {
k[keyID] = data.PublicKeyFromPrivate(edKey.privKey)
}
}
return k, nil
} | go | func (e *Ed25519) PublicKeys(keyIDs ...string) (map[string]data.PublicKey, error) {
k := make(map[string]data.PublicKey)
for _, keyID := range keyIDs {
if edKey, ok := e.keys[keyID]; ok {
k[keyID] = data.PublicKeyFromPrivate(edKey.privKey)
}
}
return k, nil
} | [
"func",
"(",
"e",
"*",
"Ed25519",
")",
"PublicKeys",
"(",
"keyIDs",
"...",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"data",
".",
"PublicKey",
",",
"error",
")",
"{",
"k",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"data",
".",
"PublicKey",... | // PublicKeys returns a map of public keys for the ids provided, when those IDs are found
// in the store. | [
"PublicKeys",
"returns",
"a",
"map",
"of",
"public",
"keys",
"for",
"the",
"ids",
"provided",
"when",
"those",
"IDs",
"are",
"found",
"in",
"the",
"store",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L87-L95 | train |
theupdateframework/notary | tuf/signed/ed25519.go | GetKey | func (e *Ed25519) GetKey(keyID string) data.PublicKey {
if privKey, _, err := e.GetPrivateKey(keyID); err == nil {
return data.PublicKeyFromPrivate(privKey)
}
return nil
} | go | func (e *Ed25519) GetKey(keyID string) data.PublicKey {
if privKey, _, err := e.GetPrivateKey(keyID); err == nil {
return data.PublicKeyFromPrivate(privKey)
}
return nil
} | [
"func",
"(",
"e",
"*",
"Ed25519",
")",
"GetKey",
"(",
"keyID",
"string",
")",
"data",
".",
"PublicKey",
"{",
"if",
"privKey",
",",
"_",
",",
"err",
":=",
"e",
".",
"GetPrivateKey",
"(",
"keyID",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"data",
... | // GetKey returns a single public key based on the ID | [
"GetKey",
"returns",
"a",
"single",
"public",
"key",
"based",
"on",
"the",
"ID"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L98-L103 | train |
theupdateframework/notary | tuf/signed/ed25519.go | GetPrivateKey | func (e *Ed25519) GetPrivateKey(keyID string) (data.PrivateKey, data.RoleName, error) {
if k, ok := e.keys[keyID]; ok {
return k.privKey, k.role, nil
}
return nil, "", trustmanager.ErrKeyNotFound{KeyID: keyID}
} | go | func (e *Ed25519) GetPrivateKey(keyID string) (data.PrivateKey, data.RoleName, error) {
if k, ok := e.keys[keyID]; ok {
return k.privKey, k.role, nil
}
return nil, "", trustmanager.ErrKeyNotFound{KeyID: keyID}
} | [
"func",
"(",
"e",
"*",
"Ed25519",
")",
"GetPrivateKey",
"(",
"keyID",
"string",
")",
"(",
"data",
".",
"PrivateKey",
",",
"data",
".",
"RoleName",
",",
"error",
")",
"{",
"if",
"k",
",",
"ok",
":=",
"e",
".",
"keys",
"[",
"keyID",
"]",
";",
"ok",... | // GetPrivateKey returns a single private key and role if present, based on the ID | [
"GetPrivateKey",
"returns",
"a",
"single",
"private",
"key",
"and",
"role",
"if",
"present",
"based",
"on",
"the",
"ID"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/signed/ed25519.go#L106-L111 | train |
theupdateframework/notary | tuf/utils/stack.go | Push | func (s *Stack) Push(item interface{}) {
s.l.Lock()
defer s.l.Unlock()
s.s = append(s.s, item)
} | go | func (s *Stack) Push(item interface{}) {
s.l.Lock()
defer s.l.Unlock()
s.s = append(s.s, item)
} | [
"func",
"(",
"s",
"*",
"Stack",
")",
"Push",
"(",
"item",
"interface",
"{",
"}",
")",
"{",
"s",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"s",
"=",
"append",
"(",
"s",
".",
"s"... | // Push adds an item to the top of the stack. | [
"Push",
"adds",
"an",
"item",
"to",
"the",
"top",
"of",
"the",
"stack",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/stack.go#L41-L45 | train |
theupdateframework/notary | tuf/utils/stack.go | Pop | func (s *Stack) Pop() (interface{}, error) {
s.l.Lock()
defer s.l.Unlock()
l := len(s.s)
if l > 0 {
item := s.s[l-1]
s.s = s.s[:l-1]
return item, nil
}
return nil, ErrEmptyStack{action: "Pop"}
} | go | func (s *Stack) Pop() (interface{}, error) {
s.l.Lock()
defer s.l.Unlock()
l := len(s.s)
if l > 0 {
item := s.s[l-1]
s.s = s.s[:l-1]
return item, nil
}
return nil, ErrEmptyStack{action: "Pop"}
} | [
"func",
"(",
"s",
"*",
"Stack",
")",
"Pop",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"s",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"l",
":=",
"len",
"(",
"s",
".",
... | // Pop removes and returns the top item on the stack, or returns
// ErrEmptyStack if the stack has no content | [
"Pop",
"removes",
"and",
"returns",
"the",
"top",
"item",
"on",
"the",
"stack",
"or",
"returns",
"ErrEmptyStack",
"if",
"the",
"stack",
"has",
"no",
"content"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/stack.go#L49-L59 | train |
theupdateframework/notary | tuf/utils/stack.go | PopString | func (s *Stack) PopString() (string, error) {
s.l.Lock()
defer s.l.Unlock()
l := len(s.s)
if l > 0 {
item := s.s[l-1]
if item, ok := item.(string); ok {
s.s = s.s[:l-1]
return item, nil
}
return "", ErrBadTypeCast{}
}
return "", ErrEmptyStack{action: "PopString"}
} | go | func (s *Stack) PopString() (string, error) {
s.l.Lock()
defer s.l.Unlock()
l := len(s.s)
if l > 0 {
item := s.s[l-1]
if item, ok := item.(string); ok {
s.s = s.s[:l-1]
return item, nil
}
return "", ErrBadTypeCast{}
}
return "", ErrEmptyStack{action: "PopString"}
} | [
"func",
"(",
"s",
"*",
"Stack",
")",
"PopString",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"l",
":=",
"len",
"(",
"s",
".",
"s",
")... | // PopString attempts to cast the top item on the stack to the string type.
// If this succeeds, it removes and returns the top item. If the item
// is not of the string type, ErrBadTypeCast is returned. If the stack
// is empty, ErrEmptyStack is returned | [
"PopString",
"attempts",
"to",
"cast",
"the",
"top",
"item",
"on",
"the",
"stack",
"to",
"the",
"string",
"type",
".",
"If",
"this",
"succeeds",
"it",
"removes",
"and",
"returns",
"the",
"top",
"item",
".",
"If",
"the",
"item",
"is",
"not",
"of",
"the"... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/stack.go#L65-L78 | train |
theupdateframework/notary | tuf/utils/stack.go | Empty | func (s *Stack) Empty() bool {
s.l.Lock()
defer s.l.Unlock()
return len(s.s) == 0
} | go | func (s *Stack) Empty() bool {
s.l.Lock()
defer s.l.Unlock()
return len(s.s) == 0
} | [
"func",
"(",
"s",
"*",
"Stack",
")",
"Empty",
"(",
")",
"bool",
"{",
"s",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"return",
"len",
"(",
"s",
".",
"s",
")",
"==",
"0",
"\n",
"}"
] | // Empty returns true if the stack is empty | [
"Empty",
"returns",
"true",
"if",
"the",
"stack",
"is",
"empty"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/stack.go#L81-L85 | train |
theupdateframework/notary | trustmanager/keys.go | ExportKeysByGUN | func ExportKeysByGUN(to io.Writer, s Exporter, gun string) error {
keys := s.ListFiles()
sort.Strings(keys) // ensure consistency. ListFiles has no order guarantee
for _, loc := range keys {
keyFile, err := s.Get(loc)
if err != nil {
logrus.Warn("Could not parse key file at ", loc)
continue
}
block, _ := pem.Decode(keyFile)
keyGun := block.Headers["gun"]
if keyGun == gun { // must be full GUN match
if err := ExportKeys(to, s, loc); err != nil {
return err
}
}
}
return nil
} | go | func ExportKeysByGUN(to io.Writer, s Exporter, gun string) error {
keys := s.ListFiles()
sort.Strings(keys) // ensure consistency. ListFiles has no order guarantee
for _, loc := range keys {
keyFile, err := s.Get(loc)
if err != nil {
logrus.Warn("Could not parse key file at ", loc)
continue
}
block, _ := pem.Decode(keyFile)
keyGun := block.Headers["gun"]
if keyGun == gun { // must be full GUN match
if err := ExportKeys(to, s, loc); err != nil {
return err
}
}
}
return nil
} | [
"func",
"ExportKeysByGUN",
"(",
"to",
"io",
".",
"Writer",
",",
"s",
"Exporter",
",",
"gun",
"string",
")",
"error",
"{",
"keys",
":=",
"s",
".",
"ListFiles",
"(",
")",
"\n",
"sort",
".",
"Strings",
"(",
"keys",
")",
"\n",
"for",
"_",
",",
"loc",
... | // ExportKeysByGUN exports all keys filtered to a GUN | [
"ExportKeysByGUN",
"exports",
"all",
"keys",
"filtered",
"to",
"a",
"GUN"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keys.go#L31-L49 | train |
theupdateframework/notary | trustmanager/keys.go | ExportKeysByID | func ExportKeysByID(to io.Writer, s Exporter, ids []string) error {
want := make(map[string]struct{})
for _, id := range ids {
want[id] = struct{}{}
}
keys := s.ListFiles()
for _, k := range keys {
id := filepath.Base(k)
if _, ok := want[id]; ok {
if err := ExportKeys(to, s, k); err != nil {
return err
}
}
}
return nil
} | go | func ExportKeysByID(to io.Writer, s Exporter, ids []string) error {
want := make(map[string]struct{})
for _, id := range ids {
want[id] = struct{}{}
}
keys := s.ListFiles()
for _, k := range keys {
id := filepath.Base(k)
if _, ok := want[id]; ok {
if err := ExportKeys(to, s, k); err != nil {
return err
}
}
}
return nil
} | [
"func",
"ExportKeysByID",
"(",
"to",
"io",
".",
"Writer",
",",
"s",
"Exporter",
",",
"ids",
"[",
"]",
"string",
")",
"error",
"{",
"want",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"id",
":=",
... | // ExportKeysByID exports all keys matching the given ID | [
"ExportKeysByID",
"exports",
"all",
"keys",
"matching",
"the",
"given",
"ID"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keys.go#L52-L67 | train |
theupdateframework/notary | trustmanager/keys.go | ExportKeys | func ExportKeys(to io.Writer, s Exporter, from string) error {
// get PEM block
k, err := s.Get(from)
if err != nil {
return err
}
// parse PEM blocks if there are more than one
for block, rest := pem.Decode(k); block != nil; block, rest = pem.Decode(rest) {
// add from path in a header for later import
block.Headers["path"] = from
// write serialized PEM
err = pem.Encode(to, block)
if err != nil {
return err
}
}
return nil
} | go | func ExportKeys(to io.Writer, s Exporter, from string) error {
// get PEM block
k, err := s.Get(from)
if err != nil {
return err
}
// parse PEM blocks if there are more than one
for block, rest := pem.Decode(k); block != nil; block, rest = pem.Decode(rest) {
// add from path in a header for later import
block.Headers["path"] = from
// write serialized PEM
err = pem.Encode(to, block)
if err != nil {
return err
}
}
return nil
} | [
"func",
"ExportKeys",
"(",
"to",
"io",
".",
"Writer",
",",
"s",
"Exporter",
",",
"from",
"string",
")",
"error",
"{",
"k",
",",
"err",
":=",
"s",
".",
"Get",
"(",
"from",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n... | // ExportKeys copies a key from the store to the io.Writer | [
"ExportKeys",
"copies",
"a",
"key",
"from",
"the",
"store",
"to",
"the",
"io",
".",
"Writer"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keys.go#L70-L88 | train |
theupdateframework/notary | trustmanager/keys.go | ImportKeys | func ImportKeys(from io.Reader, to []Importer, fallbackRole string, fallbackGUN string, passRet notary.PassRetriever) error {
// importLogic.md contains a small flowchart I made to clear up my understand while writing the cases in this function
// it is very rough, but it may help while reading this piece of code
data, err := ioutil.ReadAll(from)
if err != nil {
return err
}
var (
writeTo string
toWrite []byte
errBlocks []string
)
for block, rest := pem.Decode(data); block != nil; block, rest = pem.Decode(rest) {
handleLegacyPath(block)
setFallbacks(block, fallbackGUN, fallbackRole)
loc, err := checkValidity(block)
if err != nil {
// already logged in checkValidity
errBlocks = append(errBlocks, err.Error())
continue
}
// the path header is not of any use once we've imported the key so strip it away
delete(block.Headers, "path")
// we are now all set for import but let's first encrypt the key
blockBytes := pem.EncodeToMemory(block)
// check if key is encrypted, note: if it is encrypted at this point, it will have had a path header
if privKey, err := utils.ParsePEMPrivateKey(blockBytes, ""); err == nil {
// Key is not encrypted- ask for a passphrase and encrypt this key
var chosenPassphrase string
for attempts := 0; ; attempts++ {
var giveup bool
chosenPassphrase, giveup, err = passRet(loc, block.Headers["role"], true, attempts)
if err == nil {
break
}
if giveup || attempts > 10 {
return errors.New("maximum number of passphrase attempts exceeded")
}
}
blockBytes, err = utils.ConvertPrivateKeyToPKCS8(privKey, tufdata.RoleName(block.Headers["role"]), tufdata.GUN(block.Headers["gun"]), chosenPassphrase)
if err != nil {
return errors.New("failed to encrypt key with given passphrase")
}
}
if loc != writeTo {
// next location is different from previous one. We've finished aggregating
// data for the previous file. If we have data, write the previous file,
// clear toWrite and set writeTo to the next path we're going to write
if toWrite != nil {
if err = importToStores(to, writeTo, toWrite); err != nil {
return err
}
}
// set up for aggregating next file's data
toWrite = nil
writeTo = loc
}
toWrite = append(toWrite, blockBytes...)
}
if toWrite != nil { // close out final iteration if there's data left
return importToStores(to, writeTo, toWrite)
}
if len(errBlocks) > 0 {
return fmt.Errorf("failed to import all keys: %s", strings.Join(errBlocks, ", "))
}
return nil
} | go | func ImportKeys(from io.Reader, to []Importer, fallbackRole string, fallbackGUN string, passRet notary.PassRetriever) error {
// importLogic.md contains a small flowchart I made to clear up my understand while writing the cases in this function
// it is very rough, but it may help while reading this piece of code
data, err := ioutil.ReadAll(from)
if err != nil {
return err
}
var (
writeTo string
toWrite []byte
errBlocks []string
)
for block, rest := pem.Decode(data); block != nil; block, rest = pem.Decode(rest) {
handleLegacyPath(block)
setFallbacks(block, fallbackGUN, fallbackRole)
loc, err := checkValidity(block)
if err != nil {
// already logged in checkValidity
errBlocks = append(errBlocks, err.Error())
continue
}
// the path header is not of any use once we've imported the key so strip it away
delete(block.Headers, "path")
// we are now all set for import but let's first encrypt the key
blockBytes := pem.EncodeToMemory(block)
// check if key is encrypted, note: if it is encrypted at this point, it will have had a path header
if privKey, err := utils.ParsePEMPrivateKey(blockBytes, ""); err == nil {
// Key is not encrypted- ask for a passphrase and encrypt this key
var chosenPassphrase string
for attempts := 0; ; attempts++ {
var giveup bool
chosenPassphrase, giveup, err = passRet(loc, block.Headers["role"], true, attempts)
if err == nil {
break
}
if giveup || attempts > 10 {
return errors.New("maximum number of passphrase attempts exceeded")
}
}
blockBytes, err = utils.ConvertPrivateKeyToPKCS8(privKey, tufdata.RoleName(block.Headers["role"]), tufdata.GUN(block.Headers["gun"]), chosenPassphrase)
if err != nil {
return errors.New("failed to encrypt key with given passphrase")
}
}
if loc != writeTo {
// next location is different from previous one. We've finished aggregating
// data for the previous file. If we have data, write the previous file,
// clear toWrite and set writeTo to the next path we're going to write
if toWrite != nil {
if err = importToStores(to, writeTo, toWrite); err != nil {
return err
}
}
// set up for aggregating next file's data
toWrite = nil
writeTo = loc
}
toWrite = append(toWrite, blockBytes...)
}
if toWrite != nil { // close out final iteration if there's data left
return importToStores(to, writeTo, toWrite)
}
if len(errBlocks) > 0 {
return fmt.Errorf("failed to import all keys: %s", strings.Join(errBlocks, ", "))
}
return nil
} | [
"func",
"ImportKeys",
"(",
"from",
"io",
".",
"Reader",
",",
"to",
"[",
"]",
"Importer",
",",
"fallbackRole",
"string",
",",
"fallbackGUN",
"string",
",",
"passRet",
"notary",
".",
"PassRetriever",
")",
"error",
"{",
"data",
",",
"err",
":=",
"ioutil",
"... | // ImportKeys expects an io.Reader containing one or more PEM blocks.
// It reads PEM blocks one at a time until pem.Decode returns a nil
// block.
// Each block is written to the subpath indicated in the "path" PEM
// header. If the file already exists, the file is truncated. Multiple
// adjacent PEMs with the same "path" header are appended together. | [
"ImportKeys",
"expects",
"an",
"io",
".",
"Reader",
"containing",
"one",
"or",
"more",
"PEM",
"blocks",
".",
"It",
"reads",
"PEM",
"blocks",
"one",
"at",
"a",
"time",
"until",
"pem",
".",
"Decode",
"returns",
"a",
"nil",
"block",
".",
"Each",
"block",
... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keys.go#L96-L167 | train |
theupdateframework/notary | trustmanager/keys.go | checkValidity | func checkValidity(block *pem.Block) (string, error) {
// A root key or a delegations key should not have a gun
// Note that a key that is not any of the canonical roles (except root) is a delegations key and should not have a gun
switch block.Headers["role"] {
case tufdata.CanonicalSnapshotRole.String(), tufdata.CanonicalTargetsRole.String(), tufdata.CanonicalTimestampRole.String():
// check if the key is missing a gun header or has an empty gun and error out since we don't know what gun it belongs to
if block.Headers["gun"] == "" {
logrus.Warnf("failed to import key (%s) to store: Cannot have canonical role key without a gun, don't know what gun it belongs to", block.Headers["path"])
return "", errors.New("invalid key pem block")
}
default:
delete(block.Headers, "gun")
}
loc, ok := block.Headers["path"]
// only if the path isn't specified do we get into this parsing path logic
if !ok || loc == "" {
// if the path isn't specified, we will try to infer the path rel to trust dir from the role (and then gun)
// parse key for the keyID which we will save it by.
// if the key is encrypted at this point, we will generate an error and continue since we don't know the ID to save it by
decodedKey, err := utils.ParsePEMPrivateKey(pem.EncodeToMemory(block), "")
if err != nil {
logrus.Warn("failed to import key to store: Invalid key generated, key may be encrypted and does not contain path header")
return "", errors.New("invalid key pem block")
}
loc = decodedKey.ID()
}
return loc, nil
} | go | func checkValidity(block *pem.Block) (string, error) {
// A root key or a delegations key should not have a gun
// Note that a key that is not any of the canonical roles (except root) is a delegations key and should not have a gun
switch block.Headers["role"] {
case tufdata.CanonicalSnapshotRole.String(), tufdata.CanonicalTargetsRole.String(), tufdata.CanonicalTimestampRole.String():
// check if the key is missing a gun header or has an empty gun and error out since we don't know what gun it belongs to
if block.Headers["gun"] == "" {
logrus.Warnf("failed to import key (%s) to store: Cannot have canonical role key without a gun, don't know what gun it belongs to", block.Headers["path"])
return "", errors.New("invalid key pem block")
}
default:
delete(block.Headers, "gun")
}
loc, ok := block.Headers["path"]
// only if the path isn't specified do we get into this parsing path logic
if !ok || loc == "" {
// if the path isn't specified, we will try to infer the path rel to trust dir from the role (and then gun)
// parse key for the keyID which we will save it by.
// if the key is encrypted at this point, we will generate an error and continue since we don't know the ID to save it by
decodedKey, err := utils.ParsePEMPrivateKey(pem.EncodeToMemory(block), "")
if err != nil {
logrus.Warn("failed to import key to store: Invalid key generated, key may be encrypted and does not contain path header")
return "", errors.New("invalid key pem block")
}
loc = decodedKey.ID()
}
return loc, nil
} | [
"func",
"checkValidity",
"(",
"block",
"*",
"pem",
".",
"Block",
")",
"(",
"string",
",",
"error",
")",
"{",
"switch",
"block",
".",
"Headers",
"[",
"\"role\"",
"]",
"{",
"case",
"tufdata",
".",
"CanonicalSnapshotRole",
".",
"String",
"(",
")",
",",
"t... | // checkValidity ensures the fields in the pem headers are valid and parses out the location.
// While importing a collection of keys, errors from this function should result in only the
// current pem block being skipped. | [
"checkValidity",
"ensures",
"the",
"fields",
"in",
"the",
"pem",
"headers",
"are",
"valid",
"and",
"parses",
"out",
"the",
"location",
".",
"While",
"importing",
"a",
"collection",
"of",
"keys",
"errors",
"from",
"this",
"function",
"should",
"result",
"in",
... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keys.go#L205-L234 | train |
theupdateframework/notary | server/timestamp/timestamp.go | GetOrCreateTimestamp | func GetOrCreateTimestamp(gun data.GUN, store storage.MetaStore, cryptoService signed.CryptoService) (
*time.Time, []byte, error) {
updates := []storage.MetaUpdate{}
lastModified, timestampJSON, err := store.GetCurrent(gun, data.CanonicalTimestampRole)
if err != nil {
logrus.Debug("error retrieving timestamp: ", err.Error())
return nil, nil, err
}
prev := &data.SignedTimestamp{}
if err := json.Unmarshal(timestampJSON, prev); err != nil {
logrus.Error("Failed to unmarshal existing timestamp")
return nil, nil, err
}
snapChecksums, err := prev.GetSnapshot()
if err != nil || snapChecksums == nil {
return nil, nil, err
}
snapshotSHA256Bytes, ok := snapChecksums.Hashes[notary.SHA256]
if !ok {
return nil, nil, data.ErrMissingMeta{Role: data.CanonicalSnapshotRole.String()}
}
snapshotSHA256Hex := hex.EncodeToString(snapshotSHA256Bytes[:])
snapshotTime, snapshot, err := snapshot.GetOrCreateSnapshot(gun, snapshotSHA256Hex, store, cryptoService)
if err != nil {
logrus.Debug("Previous timestamp, but no valid snapshot for GUN ", gun)
return nil, nil, err
}
snapshotRole := &data.SignedSnapshot{}
if err := json.Unmarshal(snapshot, snapshotRole); err != nil {
logrus.Error("Failed to unmarshal retrieved snapshot")
return nil, nil, err
}
// If the snapshot was generated, we should write it with the timestamp
if snapshotTime == nil {
updates = append(updates, storage.MetaUpdate{Role: data.CanonicalSnapshotRole, Version: snapshotRole.Signed.Version, Data: snapshot})
}
if !timestampExpired(prev) && !snapshotExpired(prev, snapshot) {
return lastModified, timestampJSON, nil
}
tsUpdate, err := createTimestamp(gun, prev, snapshot, store, cryptoService)
if err != nil {
logrus.Error("Failed to create a new timestamp")
return nil, nil, err
}
updates = append(updates, *tsUpdate)
c := time.Now()
// Write the timestamp, and potentially snapshot
if err = store.UpdateMany(gun, updates); err != nil {
return nil, nil, err
}
return &c, tsUpdate.Data, nil
} | go | func GetOrCreateTimestamp(gun data.GUN, store storage.MetaStore, cryptoService signed.CryptoService) (
*time.Time, []byte, error) {
updates := []storage.MetaUpdate{}
lastModified, timestampJSON, err := store.GetCurrent(gun, data.CanonicalTimestampRole)
if err != nil {
logrus.Debug("error retrieving timestamp: ", err.Error())
return nil, nil, err
}
prev := &data.SignedTimestamp{}
if err := json.Unmarshal(timestampJSON, prev); err != nil {
logrus.Error("Failed to unmarshal existing timestamp")
return nil, nil, err
}
snapChecksums, err := prev.GetSnapshot()
if err != nil || snapChecksums == nil {
return nil, nil, err
}
snapshotSHA256Bytes, ok := snapChecksums.Hashes[notary.SHA256]
if !ok {
return nil, nil, data.ErrMissingMeta{Role: data.CanonicalSnapshotRole.String()}
}
snapshotSHA256Hex := hex.EncodeToString(snapshotSHA256Bytes[:])
snapshotTime, snapshot, err := snapshot.GetOrCreateSnapshot(gun, snapshotSHA256Hex, store, cryptoService)
if err != nil {
logrus.Debug("Previous timestamp, but no valid snapshot for GUN ", gun)
return nil, nil, err
}
snapshotRole := &data.SignedSnapshot{}
if err := json.Unmarshal(snapshot, snapshotRole); err != nil {
logrus.Error("Failed to unmarshal retrieved snapshot")
return nil, nil, err
}
// If the snapshot was generated, we should write it with the timestamp
if snapshotTime == nil {
updates = append(updates, storage.MetaUpdate{Role: data.CanonicalSnapshotRole, Version: snapshotRole.Signed.Version, Data: snapshot})
}
if !timestampExpired(prev) && !snapshotExpired(prev, snapshot) {
return lastModified, timestampJSON, nil
}
tsUpdate, err := createTimestamp(gun, prev, snapshot, store, cryptoService)
if err != nil {
logrus.Error("Failed to create a new timestamp")
return nil, nil, err
}
updates = append(updates, *tsUpdate)
c := time.Now()
// Write the timestamp, and potentially snapshot
if err = store.UpdateMany(gun, updates); err != nil {
return nil, nil, err
}
return &c, tsUpdate.Data, nil
} | [
"func",
"GetOrCreateTimestamp",
"(",
"gun",
"data",
".",
"GUN",
",",
"store",
"storage",
".",
"MetaStore",
",",
"cryptoService",
"signed",
".",
"CryptoService",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"updates",... | // GetOrCreateTimestamp returns the current timestamp for the gun. This may mean
// a new timestamp is generated either because none exists, or because the current
// one has expired. Once generated, the timestamp is saved in the store.
// Additionally, if we had to generate a new snapshot for this timestamp,
// it is also saved in the store | [
"GetOrCreateTimestamp",
"returns",
"the",
"current",
"timestamp",
"for",
"the",
"gun",
".",
"This",
"may",
"mean",
"a",
"new",
"timestamp",
"is",
"generated",
"either",
"because",
"none",
"exists",
"or",
"because",
"the",
"current",
"one",
"has",
"expired",
".... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/timestamp/timestamp.go#L74-L133 | train |
theupdateframework/notary | server/timestamp/timestamp.go | timestampExpired | func timestampExpired(ts *data.SignedTimestamp) bool {
return signed.IsExpired(ts.Signed.Expires)
} | go | func timestampExpired(ts *data.SignedTimestamp) bool {
return signed.IsExpired(ts.Signed.Expires)
} | [
"func",
"timestampExpired",
"(",
"ts",
"*",
"data",
".",
"SignedTimestamp",
")",
"bool",
"{",
"return",
"signed",
".",
"IsExpired",
"(",
"ts",
".",
"Signed",
".",
"Expires",
")",
"\n",
"}"
] | // timestampExpired compares the current time to the expiry time of the timestamp | [
"timestampExpired",
"compares",
"the",
"current",
"time",
"to",
"the",
"expiry",
"time",
"of",
"the",
"timestamp"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/timestamp/timestamp.go#L136-L138 | train |
theupdateframework/notary | server/timestamp/timestamp.go | createTimestamp | func createTimestamp(gun data.GUN, prev *data.SignedTimestamp, snapshot []byte, store storage.MetaStore,
cryptoService signed.CryptoService) (*storage.MetaUpdate, error) {
builder := tuf.NewRepoBuilder(gun, cryptoService, trustpinning.TrustPinConfig{})
// load the current root to ensure we use the correct timestamp key.
_, root, err := store.GetCurrent(gun, data.CanonicalRootRole)
if err != nil {
logrus.Debug("Previous timestamp, but no root for GUN ", gun)
return nil, err
}
if err := builder.Load(data.CanonicalRootRole, root, 1, false); err != nil {
logrus.Debug("Could not load valid previous root for GUN ", gun)
return nil, err
}
// load snapshot so we can include it in timestamp
if err := builder.Load(data.CanonicalSnapshotRole, snapshot, 1, false); err != nil {
logrus.Debug("Could not load valid previous snapshot for GUN ", gun)
return nil, err
}
meta, ver, err := builder.GenerateTimestamp(prev)
if err != nil {
return nil, err
}
return &storage.MetaUpdate{
Role: data.CanonicalTimestampRole,
Version: ver,
Data: meta,
}, nil
} | go | func createTimestamp(gun data.GUN, prev *data.SignedTimestamp, snapshot []byte, store storage.MetaStore,
cryptoService signed.CryptoService) (*storage.MetaUpdate, error) {
builder := tuf.NewRepoBuilder(gun, cryptoService, trustpinning.TrustPinConfig{})
// load the current root to ensure we use the correct timestamp key.
_, root, err := store.GetCurrent(gun, data.CanonicalRootRole)
if err != nil {
logrus.Debug("Previous timestamp, but no root for GUN ", gun)
return nil, err
}
if err := builder.Load(data.CanonicalRootRole, root, 1, false); err != nil {
logrus.Debug("Could not load valid previous root for GUN ", gun)
return nil, err
}
// load snapshot so we can include it in timestamp
if err := builder.Load(data.CanonicalSnapshotRole, snapshot, 1, false); err != nil {
logrus.Debug("Could not load valid previous snapshot for GUN ", gun)
return nil, err
}
meta, ver, err := builder.GenerateTimestamp(prev)
if err != nil {
return nil, err
}
return &storage.MetaUpdate{
Role: data.CanonicalTimestampRole,
Version: ver,
Data: meta,
}, nil
} | [
"func",
"createTimestamp",
"(",
"gun",
"data",
".",
"GUN",
",",
"prev",
"*",
"data",
".",
"SignedTimestamp",
",",
"snapshot",
"[",
"]",
"byte",
",",
"store",
"storage",
".",
"MetaStore",
",",
"cryptoService",
"signed",
".",
"CryptoService",
")",
"(",
"*",
... | // CreateTimestamp creates a new timestamp. If a prev timestamp is provided, it
// is assumed this is the immediately previous one, and the new one will have a
// version number one higher than prev. The store is used to lookup the current
// snapshot, this function does not save the newly generated timestamp. | [
"CreateTimestamp",
"creates",
"a",
"new",
"timestamp",
".",
"If",
"a",
"prev",
"timestamp",
"is",
"provided",
"it",
"is",
"assumed",
"this",
"is",
"the",
"immediately",
"previous",
"one",
"and",
"the",
"new",
"one",
"will",
"have",
"a",
"version",
"number",
... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/timestamp/timestamp.go#L152-L183 | train |
theupdateframework/notary | tuf/utils/utils.go | StrSliceContains | func StrSliceContains(ss []string, s string) bool {
for _, v := range ss {
if v == s {
return true
}
}
return false
} | go | func StrSliceContains(ss []string, s string) bool {
for _, v := range ss {
if v == s {
return true
}
}
return false
} | [
"func",
"StrSliceContains",
"(",
"ss",
"[",
"]",
"string",
",",
"s",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"ss",
"{",
"if",
"v",
"==",
"s",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"... | // StrSliceContains checks if the given string appears in the slice | [
"StrSliceContains",
"checks",
"if",
"the",
"given",
"string",
"appears",
"in",
"the",
"slice"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L14-L21 | train |
theupdateframework/notary | tuf/utils/utils.go | RoleNameSliceContains | func RoleNameSliceContains(ss []data.RoleName, s data.RoleName) bool {
for _, v := range ss {
if v == s {
return true
}
}
return false
} | go | func RoleNameSliceContains(ss []data.RoleName, s data.RoleName) bool {
for _, v := range ss {
if v == s {
return true
}
}
return false
} | [
"func",
"RoleNameSliceContains",
"(",
"ss",
"[",
"]",
"data",
".",
"RoleName",
",",
"s",
"data",
".",
"RoleName",
")",
"bool",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"ss",
"{",
"if",
"v",
"==",
"s",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",... | // RoleNameSliceContains checks if the given string appears in the slice | [
"RoleNameSliceContains",
"checks",
"if",
"the",
"given",
"string",
"appears",
"in",
"the",
"slice"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L24-L31 | train |
theupdateframework/notary | tuf/utils/utils.go | RoleNameSliceRemove | func RoleNameSliceRemove(ss []data.RoleName, s data.RoleName) []data.RoleName {
res := []data.RoleName{}
for _, v := range ss {
if v != s {
res = append(res, v)
}
}
return res
} | go | func RoleNameSliceRemove(ss []data.RoleName, s data.RoleName) []data.RoleName {
res := []data.RoleName{}
for _, v := range ss {
if v != s {
res = append(res, v)
}
}
return res
} | [
"func",
"RoleNameSliceRemove",
"(",
"ss",
"[",
"]",
"data",
".",
"RoleName",
",",
"s",
"data",
".",
"RoleName",
")",
"[",
"]",
"data",
".",
"RoleName",
"{",
"res",
":=",
"[",
"]",
"data",
".",
"RoleName",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=... | // RoleNameSliceRemove removes the the given RoleName from the slice, returning a new slice | [
"RoleNameSliceRemove",
"removes",
"the",
"the",
"given",
"RoleName",
"from",
"the",
"slice",
"returning",
"a",
"new",
"slice"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L34-L42 | train |
theupdateframework/notary | tuf/utils/utils.go | DoHash | func DoHash(alg string, d []byte) []byte {
switch alg {
case "sha256":
digest := sha256.Sum256(d)
return digest[:]
case "sha512":
digest := sha512.Sum512(d)
return digest[:]
}
return nil
} | go | func DoHash(alg string, d []byte) []byte {
switch alg {
case "sha256":
digest := sha256.Sum256(d)
return digest[:]
case "sha512":
digest := sha512.Sum512(d)
return digest[:]
}
return nil
} | [
"func",
"DoHash",
"(",
"alg",
"string",
",",
"d",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"switch",
"alg",
"{",
"case",
"\"sha256\"",
":",
"digest",
":=",
"sha256",
".",
"Sum256",
"(",
"d",
")",
"\n",
"return",
"digest",
"[",
":",
"]",
"\n"... | // DoHash returns the digest of d using the hashing algorithm named
// in alg | [
"DoHash",
"returns",
"the",
"digest",
"of",
"d",
"using",
"the",
"hashing",
"algorithm",
"named",
"in",
"alg"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L57-L67 | train |
theupdateframework/notary | tuf/utils/utils.go | UnusedDelegationKeys | func UnusedDelegationKeys(t data.SignedTargets) []string {
// compare ids to all still active key ids in all active roles
// with the targets file
found := make(map[string]bool)
for _, r := range t.Signed.Delegations.Roles {
for _, id := range r.KeyIDs {
found[id] = true
}
}
var discard []string
for id := range t.Signed.Delegations.Keys {
if !found[id] {
discard = append(discard, id)
}
}
return discard
} | go | func UnusedDelegationKeys(t data.SignedTargets) []string {
// compare ids to all still active key ids in all active roles
// with the targets file
found := make(map[string]bool)
for _, r := range t.Signed.Delegations.Roles {
for _, id := range r.KeyIDs {
found[id] = true
}
}
var discard []string
for id := range t.Signed.Delegations.Keys {
if !found[id] {
discard = append(discard, id)
}
}
return discard
} | [
"func",
"UnusedDelegationKeys",
"(",
"t",
"data",
".",
"SignedTargets",
")",
"[",
"]",
"string",
"{",
"found",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"t",
".",
"Signed",
".",
"Delegations... | // UnusedDelegationKeys prunes a list of keys, returning those that are no
// longer in use for a given targets file | [
"UnusedDelegationKeys",
"prunes",
"a",
"list",
"of",
"keys",
"returning",
"those",
"that",
"are",
"no",
"longer",
"in",
"use",
"for",
"a",
"given",
"targets",
"file"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L71-L87 | train |
theupdateframework/notary | tuf/utils/utils.go | RemoveUnusedKeys | func RemoveUnusedKeys(t *data.SignedTargets) {
unusedIDs := UnusedDelegationKeys(*t)
for _, id := range unusedIDs {
delete(t.Signed.Delegations.Keys, id)
}
} | go | func RemoveUnusedKeys(t *data.SignedTargets) {
unusedIDs := UnusedDelegationKeys(*t)
for _, id := range unusedIDs {
delete(t.Signed.Delegations.Keys, id)
}
} | [
"func",
"RemoveUnusedKeys",
"(",
"t",
"*",
"data",
".",
"SignedTargets",
")",
"{",
"unusedIDs",
":=",
"UnusedDelegationKeys",
"(",
"*",
"t",
")",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"unusedIDs",
"{",
"delete",
"(",
"t",
".",
"Signed",
".",
"Del... | // RemoveUnusedKeys determines which keys in the slice of IDs are no longer
// used in the given targets file and removes them from the delegated keys
// map | [
"RemoveUnusedKeys",
"determines",
"which",
"keys",
"in",
"the",
"slice",
"of",
"IDs",
"are",
"no",
"longer",
"used",
"in",
"the",
"given",
"targets",
"file",
"and",
"removes",
"them",
"from",
"the",
"delegated",
"keys",
"map"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L92-L97 | train |
theupdateframework/notary | tuf/utils/utils.go | ConsistentName | func ConsistentName(role string, hashSHA256 []byte) string {
if len(hashSHA256) > 0 {
hash := hex.EncodeToString(hashSHA256)
return fmt.Sprintf("%s.%s", role, hash)
}
return role
} | go | func ConsistentName(role string, hashSHA256 []byte) string {
if len(hashSHA256) > 0 {
hash := hex.EncodeToString(hashSHA256)
return fmt.Sprintf("%s.%s", role, hash)
}
return role
} | [
"func",
"ConsistentName",
"(",
"role",
"string",
",",
"hashSHA256",
"[",
"]",
"byte",
")",
"string",
"{",
"if",
"len",
"(",
"hashSHA256",
")",
">",
"0",
"{",
"hash",
":=",
"hex",
".",
"EncodeToString",
"(",
"hashSHA256",
")",
"\n",
"return",
"fmt",
"."... | // ConsistentName generates the appropriate HTTP URL path for the role,
// based on whether the repo is marked as consistent. The RemoteStore
// is responsible for adding file extensions. | [
"ConsistentName",
"generates",
"the",
"appropriate",
"HTTP",
"URL",
"path",
"for",
"the",
"role",
"based",
"on",
"whether",
"the",
"repo",
"is",
"marked",
"as",
"consistent",
".",
"The",
"RemoteStore",
"is",
"responsible",
"for",
"adding",
"file",
"extensions",
... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/tuf/utils/utils.go#L113-L119 | train |
theupdateframework/notary | trustpinning/trustpin.go | NewTrustPinChecker | func NewTrustPinChecker(trustPinConfig TrustPinConfig, gun data.GUN, firstBootstrap bool) (CertChecker, error) {
t := trustPinChecker{gun: gun, config: trustPinConfig}
// Determine the mode, and if it's even valid
if pinnedCerts, ok := trustPinConfig.Certs[gun.String()]; ok {
logrus.Debugf("trust-pinning using Cert IDs")
t.pinnedCertIDs = pinnedCerts
return t.certsCheck, nil
}
var ok bool
t.pinnedCertIDs, ok = wildcardMatch(gun, trustPinConfig.Certs)
if ok {
return t.certsCheck, nil
}
if caFilepath, err := getPinnedCAFilepathByPrefix(gun, trustPinConfig); err == nil {
logrus.Debugf("trust-pinning using root CA bundle at: %s", caFilepath)
// Try to add the CA certs from its bundle file to our certificate store,
// and use it to validate certs in the root.json later
caCerts, err := utils.LoadCertBundleFromFile(caFilepath)
if err != nil {
return nil, fmt.Errorf("could not load root cert from CA path")
}
// Now only consider certificates that are direct children from this CA cert chain
caRootPool := x509.NewCertPool()
for _, caCert := range caCerts {
if err = utils.ValidateCertificate(caCert, true); err != nil {
logrus.Debugf("ignoring root CA certificate with CN %s in bundle: %s", caCert.Subject.CommonName, err)
continue
}
caRootPool.AddCert(caCert)
}
// If we didn't have any valid CA certs, error out
if len(caRootPool.Subjects()) == 0 {
return nil, fmt.Errorf("invalid CA certs provided")
}
t.pinnedCAPool = caRootPool
return t.caCheck, nil
}
// If TOFUs is disabled and we don't have any previous trusted root data for this GUN, we error out
if trustPinConfig.DisableTOFU && firstBootstrap {
return nil, fmt.Errorf("invalid trust pinning specified")
}
return t.tofusCheck, nil
} | go | func NewTrustPinChecker(trustPinConfig TrustPinConfig, gun data.GUN, firstBootstrap bool) (CertChecker, error) {
t := trustPinChecker{gun: gun, config: trustPinConfig}
// Determine the mode, and if it's even valid
if pinnedCerts, ok := trustPinConfig.Certs[gun.String()]; ok {
logrus.Debugf("trust-pinning using Cert IDs")
t.pinnedCertIDs = pinnedCerts
return t.certsCheck, nil
}
var ok bool
t.pinnedCertIDs, ok = wildcardMatch(gun, trustPinConfig.Certs)
if ok {
return t.certsCheck, nil
}
if caFilepath, err := getPinnedCAFilepathByPrefix(gun, trustPinConfig); err == nil {
logrus.Debugf("trust-pinning using root CA bundle at: %s", caFilepath)
// Try to add the CA certs from its bundle file to our certificate store,
// and use it to validate certs in the root.json later
caCerts, err := utils.LoadCertBundleFromFile(caFilepath)
if err != nil {
return nil, fmt.Errorf("could not load root cert from CA path")
}
// Now only consider certificates that are direct children from this CA cert chain
caRootPool := x509.NewCertPool()
for _, caCert := range caCerts {
if err = utils.ValidateCertificate(caCert, true); err != nil {
logrus.Debugf("ignoring root CA certificate with CN %s in bundle: %s", caCert.Subject.CommonName, err)
continue
}
caRootPool.AddCert(caCert)
}
// If we didn't have any valid CA certs, error out
if len(caRootPool.Subjects()) == 0 {
return nil, fmt.Errorf("invalid CA certs provided")
}
t.pinnedCAPool = caRootPool
return t.caCheck, nil
}
// If TOFUs is disabled and we don't have any previous trusted root data for this GUN, we error out
if trustPinConfig.DisableTOFU && firstBootstrap {
return nil, fmt.Errorf("invalid trust pinning specified")
}
return t.tofusCheck, nil
} | [
"func",
"NewTrustPinChecker",
"(",
"trustPinConfig",
"TrustPinConfig",
",",
"gun",
"data",
".",
"GUN",
",",
"firstBootstrap",
"bool",
")",
"(",
"CertChecker",
",",
"error",
")",
"{",
"t",
":=",
"trustPinChecker",
"{",
"gun",
":",
"gun",
",",
"config",
":",
... | // NewTrustPinChecker returns a new certChecker function from a TrustPinConfig for a GUN | [
"NewTrustPinChecker",
"returns",
"a",
"new",
"certChecker",
"function",
"from",
"a",
"TrustPinConfig",
"for",
"a",
"GUN"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustpinning/trustpin.go#L47-L93 | train |
theupdateframework/notary | server/snapshot/snapshot.go | GetOrCreateSnapshotKey | func GetOrCreateSnapshotKey(gun data.GUN, store storage.MetaStore, crypto signed.CryptoService, createAlgorithm string) (data.PublicKey, error) {
_, rootJSON, err := store.GetCurrent(gun, data.CanonicalRootRole)
if err != nil {
// If the error indicates we couldn't find the root, create a new key
if _, ok := err.(storage.ErrNotFound); !ok {
logrus.Errorf("Error when retrieving root role for GUN %s: %v", gun.String(), err)
return nil, err
}
return crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm)
}
// If we have a current root, parse out the public key for the snapshot role, and return it
repoSignedRoot := new(data.SignedRoot)
if err := json.Unmarshal(rootJSON, repoSignedRoot); err != nil {
logrus.Errorf("Failed to unmarshal existing root for GUN %s to retrieve snapshot key ID", gun)
return nil, err
}
snapshotRole, err := repoSignedRoot.BuildBaseRole(data.CanonicalSnapshotRole)
if err != nil {
logrus.Errorf("Failed to extract snapshot role from root for GUN %s", gun)
return nil, err
}
// We currently only support single keys for snapshot and timestamp, so we can return the first and only key in the map if the signer has it
for keyID := range snapshotRole.Keys {
if pubKey := crypto.GetKey(keyID); pubKey != nil {
return pubKey, nil
}
}
logrus.Debugf("Failed to find any snapshot keys in cryptosigner from root for GUN %s, generating new key", gun)
return crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm)
} | go | func GetOrCreateSnapshotKey(gun data.GUN, store storage.MetaStore, crypto signed.CryptoService, createAlgorithm string) (data.PublicKey, error) {
_, rootJSON, err := store.GetCurrent(gun, data.CanonicalRootRole)
if err != nil {
// If the error indicates we couldn't find the root, create a new key
if _, ok := err.(storage.ErrNotFound); !ok {
logrus.Errorf("Error when retrieving root role for GUN %s: %v", gun.String(), err)
return nil, err
}
return crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm)
}
// If we have a current root, parse out the public key for the snapshot role, and return it
repoSignedRoot := new(data.SignedRoot)
if err := json.Unmarshal(rootJSON, repoSignedRoot); err != nil {
logrus.Errorf("Failed to unmarshal existing root for GUN %s to retrieve snapshot key ID", gun)
return nil, err
}
snapshotRole, err := repoSignedRoot.BuildBaseRole(data.CanonicalSnapshotRole)
if err != nil {
logrus.Errorf("Failed to extract snapshot role from root for GUN %s", gun)
return nil, err
}
// We currently only support single keys for snapshot and timestamp, so we can return the first and only key in the map if the signer has it
for keyID := range snapshotRole.Keys {
if pubKey := crypto.GetKey(keyID); pubKey != nil {
return pubKey, nil
}
}
logrus.Debugf("Failed to find any snapshot keys in cryptosigner from root for GUN %s, generating new key", gun)
return crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm)
} | [
"func",
"GetOrCreateSnapshotKey",
"(",
"gun",
"data",
".",
"GUN",
",",
"store",
"storage",
".",
"MetaStore",
",",
"crypto",
"signed",
".",
"CryptoService",
",",
"createAlgorithm",
"string",
")",
"(",
"data",
".",
"PublicKey",
",",
"error",
")",
"{",
"_",
"... | // GetOrCreateSnapshotKey either creates a new snapshot key, or returns
// the existing one. Only the PublicKey is returned. The private part
// is held by the CryptoService. | [
"GetOrCreateSnapshotKey",
"either",
"creates",
"a",
"new",
"snapshot",
"key",
"or",
"returns",
"the",
"existing",
"one",
".",
"Only",
"the",
"PublicKey",
"is",
"returned",
".",
"The",
"private",
"part",
"is",
"held",
"by",
"the",
"CryptoService",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/snapshot/snapshot.go#L19-L51 | train |
theupdateframework/notary | server/snapshot/snapshot.go | RotateSnapshotKey | func RotateSnapshotKey(gun data.GUN, store storage.MetaStore, crypto signed.CryptoService, createAlgorithm string) (data.PublicKey, error) {
// Always attempt to create a new key, but this might be rate-limited
key, err := crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm)
if err != nil {
return nil, err
}
logrus.Debug("Created new pending snapshot key ", key.ID(), "to rotate to for ", gun, ". With algo: ", key.Algorithm())
return key, nil
} | go | func RotateSnapshotKey(gun data.GUN, store storage.MetaStore, crypto signed.CryptoService, createAlgorithm string) (data.PublicKey, error) {
// Always attempt to create a new key, but this might be rate-limited
key, err := crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm)
if err != nil {
return nil, err
}
logrus.Debug("Created new pending snapshot key ", key.ID(), "to rotate to for ", gun, ". With algo: ", key.Algorithm())
return key, nil
} | [
"func",
"RotateSnapshotKey",
"(",
"gun",
"data",
".",
"GUN",
",",
"store",
"storage",
".",
"MetaStore",
",",
"crypto",
"signed",
".",
"CryptoService",
",",
"createAlgorithm",
"string",
")",
"(",
"data",
".",
"PublicKey",
",",
"error",
")",
"{",
"key",
",",... | // RotateSnapshotKey attempts to rotate a snapshot key in the signer, but might be rate-limited by the signer | [
"RotateSnapshotKey",
"attempts",
"to",
"rotate",
"a",
"snapshot",
"key",
"in",
"the",
"signer",
"but",
"might",
"be",
"rate",
"-",
"limited",
"by",
"the",
"signer"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/snapshot/snapshot.go#L54-L62 | train |
theupdateframework/notary | server/snapshot/snapshot.go | GetOrCreateSnapshot | func GetOrCreateSnapshot(gun data.GUN, checksum string, store storage.MetaStore, cryptoService signed.CryptoService) (
*time.Time, []byte, error) {
lastModified, currentJSON, err := store.GetChecksum(gun, data.CanonicalSnapshotRole, checksum)
if err != nil {
return nil, nil, err
}
prev := new(data.SignedSnapshot)
if err := json.Unmarshal(currentJSON, prev); err != nil {
logrus.Error("Failed to unmarshal existing snapshot for GUN ", gun)
return nil, nil, err
}
if !snapshotExpired(prev) {
return lastModified, currentJSON, nil
}
builder := tuf.NewRepoBuilder(gun, cryptoService, trustpinning.TrustPinConfig{})
// load the current root to ensure we use the correct snapshot key.
_, rootJSON, err := store.GetCurrent(gun, data.CanonicalRootRole)
if err != nil {
logrus.Debug("Previous snapshot, but no root for GUN ", gun)
return nil, nil, err
}
if err := builder.Load(data.CanonicalRootRole, rootJSON, 1, false); err != nil {
logrus.Debug("Could not load valid previous root for GUN ", gun)
return nil, nil, err
}
meta, _, err := builder.GenerateSnapshot(prev)
if err != nil {
return nil, nil, err
}
return nil, meta, nil
} | go | func GetOrCreateSnapshot(gun data.GUN, checksum string, store storage.MetaStore, cryptoService signed.CryptoService) (
*time.Time, []byte, error) {
lastModified, currentJSON, err := store.GetChecksum(gun, data.CanonicalSnapshotRole, checksum)
if err != nil {
return nil, nil, err
}
prev := new(data.SignedSnapshot)
if err := json.Unmarshal(currentJSON, prev); err != nil {
logrus.Error("Failed to unmarshal existing snapshot for GUN ", gun)
return nil, nil, err
}
if !snapshotExpired(prev) {
return lastModified, currentJSON, nil
}
builder := tuf.NewRepoBuilder(gun, cryptoService, trustpinning.TrustPinConfig{})
// load the current root to ensure we use the correct snapshot key.
_, rootJSON, err := store.GetCurrent(gun, data.CanonicalRootRole)
if err != nil {
logrus.Debug("Previous snapshot, but no root for GUN ", gun)
return nil, nil, err
}
if err := builder.Load(data.CanonicalRootRole, rootJSON, 1, false); err != nil {
logrus.Debug("Could not load valid previous root for GUN ", gun)
return nil, nil, err
}
meta, _, err := builder.GenerateSnapshot(prev)
if err != nil {
return nil, nil, err
}
return nil, meta, nil
} | [
"func",
"GetOrCreateSnapshot",
"(",
"gun",
"data",
".",
"GUN",
",",
"checksum",
"string",
",",
"store",
"storage",
".",
"MetaStore",
",",
"cryptoService",
"signed",
".",
"CryptoService",
")",
"(",
"*",
"time",
".",
"Time",
",",
"[",
"]",
"byte",
",",
"er... | // GetOrCreateSnapshot either returns the existing latest snapshot, or uses
// whatever the most recent snapshot is to generate the next one, only updating
// the expiry time and version. Note that this function does not write generated
// snapshots to the underlying data store, and will either return the latest snapshot time
// or nil as the time modified | [
"GetOrCreateSnapshot",
"either",
"returns",
"the",
"existing",
"latest",
"snapshot",
"or",
"uses",
"whatever",
"the",
"most",
"recent",
"snapshot",
"is",
"to",
"generate",
"the",
"next",
"one",
"only",
"updating",
"the",
"expiry",
"time",
"and",
"version",
".",
... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/snapshot/snapshot.go#L69-L106 | train |
theupdateframework/notary | server/snapshot/snapshot.go | snapshotExpired | func snapshotExpired(sn *data.SignedSnapshot) bool {
return signed.IsExpired(sn.Signed.Expires)
} | go | func snapshotExpired(sn *data.SignedSnapshot) bool {
return signed.IsExpired(sn.Signed.Expires)
} | [
"func",
"snapshotExpired",
"(",
"sn",
"*",
"data",
".",
"SignedSnapshot",
")",
"bool",
"{",
"return",
"signed",
".",
"IsExpired",
"(",
"sn",
".",
"Signed",
".",
"Expires",
")",
"\n",
"}"
] | // snapshotExpired simply checks if the snapshot is past its expiry time | [
"snapshotExpired",
"simply",
"checks",
"if",
"the",
"snapshot",
"is",
"past",
"its",
"expiry",
"time"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/snapshot/snapshot.go#L109-L111 | train |
theupdateframework/notary | storage/offlinestore.go | GetSized | func (es OfflineStore) GetSized(name string, size int64) ([]byte, error) {
return nil, err
} | go | func (es OfflineStore) GetSized(name string, size int64) ([]byte, error) {
return nil, err
} | [
"func",
"(",
"es",
"OfflineStore",
")",
"GetSized",
"(",
"name",
"string",
",",
"size",
"int64",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"nil",
",",
"err",
"\n",
"}"
] | // GetSized returns ErrOffline | [
"GetSized",
"returns",
"ErrOffline"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/offlinestore.go#L21-L23 | train |
theupdateframework/notary | storage/offlinestore.go | GetKey | func (es OfflineStore) GetKey(role data.RoleName) ([]byte, error) {
return nil, err
} | go | func (es OfflineStore) GetKey(role data.RoleName) ([]byte, error) {
return nil, err
} | [
"func",
"(",
"es",
"OfflineStore",
")",
"GetKey",
"(",
"role",
"data",
".",
"RoleName",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"nil",
",",
"err",
"\n",
"}"
] | // GetKey returns ErrOffline | [
"GetKey",
"returns",
"ErrOffline"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/storage/offlinestore.go#L41-L43 | train |
theupdateframework/notary | client/delegations.go | AddDelegationRoleAndKeys | func (r *repository) AddDelegationRoleAndKeys(name data.RoleName, delegationKeys []data.PublicKey) error {
if !data.IsDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Adding delegation "%s" with threshold %d, and %d keys\n`,
name, notary.MinThreshold, len(delegationKeys))
// Defaulting to threshold of 1, since we don't allow for larger thresholds at the moment.
tdJSON, err := json.Marshal(&changelist.TUFDelegation{
NewThreshold: notary.MinThreshold,
AddKeys: data.KeyList(delegationKeys),
})
if err != nil {
return err
}
template := newCreateDelegationChange(name, tdJSON)
return addChange(r.changelist, template, name)
} | go | func (r *repository) AddDelegationRoleAndKeys(name data.RoleName, delegationKeys []data.PublicKey) error {
if !data.IsDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Adding delegation "%s" with threshold %d, and %d keys\n`,
name, notary.MinThreshold, len(delegationKeys))
// Defaulting to threshold of 1, since we don't allow for larger thresholds at the moment.
tdJSON, err := json.Marshal(&changelist.TUFDelegation{
NewThreshold: notary.MinThreshold,
AddKeys: data.KeyList(delegationKeys),
})
if err != nil {
return err
}
template := newCreateDelegationChange(name, tdJSON)
return addChange(r.changelist, template, name)
} | [
"func",
"(",
"r",
"*",
"repository",
")",
"AddDelegationRoleAndKeys",
"(",
"name",
"data",
".",
"RoleName",
",",
"delegationKeys",
"[",
"]",
"data",
".",
"PublicKey",
")",
"error",
"{",
"if",
"!",
"data",
".",
"IsDelegation",
"(",
"name",
")",
"{",
"retu... | // AddDelegationRoleAndKeys creates a changelist entry to add provided delegation public keys.
// This method is the simplest way to create a new delegation, because the delegation must have at least
// one key upon creation to be valid since we will reject the changelist while validating the threshold. | [
"AddDelegationRoleAndKeys",
"creates",
"a",
"changelist",
"entry",
"to",
"add",
"provided",
"delegation",
"public",
"keys",
".",
"This",
"method",
"is",
"the",
"simplest",
"way",
"to",
"create",
"a",
"new",
"delegation",
"because",
"the",
"delegation",
"must",
"... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L35-L55 | train |
theupdateframework/notary | client/delegations.go | AddDelegationPaths | func (r *repository) AddDelegationPaths(name data.RoleName, paths []string) error {
if !data.IsDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Adding %s paths to delegation %s\n`, paths, name)
tdJSON, err := json.Marshal(&changelist.TUFDelegation{
AddPaths: paths,
})
if err != nil {
return err
}
template := newCreateDelegationChange(name, tdJSON)
return addChange(r.changelist, template, name)
} | go | func (r *repository) AddDelegationPaths(name data.RoleName, paths []string) error {
if !data.IsDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Adding %s paths to delegation %s\n`, paths, name)
tdJSON, err := json.Marshal(&changelist.TUFDelegation{
AddPaths: paths,
})
if err != nil {
return err
}
template := newCreateDelegationChange(name, tdJSON)
return addChange(r.changelist, template, name)
} | [
"func",
"(",
"r",
"*",
"repository",
")",
"AddDelegationPaths",
"(",
"name",
"data",
".",
"RoleName",
",",
"paths",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"!",
"data",
".",
"IsDelegation",
"(",
"name",
")",
"{",
"return",
"data",
".",
"ErrInvalid... | // AddDelegationPaths creates a changelist entry to add provided paths to an existing delegation.
// This method cannot create a new delegation itself because the role must meet the key threshold upon creation. | [
"AddDelegationPaths",
"creates",
"a",
"changelist",
"entry",
"to",
"add",
"provided",
"paths",
"to",
"an",
"existing",
"delegation",
".",
"This",
"method",
"cannot",
"create",
"a",
"new",
"delegation",
"itself",
"because",
"the",
"role",
"must",
"meet",
"the",
... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L59-L76 | train |
theupdateframework/notary | client/delegations.go | RemoveDelegationRole | func (r *repository) RemoveDelegationRole(name data.RoleName) error {
if !data.IsDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Removing delegation "%s"\n`, name)
template := newDeleteDelegationChange(name, nil)
return addChange(r.changelist, template, name)
} | go | func (r *repository) RemoveDelegationRole(name data.RoleName) error {
if !data.IsDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Removing delegation "%s"\n`, name)
template := newDeleteDelegationChange(name, nil)
return addChange(r.changelist, template, name)
} | [
"func",
"(",
"r",
"*",
"repository",
")",
"RemoveDelegationRole",
"(",
"name",
"data",
".",
"RoleName",
")",
"error",
"{",
"if",
"!",
"data",
".",
"IsDelegation",
"(",
"name",
")",
"{",
"return",
"data",
".",
"ErrInvalidRole",
"{",
"Role",
":",
"name",
... | // RemoveDelegationRole creates a changelist to remove all paths and keys from a role, and delete the role in its entirety. | [
"RemoveDelegationRole",
"creates",
"a",
"changelist",
"to",
"remove",
"all",
"paths",
"and",
"keys",
"from",
"a",
"role",
"and",
"delete",
"the",
"role",
"in",
"its",
"entirety",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L97-L107 | train |
theupdateframework/notary | client/delegations.go | RemoveDelegationPaths | func (r *repository) RemoveDelegationPaths(name data.RoleName, paths []string) error {
if !data.IsDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Removing %s paths from delegation "%s"\n`, paths, name)
tdJSON, err := json.Marshal(&changelist.TUFDelegation{
RemovePaths: paths,
})
if err != nil {
return err
}
template := newUpdateDelegationChange(name, tdJSON)
return addChange(r.changelist, template, name)
} | go | func (r *repository) RemoveDelegationPaths(name data.RoleName, paths []string) error {
if !data.IsDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Removing %s paths from delegation "%s"\n`, paths, name)
tdJSON, err := json.Marshal(&changelist.TUFDelegation{
RemovePaths: paths,
})
if err != nil {
return err
}
template := newUpdateDelegationChange(name, tdJSON)
return addChange(r.changelist, template, name)
} | [
"func",
"(",
"r",
"*",
"repository",
")",
"RemoveDelegationPaths",
"(",
"name",
"data",
".",
"RoleName",
",",
"paths",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"!",
"data",
".",
"IsDelegation",
"(",
"name",
")",
"{",
"return",
"data",
".",
"ErrInva... | // RemoveDelegationPaths creates a changelist entry to remove provided paths from an existing delegation. | [
"RemoveDelegationPaths",
"creates",
"a",
"changelist",
"entry",
"to",
"remove",
"provided",
"paths",
"from",
"an",
"existing",
"delegation",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L110-L127 | train |
theupdateframework/notary | client/delegations.go | RemoveDelegationKeys | func (r *repository) RemoveDelegationKeys(name data.RoleName, keyIDs []string) error {
if !data.IsDelegation(name) && !data.IsWildDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Removing %s keys from delegation "%s"\n`, keyIDs, name)
tdJSON, err := json.Marshal(&changelist.TUFDelegation{
RemoveKeys: keyIDs,
})
if err != nil {
return err
}
template := newUpdateDelegationChange(name, tdJSON)
return addChange(r.changelist, template, name)
} | go | func (r *repository) RemoveDelegationKeys(name data.RoleName, keyIDs []string) error {
if !data.IsDelegation(name) && !data.IsWildDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Removing %s keys from delegation "%s"\n`, keyIDs, name)
tdJSON, err := json.Marshal(&changelist.TUFDelegation{
RemoveKeys: keyIDs,
})
if err != nil {
return err
}
template := newUpdateDelegationChange(name, tdJSON)
return addChange(r.changelist, template, name)
} | [
"func",
"(",
"r",
"*",
"repository",
")",
"RemoveDelegationKeys",
"(",
"name",
"data",
".",
"RoleName",
",",
"keyIDs",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"!",
"data",
".",
"IsDelegation",
"(",
"name",
")",
"&&",
"!",
"data",
".",
"IsWildDeleg... | // RemoveDelegationKeys creates a changelist entry to remove provided keys from an existing delegation.
// When this changelist is applied, if the specified keys are the only keys left in the role,
// the role itself will be deleted in its entirety.
// It can also delete a key from all delegations under a parent using a name
// with a wildcard at the end. | [
"RemoveDelegationKeys",
"creates",
"a",
"changelist",
"entry",
"to",
"remove",
"provided",
"keys",
"from",
"an",
"existing",
"delegation",
".",
"When",
"this",
"changelist",
"is",
"applied",
"if",
"the",
"specified",
"keys",
"are",
"the",
"only",
"keys",
"left",... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L134-L151 | train |
theupdateframework/notary | client/delegations.go | ClearDelegationPaths | func (r *repository) ClearDelegationPaths(name data.RoleName) error {
if !data.IsDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Removing all paths from delegation "%s"\n`, name)
tdJSON, err := json.Marshal(&changelist.TUFDelegation{
ClearAllPaths: true,
})
if err != nil {
return err
}
template := newUpdateDelegationChange(name, tdJSON)
return addChange(r.changelist, template, name)
} | go | func (r *repository) ClearDelegationPaths(name data.RoleName) error {
if !data.IsDelegation(name) {
return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
}
logrus.Debugf(`Removing all paths from delegation "%s"\n`, name)
tdJSON, err := json.Marshal(&changelist.TUFDelegation{
ClearAllPaths: true,
})
if err != nil {
return err
}
template := newUpdateDelegationChange(name, tdJSON)
return addChange(r.changelist, template, name)
} | [
"func",
"(",
"r",
"*",
"repository",
")",
"ClearDelegationPaths",
"(",
"name",
"data",
".",
"RoleName",
")",
"error",
"{",
"if",
"!",
"data",
".",
"IsDelegation",
"(",
"name",
")",
"{",
"return",
"data",
".",
"ErrInvalidRole",
"{",
"Role",
":",
"name",
... | // ClearDelegationPaths creates a changelist entry to remove all paths from an existing delegation. | [
"ClearDelegationPaths",
"creates",
"a",
"changelist",
"entry",
"to",
"remove",
"all",
"paths",
"from",
"an",
"existing",
"delegation",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/client/delegations.go#L154-L171 | train |
theupdateframework/notary | signer/client/signer_trust.go | Public | func (rs *RemoteSigner) Public() crypto.PublicKey {
publicKey, err := x509.ParsePKIXPublicKey(rs.RemotePrivateKey.Public())
if err != nil {
return nil
}
return publicKey
} | go | func (rs *RemoteSigner) Public() crypto.PublicKey {
publicKey, err := x509.ParsePKIXPublicKey(rs.RemotePrivateKey.Public())
if err != nil {
return nil
}
return publicKey
} | [
"func",
"(",
"rs",
"*",
"RemoteSigner",
")",
"Public",
"(",
")",
"crypto",
".",
"PublicKey",
"{",
"publicKey",
",",
"err",
":=",
"x509",
".",
"ParsePKIXPublicKey",
"(",
"rs",
".",
"RemotePrivateKey",
".",
"Public",
"(",
")",
")",
"\n",
"if",
"err",
"!=... | // Public method of a crypto.Signer needs to return a crypto public key. | [
"Public",
"method",
"of",
"a",
"crypto",
".",
"Signer",
"needs",
"to",
"return",
"a",
"crypto",
"public",
"key",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L38-L45 | train |
theupdateframework/notary | signer/client/signer_trust.go | Sign | func (pk *RemotePrivateKey) Sign(rand io.Reader, msg []byte,
opts crypto.SignerOpts) ([]byte, error) {
keyID := pb.KeyID{ID: pk.ID()}
sr := &pb.SignatureRequest{
Content: msg,
KeyID: &keyID,
}
sig, err := pk.sClient.Sign(context.Background(), sr)
if err != nil {
return nil, err
}
return sig.Content, nil
} | go | func (pk *RemotePrivateKey) Sign(rand io.Reader, msg []byte,
opts crypto.SignerOpts) ([]byte, error) {
keyID := pb.KeyID{ID: pk.ID()}
sr := &pb.SignatureRequest{
Content: msg,
KeyID: &keyID,
}
sig, err := pk.sClient.Sign(context.Background(), sr)
if err != nil {
return nil, err
}
return sig.Content, nil
} | [
"func",
"(",
"pk",
"*",
"RemotePrivateKey",
")",
"Sign",
"(",
"rand",
"io",
".",
"Reader",
",",
"msg",
"[",
"]",
"byte",
",",
"opts",
"crypto",
".",
"SignerOpts",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"keyID",
":=",
"pb",
".",
"KeyI... | // Sign calls a remote service to sign a message. | [
"Sign",
"calls",
"a",
"remote",
"service",
"to",
"sign",
"a",
"message",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L62-L75 | train |
theupdateframework/notary | signer/client/signer_trust.go | SignatureAlgorithm | func (pk *RemotePrivateKey) SignatureAlgorithm() data.SigAlgorithm {
switch pk.PublicKey.Algorithm() {
case data.ECDSAKey, data.ECDSAx509Key:
return data.ECDSASignature
case data.RSAKey, data.RSAx509Key:
return data.RSAPSSSignature
case data.ED25519Key:
return data.EDDSASignature
default: // unknown
return ""
}
} | go | func (pk *RemotePrivateKey) SignatureAlgorithm() data.SigAlgorithm {
switch pk.PublicKey.Algorithm() {
case data.ECDSAKey, data.ECDSAx509Key:
return data.ECDSASignature
case data.RSAKey, data.RSAx509Key:
return data.RSAPSSSignature
case data.ED25519Key:
return data.EDDSASignature
default: // unknown
return ""
}
} | [
"func",
"(",
"pk",
"*",
"RemotePrivateKey",
")",
"SignatureAlgorithm",
"(",
")",
"data",
".",
"SigAlgorithm",
"{",
"switch",
"pk",
".",
"PublicKey",
".",
"Algorithm",
"(",
")",
"{",
"case",
"data",
".",
"ECDSAKey",
",",
"data",
".",
"ECDSAx509Key",
":",
... | // SignatureAlgorithm returns the signing algorithm based on the type of
// PublicKey algorithm. | [
"SignatureAlgorithm",
"returns",
"the",
"signing",
"algorithm",
"based",
"on",
"the",
"type",
"of",
"PublicKey",
"algorithm",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L79-L90 | train |
theupdateframework/notary | signer/client/signer_trust.go | CheckHealth | func (trust *NotarySigner) CheckHealth(d time.Duration, serviceName string) error {
switch serviceName {
case notary.HealthCheckKeyManagement:
return healthCheckKeyManagement(d, trust.healthClient)
case notary.HealthCheckSigner:
return healthCheckSigner(d, trust.healthClient)
case notary.HealthCheckOverall:
if err := healthCheckKeyManagement(d, trust.healthClient); err != nil {
return err
}
return healthCheckSigner(d, trust.healthClient)
default:
return fmt.Errorf("Unknown grpc service %s", serviceName)
}
} | go | func (trust *NotarySigner) CheckHealth(d time.Duration, serviceName string) error {
switch serviceName {
case notary.HealthCheckKeyManagement:
return healthCheckKeyManagement(d, trust.healthClient)
case notary.HealthCheckSigner:
return healthCheckSigner(d, trust.healthClient)
case notary.HealthCheckOverall:
if err := healthCheckKeyManagement(d, trust.healthClient); err != nil {
return err
}
return healthCheckSigner(d, trust.healthClient)
default:
return fmt.Errorf("Unknown grpc service %s", serviceName)
}
} | [
"func",
"(",
"trust",
"*",
"NotarySigner",
")",
"CheckHealth",
"(",
"d",
"time",
".",
"Duration",
",",
"serviceName",
"string",
")",
"error",
"{",
"switch",
"serviceName",
"{",
"case",
"notary",
".",
"HealthCheckKeyManagement",
":",
"return",
"healthCheckKeyMana... | // CheckHealth are used to probe whether the server is able to handle rpcs. | [
"CheckHealth",
"are",
"used",
"to",
"probe",
"whether",
"the",
"server",
"is",
"able",
"to",
"handle",
"rpcs",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L138-L152 | train |
theupdateframework/notary | signer/client/signer_trust.go | NewGRPCConnection | func NewGRPCConnection(hostname string, port string, tlsConfig *tls.Config) (*grpc.ClientConn, error) {
var opts []grpc.DialOption
netAddr := net.JoinHostPort(hostname, port)
creds := credentials.NewTLS(tlsConfig)
opts = append(opts, grpc.WithTransportCredentials(creds))
return grpc.Dial(netAddr, opts...)
} | go | func NewGRPCConnection(hostname string, port string, tlsConfig *tls.Config) (*grpc.ClientConn, error) {
var opts []grpc.DialOption
netAddr := net.JoinHostPort(hostname, port)
creds := credentials.NewTLS(tlsConfig)
opts = append(opts, grpc.WithTransportCredentials(creds))
return grpc.Dial(netAddr, opts...)
} | [
"func",
"NewGRPCConnection",
"(",
"hostname",
"string",
",",
"port",
"string",
",",
"tlsConfig",
"*",
"tls",
".",
"Config",
")",
"(",
"*",
"grpc",
".",
"ClientConn",
",",
"error",
")",
"{",
"var",
"opts",
"[",
"]",
"grpc",
".",
"DialOption",
"\n",
"net... | // NewGRPCConnection is a convenience method that returns GRPC Client Connection given a hostname, endpoint, and TLS options | [
"NewGRPCConnection",
"is",
"a",
"convenience",
"method",
"that",
"returns",
"GRPC",
"Client",
"Connection",
"given",
"a",
"hostname",
"endpoint",
"and",
"TLS",
"options"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L155-L161 | train |
theupdateframework/notary | signer/client/signer_trust.go | NewNotarySigner | func NewNotarySigner(conn *grpc.ClientConn) *NotarySigner {
kmClient := pb.NewKeyManagementClient(conn)
sClient := pb.NewSignerClient(conn)
hc := healthpb.NewHealthClient(conn)
return &NotarySigner{
kmClient: kmClient,
sClient: sClient,
healthClient: hc,
}
} | go | func NewNotarySigner(conn *grpc.ClientConn) *NotarySigner {
kmClient := pb.NewKeyManagementClient(conn)
sClient := pb.NewSignerClient(conn)
hc := healthpb.NewHealthClient(conn)
return &NotarySigner{
kmClient: kmClient,
sClient: sClient,
healthClient: hc,
}
} | [
"func",
"NewNotarySigner",
"(",
"conn",
"*",
"grpc",
".",
"ClientConn",
")",
"*",
"NotarySigner",
"{",
"kmClient",
":=",
"pb",
".",
"NewKeyManagementClient",
"(",
"conn",
")",
"\n",
"sClient",
":=",
"pb",
".",
"NewSignerClient",
"(",
"conn",
")",
"\n",
"hc... | // NewNotarySigner is a convenience method that returns NotarySigner given a GRPC connection | [
"NewNotarySigner",
"is",
"a",
"convenience",
"method",
"that",
"returns",
"NotarySigner",
"given",
"a",
"GRPC",
"connection"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L164-L174 | train |
theupdateframework/notary | signer/client/signer_trust.go | Create | func (trust *NotarySigner) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) {
publicKey, err := trust.kmClient.CreateKey(context.Background(),
&pb.CreateKeyRequest{Algorithm: algorithm, Role: role.String(), Gun: gun.String()})
if err != nil {
return nil, err
}
public := data.NewPublicKey(publicKey.KeyInfo.Algorithm.Algorithm, publicKey.PublicKey)
return public, nil
} | go | func (trust *NotarySigner) Create(role data.RoleName, gun data.GUN, algorithm string) (data.PublicKey, error) {
publicKey, err := trust.kmClient.CreateKey(context.Background(),
&pb.CreateKeyRequest{Algorithm: algorithm, Role: role.String(), Gun: gun.String()})
if err != nil {
return nil, err
}
public := data.NewPublicKey(publicKey.KeyInfo.Algorithm.Algorithm, publicKey.PublicKey)
return public, nil
} | [
"func",
"(",
"trust",
"*",
"NotarySigner",
")",
"Create",
"(",
"role",
"data",
".",
"RoleName",
",",
"gun",
"data",
".",
"GUN",
",",
"algorithm",
"string",
")",
"(",
"data",
".",
"PublicKey",
",",
"error",
")",
"{",
"publicKey",
",",
"err",
":=",
"tr... | // Create creates a remote key and returns the PublicKey associated with the remote private key | [
"Create",
"creates",
"a",
"remote",
"key",
"and",
"returns",
"the",
"PublicKey",
"associated",
"with",
"the",
"remote",
"private",
"key"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L177-L185 | train |
theupdateframework/notary | signer/client/signer_trust.go | AddKey | func (trust *NotarySigner) AddKey(role data.RoleName, gun data.GUN, k data.PrivateKey) error {
return errors.New("Adding a key to NotarySigner is not supported")
} | go | func (trust *NotarySigner) AddKey(role data.RoleName, gun data.GUN, k data.PrivateKey) error {
return errors.New("Adding a key to NotarySigner is not supported")
} | [
"func",
"(",
"trust",
"*",
"NotarySigner",
")",
"AddKey",
"(",
"role",
"data",
".",
"RoleName",
",",
"gun",
"data",
".",
"GUN",
",",
"k",
"data",
".",
"PrivateKey",
")",
"error",
"{",
"return",
"errors",
".",
"New",
"(",
"\"Adding a key to NotarySigner is ... | // AddKey adds a key | [
"AddKey",
"adds",
"a",
"key"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L188-L190 | train |
theupdateframework/notary | signer/client/signer_trust.go | RemoveKey | func (trust *NotarySigner) RemoveKey(keyid string) error {
_, err := trust.kmClient.DeleteKey(context.Background(), &pb.KeyID{ID: keyid})
return err
} | go | func (trust *NotarySigner) RemoveKey(keyid string) error {
_, err := trust.kmClient.DeleteKey(context.Background(), &pb.KeyID{ID: keyid})
return err
} | [
"func",
"(",
"trust",
"*",
"NotarySigner",
")",
"RemoveKey",
"(",
"keyid",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"trust",
".",
"kmClient",
".",
"DeleteKey",
"(",
"context",
".",
"Background",
"(",
")",
",",
"&",
"pb",
".",
"KeyID",
"{",... | // RemoveKey deletes a key by ID - if the key didn't exist, succeed anyway | [
"RemoveKey",
"deletes",
"a",
"key",
"by",
"ID",
"-",
"if",
"the",
"key",
"didn",
"t",
"exist",
"succeed",
"anyway"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L193-L196 | train |
theupdateframework/notary | signer/client/signer_trust.go | GetKey | func (trust *NotarySigner) GetKey(keyid string) data.PublicKey {
pubKey, _, err := trust.getKeyInfo(keyid)
if err != nil {
return nil
}
return pubKey
} | go | func (trust *NotarySigner) GetKey(keyid string) data.PublicKey {
pubKey, _, err := trust.getKeyInfo(keyid)
if err != nil {
return nil
}
return pubKey
} | [
"func",
"(",
"trust",
"*",
"NotarySigner",
")",
"GetKey",
"(",
"keyid",
"string",
")",
"data",
".",
"PublicKey",
"{",
"pubKey",
",",
"_",
",",
"err",
":=",
"trust",
".",
"getKeyInfo",
"(",
"keyid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // GetKey retrieves a key by ID - returns nil if the key doesn't exist | [
"GetKey",
"retrieves",
"a",
"key",
"by",
"ID",
"-",
"returns",
"nil",
"if",
"the",
"key",
"doesn",
"t",
"exist"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L199-L205 | train |
theupdateframework/notary | signer/client/signer_trust.go | GetPrivateKey | func (trust *NotarySigner) GetPrivateKey(keyid string) (data.PrivateKey, data.RoleName, error) {
pubKey, role, err := trust.getKeyInfo(keyid)
if err != nil {
return nil, "", err
}
return NewRemotePrivateKey(pubKey, trust.sClient), role, nil
} | go | func (trust *NotarySigner) GetPrivateKey(keyid string) (data.PrivateKey, data.RoleName, error) {
pubKey, role, err := trust.getKeyInfo(keyid)
if err != nil {
return nil, "", err
}
return NewRemotePrivateKey(pubKey, trust.sClient), role, nil
} | [
"func",
"(",
"trust",
"*",
"NotarySigner",
")",
"GetPrivateKey",
"(",
"keyid",
"string",
")",
"(",
"data",
".",
"PrivateKey",
",",
"data",
".",
"RoleName",
",",
"error",
")",
"{",
"pubKey",
",",
"role",
",",
"err",
":=",
"trust",
".",
"getKeyInfo",
"("... | // GetPrivateKey retrieves by ID an object that can be used to sign, but that does
// not contain any private bytes. If the key doesn't exist, returns an error. | [
"GetPrivateKey",
"retrieves",
"by",
"ID",
"an",
"object",
"that",
"can",
"be",
"used",
"to",
"sign",
"but",
"that",
"does",
"not",
"contain",
"any",
"private",
"bytes",
".",
"If",
"the",
"key",
"doesn",
"t",
"exist",
"returns",
"an",
"error",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/client/signer_trust.go#L217-L223 | train |
theupdateframework/notary | trustmanager/keystore.go | NewKeyFileStore | func NewKeyFileStore(baseDir string, p notary.PassRetriever) (*GenericKeyStore, error) {
fileStore, err := store.NewPrivateKeyFileStorage(baseDir, notary.KeyExtension)
if err != nil {
return nil, err
}
return NewGenericKeyStore(fileStore, p), nil
} | go | func NewKeyFileStore(baseDir string, p notary.PassRetriever) (*GenericKeyStore, error) {
fileStore, err := store.NewPrivateKeyFileStorage(baseDir, notary.KeyExtension)
if err != nil {
return nil, err
}
return NewGenericKeyStore(fileStore, p), nil
} | [
"func",
"NewKeyFileStore",
"(",
"baseDir",
"string",
",",
"p",
"notary",
".",
"PassRetriever",
")",
"(",
"*",
"GenericKeyStore",
",",
"error",
")",
"{",
"fileStore",
",",
"err",
":=",
"store",
".",
"NewPrivateKeyFileStorage",
"(",
"baseDir",
",",
"notary",
"... | // NewKeyFileStore returns a new KeyFileStore creating a private directory to
// hold the keys. | [
"NewKeyFileStore",
"returns",
"a",
"new",
"KeyFileStore",
"creating",
"a",
"private",
"directory",
"to",
"hold",
"the",
"keys",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L35-L41 | train |
theupdateframework/notary | trustmanager/keystore.go | NewKeyMemoryStore | func NewKeyMemoryStore(p notary.PassRetriever) *GenericKeyStore {
memStore := store.NewMemoryStore(nil)
return NewGenericKeyStore(memStore, p)
} | go | func NewKeyMemoryStore(p notary.PassRetriever) *GenericKeyStore {
memStore := store.NewMemoryStore(nil)
return NewGenericKeyStore(memStore, p)
} | [
"func",
"NewKeyMemoryStore",
"(",
"p",
"notary",
".",
"PassRetriever",
")",
"*",
"GenericKeyStore",
"{",
"memStore",
":=",
"store",
".",
"NewMemoryStore",
"(",
"nil",
")",
"\n",
"return",
"NewGenericKeyStore",
"(",
"memStore",
",",
"p",
")",
"\n",
"}"
] | // NewKeyMemoryStore returns a new KeyMemoryStore which holds keys in memory | [
"NewKeyMemoryStore",
"returns",
"a",
"new",
"KeyMemoryStore",
"which",
"holds",
"keys",
"in",
"memory"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L44-L47 | train |
theupdateframework/notary | trustmanager/keystore.go | GetKeyInfo | func (s *GenericKeyStore) GetKeyInfo(keyID string) (KeyInfo, error) {
if info, ok := s.keyInfoMap[keyID]; ok {
return info, nil
}
return KeyInfo{}, fmt.Errorf("Could not find info for keyID %s", keyID)
} | go | func (s *GenericKeyStore) GetKeyInfo(keyID string) (KeyInfo, error) {
if info, ok := s.keyInfoMap[keyID]; ok {
return info, nil
}
return KeyInfo{}, fmt.Errorf("Could not find info for keyID %s", keyID)
} | [
"func",
"(",
"s",
"*",
"GenericKeyStore",
")",
"GetKeyInfo",
"(",
"keyID",
"string",
")",
"(",
"KeyInfo",
",",
"error",
")",
"{",
"if",
"info",
",",
"ok",
":=",
"s",
".",
"keyInfoMap",
"[",
"keyID",
"]",
";",
"ok",
"{",
"return",
"info",
",",
"nil"... | // GetKeyInfo returns the corresponding gun and role key info for a keyID | [
"GetKeyInfo",
"returns",
"the",
"corresponding",
"gun",
"and",
"role",
"key",
"info",
"for",
"a",
"keyID"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L85-L90 | train |
theupdateframework/notary | trustmanager/keystore.go | AddKey | func (s *GenericKeyStore) AddKey(keyInfo KeyInfo, privKey data.PrivateKey) error {
var (
chosenPassphrase string
giveup bool
err error
pemPrivKey []byte
)
s.Lock()
defer s.Unlock()
if keyInfo.Role == data.CanonicalRootRole || data.IsDelegation(keyInfo.Role) || !data.ValidRole(keyInfo.Role) {
keyInfo.Gun = ""
}
keyID := privKey.ID()
for attempts := 0; ; attempts++ {
chosenPassphrase, giveup, err = s.PassRetriever(keyID, keyInfo.Role.String(), true, attempts)
if err == nil {
break
}
if giveup || attempts > 10 {
return ErrAttemptsExceeded{}
}
}
pemPrivKey, err = utils.ConvertPrivateKeyToPKCS8(privKey, keyInfo.Role, keyInfo.Gun, chosenPassphrase)
if err != nil {
return err
}
s.cachedKeys[keyID] = &cachedKey{role: keyInfo.Role, key: privKey}
err = s.store.Set(keyID, pemPrivKey)
if err != nil {
return err
}
s.keyInfoMap[privKey.ID()] = keyInfo
return nil
} | go | func (s *GenericKeyStore) AddKey(keyInfo KeyInfo, privKey data.PrivateKey) error {
var (
chosenPassphrase string
giveup bool
err error
pemPrivKey []byte
)
s.Lock()
defer s.Unlock()
if keyInfo.Role == data.CanonicalRootRole || data.IsDelegation(keyInfo.Role) || !data.ValidRole(keyInfo.Role) {
keyInfo.Gun = ""
}
keyID := privKey.ID()
for attempts := 0; ; attempts++ {
chosenPassphrase, giveup, err = s.PassRetriever(keyID, keyInfo.Role.String(), true, attempts)
if err == nil {
break
}
if giveup || attempts > 10 {
return ErrAttemptsExceeded{}
}
}
pemPrivKey, err = utils.ConvertPrivateKeyToPKCS8(privKey, keyInfo.Role, keyInfo.Gun, chosenPassphrase)
if err != nil {
return err
}
s.cachedKeys[keyID] = &cachedKey{role: keyInfo.Role, key: privKey}
err = s.store.Set(keyID, pemPrivKey)
if err != nil {
return err
}
s.keyInfoMap[privKey.ID()] = keyInfo
return nil
} | [
"func",
"(",
"s",
"*",
"GenericKeyStore",
")",
"AddKey",
"(",
"keyInfo",
"KeyInfo",
",",
"privKey",
"data",
".",
"PrivateKey",
")",
"error",
"{",
"var",
"(",
"chosenPassphrase",
"string",
"\n",
"giveup",
"bool",
"\n",
"err",
"error",
"\n",
"pemPrivKey",
"[... | // AddKey stores the contents of a PEM-encoded private key as a PEM block | [
"AddKey",
"stores",
"the",
"contents",
"of",
"a",
"PEM",
"-",
"encoded",
"private",
"key",
"as",
"a",
"PEM",
"block"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L93-L129 | train |
theupdateframework/notary | trustmanager/keystore.go | copyKeyInfoMap | func copyKeyInfoMap(keyInfoMap map[string]KeyInfo) map[string]KeyInfo {
copyMap := make(map[string]KeyInfo)
for keyID, keyInfo := range keyInfoMap {
copyMap[keyID] = KeyInfo{Role: keyInfo.Role, Gun: keyInfo.Gun}
}
return copyMap
} | go | func copyKeyInfoMap(keyInfoMap map[string]KeyInfo) map[string]KeyInfo {
copyMap := make(map[string]KeyInfo)
for keyID, keyInfo := range keyInfoMap {
copyMap[keyID] = KeyInfo{Role: keyInfo.Role, Gun: keyInfo.Gun}
}
return copyMap
} | [
"func",
"copyKeyInfoMap",
"(",
"keyInfoMap",
"map",
"[",
"string",
"]",
"KeyInfo",
")",
"map",
"[",
"string",
"]",
"KeyInfo",
"{",
"copyMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"KeyInfo",
")",
"\n",
"for",
"keyID",
",",
"keyInfo",
":=",
"ran... | // copyKeyInfoMap returns a deep copy of the passed-in keyInfoMap | [
"copyKeyInfoMap",
"returns",
"a",
"deep",
"copy",
"of",
"the",
"passed",
"-",
"in",
"keyInfoMap"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L190-L196 | train |
theupdateframework/notary | trustmanager/keystore.go | KeyInfoFromPEM | func KeyInfoFromPEM(pemBytes []byte, filename string) (string, KeyInfo, error) {
var keyID string
keyID = filepath.Base(filename)
role, gun, err := utils.ExtractPrivateKeyAttributes(pemBytes)
if err != nil {
return "", KeyInfo{}, err
}
return keyID, KeyInfo{Gun: gun, Role: role}, nil
} | go | func KeyInfoFromPEM(pemBytes []byte, filename string) (string, KeyInfo, error) {
var keyID string
keyID = filepath.Base(filename)
role, gun, err := utils.ExtractPrivateKeyAttributes(pemBytes)
if err != nil {
return "", KeyInfo{}, err
}
return keyID, KeyInfo{Gun: gun, Role: role}, nil
} | [
"func",
"KeyInfoFromPEM",
"(",
"pemBytes",
"[",
"]",
"byte",
",",
"filename",
"string",
")",
"(",
"string",
",",
"KeyInfo",
",",
"error",
")",
"{",
"var",
"keyID",
"string",
"\n",
"keyID",
"=",
"filepath",
".",
"Base",
"(",
"filename",
")",
"\n",
"role... | // KeyInfoFromPEM attempts to get a keyID and KeyInfo from the filename and PEM bytes of a key | [
"KeyInfoFromPEM",
"attempts",
"to",
"get",
"a",
"keyID",
"and",
"KeyInfo",
"from",
"the",
"filename",
"and",
"PEM",
"bytes",
"of",
"a",
"key"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L199-L207 | train |
theupdateframework/notary | trustmanager/keystore.go | GetPasswdDecryptBytes | func GetPasswdDecryptBytes(passphraseRetriever notary.PassRetriever, pemBytes []byte, name, alias string) (data.PrivateKey, string, error) {
var (
passwd string
privKey data.PrivateKey
)
for attempts := 0; ; attempts++ {
var (
giveup bool
err error
)
if attempts > 10 {
return nil, "", ErrAttemptsExceeded{}
}
passwd, giveup, err = passphraseRetriever(name, alias, false, attempts)
// Check if the passphrase retriever got an error or if it is telling us to give up
if giveup || err != nil {
return nil, "", ErrPasswordInvalid{}
}
// Try to convert PEM encoded bytes back to a PrivateKey using the passphrase
privKey, err = utils.ParsePEMPrivateKey(pemBytes, passwd)
if err == nil {
// We managed to parse the PrivateKey. We've succeeded!
break
}
}
return privKey, passwd, nil
} | go | func GetPasswdDecryptBytes(passphraseRetriever notary.PassRetriever, pemBytes []byte, name, alias string) (data.PrivateKey, string, error) {
var (
passwd string
privKey data.PrivateKey
)
for attempts := 0; ; attempts++ {
var (
giveup bool
err error
)
if attempts > 10 {
return nil, "", ErrAttemptsExceeded{}
}
passwd, giveup, err = passphraseRetriever(name, alias, false, attempts)
// Check if the passphrase retriever got an error or if it is telling us to give up
if giveup || err != nil {
return nil, "", ErrPasswordInvalid{}
}
// Try to convert PEM encoded bytes back to a PrivateKey using the passphrase
privKey, err = utils.ParsePEMPrivateKey(pemBytes, passwd)
if err == nil {
// We managed to parse the PrivateKey. We've succeeded!
break
}
}
return privKey, passwd, nil
} | [
"func",
"GetPasswdDecryptBytes",
"(",
"passphraseRetriever",
"notary",
".",
"PassRetriever",
",",
"pemBytes",
"[",
"]",
"byte",
",",
"name",
",",
"alias",
"string",
")",
"(",
"data",
".",
"PrivateKey",
",",
"string",
",",
"error",
")",
"{",
"var",
"(",
"pa... | // GetPasswdDecryptBytes gets the password to decrypt the given pem bytes.
// Returns the password and private key | [
"GetPasswdDecryptBytes",
"gets",
"the",
"password",
"to",
"decrypt",
"the",
"given",
"pem",
"bytes",
".",
"Returns",
"the",
"password",
"and",
"private",
"key"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/trustmanager/keystore.go#L235-L262 | train |
theupdateframework/notary | signer/keydbstore/sql_keydbstore.go | NewSQLKeyDBStore | func NewSQLKeyDBStore(passphraseRetriever notary.PassRetriever, defaultPassAlias string,
dbDialect string, dbArgs ...interface{}) (*SQLKeyDBStore, error) {
db, err := gorm.Open(dbDialect, dbArgs...)
if err != nil {
return nil, err
}
return &SQLKeyDBStore{
db: *db,
dbType: dbDialect,
defaultPassAlias: defaultPassAlias,
retriever: passphraseRetriever,
nowFunc: time.Now,
}, nil
} | go | func NewSQLKeyDBStore(passphraseRetriever notary.PassRetriever, defaultPassAlias string,
dbDialect string, dbArgs ...interface{}) (*SQLKeyDBStore, error) {
db, err := gorm.Open(dbDialect, dbArgs...)
if err != nil {
return nil, err
}
return &SQLKeyDBStore{
db: *db,
dbType: dbDialect,
defaultPassAlias: defaultPassAlias,
retriever: passphraseRetriever,
nowFunc: time.Now,
}, nil
} | [
"func",
"NewSQLKeyDBStore",
"(",
"passphraseRetriever",
"notary",
".",
"PassRetriever",
",",
"defaultPassAlias",
"string",
",",
"dbDialect",
"string",
",",
"dbArgs",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"SQLKeyDBStore",
",",
"error",
")",
"{",
"db",
",... | // NewSQLKeyDBStore returns a new SQLKeyDBStore backed by a SQL database | [
"NewSQLKeyDBStore",
"returns",
"a",
"new",
"SQLKeyDBStore",
"backed",
"by",
"a",
"SQL",
"database"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/sql_keydbstore.go#L50-L65 | train |
theupdateframework/notary | signer/keydbstore/sql_keydbstore.go | GetPrivateKey | func (s *SQLKeyDBStore) GetPrivateKey(keyID string) (data.PrivateKey, data.RoleName, error) {
// Retrieve the GORM private key from the database
dbPrivateKey, decryptedPrivKey, err := s.getKey(keyID, true)
if err != nil {
return nil, "", err
}
pubKey := data.NewPublicKey(dbPrivateKey.Algorithm, []byte(dbPrivateKey.Public))
// Create a new PrivateKey with unencrypted bytes
privKey, err := data.NewPrivateKey(pubKey, []byte(decryptedPrivKey))
if err != nil {
return nil, "", err
}
return activatingPrivateKey{PrivateKey: privKey, activationFunc: s.markActive}, data.RoleName(dbPrivateKey.Role), nil
} | go | func (s *SQLKeyDBStore) GetPrivateKey(keyID string) (data.PrivateKey, data.RoleName, error) {
// Retrieve the GORM private key from the database
dbPrivateKey, decryptedPrivKey, err := s.getKey(keyID, true)
if err != nil {
return nil, "", err
}
pubKey := data.NewPublicKey(dbPrivateKey.Algorithm, []byte(dbPrivateKey.Public))
// Create a new PrivateKey with unencrypted bytes
privKey, err := data.NewPrivateKey(pubKey, []byte(decryptedPrivKey))
if err != nil {
return nil, "", err
}
return activatingPrivateKey{PrivateKey: privKey, activationFunc: s.markActive}, data.RoleName(dbPrivateKey.Role), nil
} | [
"func",
"(",
"s",
"*",
"SQLKeyDBStore",
")",
"GetPrivateKey",
"(",
"keyID",
"string",
")",
"(",
"data",
".",
"PrivateKey",
",",
"data",
".",
"RoleName",
",",
"error",
")",
"{",
"dbPrivateKey",
",",
"decryptedPrivKey",
",",
"err",
":=",
"s",
".",
"getKey"... | // GetPrivateKey returns the PrivateKey given a KeyID | [
"GetPrivateKey",
"returns",
"the",
"PrivateKey",
"given",
"a",
"KeyID"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/sql_keydbstore.go#L131-L146 | train |
theupdateframework/notary | signer/keydbstore/sql_keydbstore.go | GetKey | func (s *SQLKeyDBStore) GetKey(keyID string) data.PublicKey {
privKey, _, err := s.getKey(keyID, false)
if err != nil {
return nil
}
return data.NewPublicKey(privKey.Algorithm, []byte(privKey.Public))
} | go | func (s *SQLKeyDBStore) GetKey(keyID string) data.PublicKey {
privKey, _, err := s.getKey(keyID, false)
if err != nil {
return nil
}
return data.NewPublicKey(privKey.Algorithm, []byte(privKey.Public))
} | [
"func",
"(",
"s",
"*",
"SQLKeyDBStore",
")",
"GetKey",
"(",
"keyID",
"string",
")",
"data",
".",
"PublicKey",
"{",
"privKey",
",",
"_",
",",
"err",
":=",
"s",
".",
"getKey",
"(",
"keyID",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"r... | // GetKey performs the same get as GetPrivateKey, but does not mark the as active and only returns the public bytes | [
"GetKey",
"performs",
"the",
"same",
"get",
"as",
"GetPrivateKey",
"but",
"does",
"not",
"mark",
"the",
"as",
"active",
"and",
"only",
"returns",
"the",
"public",
"bytes"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/sql_keydbstore.go#L223-L229 | train |
theupdateframework/notary | signer/keydbstore/sql_keydbstore.go | HealthCheck | func (s *SQLKeyDBStore) HealthCheck() error {
dbPrivateKey := GormPrivateKey{}
tableOk := s.db.HasTable(&dbPrivateKey)
switch {
case s.db.Error != nil:
return s.db.Error
case !tableOk:
return fmt.Errorf(
"Cannot access table: %s", dbPrivateKey.TableName())
}
return nil
} | go | func (s *SQLKeyDBStore) HealthCheck() error {
dbPrivateKey := GormPrivateKey{}
tableOk := s.db.HasTable(&dbPrivateKey)
switch {
case s.db.Error != nil:
return s.db.Error
case !tableOk:
return fmt.Errorf(
"Cannot access table: %s", dbPrivateKey.TableName())
}
return nil
} | [
"func",
"(",
"s",
"*",
"SQLKeyDBStore",
")",
"HealthCheck",
"(",
")",
"error",
"{",
"dbPrivateKey",
":=",
"GormPrivateKey",
"{",
"}",
"\n",
"tableOk",
":=",
"s",
".",
"db",
".",
"HasTable",
"(",
"&",
"dbPrivateKey",
")",
"\n",
"switch",
"{",
"case",
"s... | // HealthCheck verifies that DB exists and is query-able | [
"HealthCheck",
"verifies",
"that",
"DB",
"exists",
"and",
"is",
"query",
"-",
"able"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/signer/keydbstore/sql_keydbstore.go#L232-L243 | train |
theupdateframework/notary | cryptoservice/certificate.go | GenerateCertificate | func GenerateCertificate(rootKey data.PrivateKey, gun data.GUN, startTime, endTime time.Time) (*x509.Certificate, error) {
signer := rootKey.CryptoSigner()
if signer == nil {
return nil, fmt.Errorf("key type not supported for Certificate generation: %s", rootKey.Algorithm())
}
return generateCertificate(signer, gun, startTime, endTime)
} | go | func GenerateCertificate(rootKey data.PrivateKey, gun data.GUN, startTime, endTime time.Time) (*x509.Certificate, error) {
signer := rootKey.CryptoSigner()
if signer == nil {
return nil, fmt.Errorf("key type not supported for Certificate generation: %s", rootKey.Algorithm())
}
return generateCertificate(signer, gun, startTime, endTime)
} | [
"func",
"GenerateCertificate",
"(",
"rootKey",
"data",
".",
"PrivateKey",
",",
"gun",
"data",
".",
"GUN",
",",
"startTime",
",",
"endTime",
"time",
".",
"Time",
")",
"(",
"*",
"x509",
".",
"Certificate",
",",
"error",
")",
"{",
"signer",
":=",
"rootKey",... | // GenerateCertificate generates an X509 Certificate from a template, given a GUN and validity interval | [
"GenerateCertificate",
"generates",
"an",
"X509",
"Certificate",
"from",
"a",
"template",
"given",
"a",
"GUN",
"and",
"validity",
"interval"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/cryptoservice/certificate.go#L15-L22 | train |
theupdateframework/notary | server/storage/rethinkdb.go | NewRethinkDBStorage | func NewRethinkDBStorage(dbName, user, password string, sess *gorethink.Session) RethinkDB {
return RethinkDB{
dbName: dbName,
sess: sess,
user: user,
password: password,
}
} | go | func NewRethinkDBStorage(dbName, user, password string, sess *gorethink.Session) RethinkDB {
return RethinkDB{
dbName: dbName,
sess: sess,
user: user,
password: password,
}
} | [
"func",
"NewRethinkDBStorage",
"(",
"dbName",
",",
"user",
",",
"password",
"string",
",",
"sess",
"*",
"gorethink",
".",
"Session",
")",
"RethinkDB",
"{",
"return",
"RethinkDB",
"{",
"dbName",
":",
"dbName",
",",
"sess",
":",
"sess",
",",
"user",
":",
"... | // NewRethinkDBStorage initializes a RethinkDB object | [
"NewRethinkDBStorage",
"initializes",
"a",
"RethinkDB",
"object"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L106-L113 | train |
theupdateframework/notary | server/storage/rethinkdb.go | UpdateCurrent | func (rdb RethinkDB) UpdateCurrent(gun data.GUN, update MetaUpdate) error {
// empty string is the zero value for tsChecksum in the RDBTUFFile struct.
// Therefore we can just call through to updateCurrentWithTSChecksum passing
// "" for the tsChecksum value.
if err := rdb.updateCurrentWithTSChecksum(gun.String(), "", update); err != nil {
return err
}
if update.Role == data.CanonicalTimestampRole {
tsChecksumBytes := sha256.Sum256(update.Data)
return rdb.writeChange(
gun.String(),
update.Version,
hex.EncodeToString(tsChecksumBytes[:]),
changeCategoryUpdate,
)
}
return nil
} | go | func (rdb RethinkDB) UpdateCurrent(gun data.GUN, update MetaUpdate) error {
// empty string is the zero value for tsChecksum in the RDBTUFFile struct.
// Therefore we can just call through to updateCurrentWithTSChecksum passing
// "" for the tsChecksum value.
if err := rdb.updateCurrentWithTSChecksum(gun.String(), "", update); err != nil {
return err
}
if update.Role == data.CanonicalTimestampRole {
tsChecksumBytes := sha256.Sum256(update.Data)
return rdb.writeChange(
gun.String(),
update.Version,
hex.EncodeToString(tsChecksumBytes[:]),
changeCategoryUpdate,
)
}
return nil
} | [
"func",
"(",
"rdb",
"RethinkDB",
")",
"UpdateCurrent",
"(",
"gun",
"data",
".",
"GUN",
",",
"update",
"MetaUpdate",
")",
"error",
"{",
"if",
"err",
":=",
"rdb",
".",
"updateCurrentWithTSChecksum",
"(",
"gun",
".",
"String",
"(",
")",
",",
"\"\"",
",",
... | // UpdateCurrent adds new metadata version for the given GUN if and only
// if it's a new role, or the version is greater than the current version
// for the role. Otherwise an error is returned. | [
"UpdateCurrent",
"adds",
"new",
"metadata",
"version",
"for",
"the",
"given",
"GUN",
"if",
"and",
"only",
"if",
"it",
"s",
"a",
"new",
"role",
"or",
"the",
"version",
"is",
"greater",
"than",
"the",
"current",
"version",
"for",
"the",
"role",
".",
"Other... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L118-L135 | train |
theupdateframework/notary | server/storage/rethinkdb.go | updateCurrentWithTSChecksum | func (rdb RethinkDB) updateCurrentWithTSChecksum(gun, tsChecksum string, update MetaUpdate) error {
now := time.Now()
checksum := sha256.Sum256(update.Data)
file := RDBTUFFile{
Timing: rethinkdb.Timing{
CreatedAt: now,
UpdatedAt: now,
},
GunRoleVersion: []interface{}{gun, update.Role, update.Version},
Gun: gun,
Role: update.Role.String(),
Version: update.Version,
SHA256: hex.EncodeToString(checksum[:]),
TSchecksum: tsChecksum,
Data: update.Data,
}
_, err := gorethink.DB(rdb.dbName).Table(file.TableName()).Insert(
file,
gorethink.InsertOpts{
Conflict: "error", // default but explicit for clarity of intent
},
).RunWrite(rdb.sess)
if err != nil && gorethink.IsConflictErr(err) {
return ErrOldVersion{}
}
return err
} | go | func (rdb RethinkDB) updateCurrentWithTSChecksum(gun, tsChecksum string, update MetaUpdate) error {
now := time.Now()
checksum := sha256.Sum256(update.Data)
file := RDBTUFFile{
Timing: rethinkdb.Timing{
CreatedAt: now,
UpdatedAt: now,
},
GunRoleVersion: []interface{}{gun, update.Role, update.Version},
Gun: gun,
Role: update.Role.String(),
Version: update.Version,
SHA256: hex.EncodeToString(checksum[:]),
TSchecksum: tsChecksum,
Data: update.Data,
}
_, err := gorethink.DB(rdb.dbName).Table(file.TableName()).Insert(
file,
gorethink.InsertOpts{
Conflict: "error", // default but explicit for clarity of intent
},
).RunWrite(rdb.sess)
if err != nil && gorethink.IsConflictErr(err) {
return ErrOldVersion{}
}
return err
} | [
"func",
"(",
"rdb",
"RethinkDB",
")",
"updateCurrentWithTSChecksum",
"(",
"gun",
",",
"tsChecksum",
"string",
",",
"update",
"MetaUpdate",
")",
"error",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"checksum",
":=",
"sha256",
".",
"Sum256",
"(",
... | // updateCurrentWithTSChecksum adds new metadata version for the given GUN with an associated
// checksum for the timestamp it belongs to, to afford us transaction-like functionality | [
"updateCurrentWithTSChecksum",
"adds",
"new",
"metadata",
"version",
"for",
"the",
"given",
"GUN",
"with",
"an",
"associated",
"checksum",
"for",
"the",
"timestamp",
"it",
"belongs",
"to",
"to",
"afford",
"us",
"transaction",
"-",
"like",
"functionality"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L139-L165 | train |
theupdateframework/notary | server/storage/rethinkdb.go | UpdateMany | func (rdb RethinkDB) UpdateMany(gun data.GUN, updates []MetaUpdate) error {
// find the timestamp first and save its checksum
// then apply the updates in alphabetic role order with the timestamp last
// if there are any failures, we roll back in the same alphabetic order
var (
tsChecksum string
tsVersion int
)
for _, up := range updates {
if up.Role == data.CanonicalTimestampRole {
tsChecksumBytes := sha256.Sum256(up.Data)
tsChecksum = hex.EncodeToString(tsChecksumBytes[:])
tsVersion = up.Version
break
}
}
// alphabetize the updates by Role name
sort.Stable(updateSorter(updates))
for _, up := range updates {
if err := rdb.updateCurrentWithTSChecksum(gun.String(), tsChecksum, up); err != nil {
// roll back with best-effort deletion, and then error out
rollbackErr := rdb.deleteByTSChecksum(tsChecksum)
if rollbackErr != nil {
logrus.Errorf("Unable to rollback DB conflict - items with timestamp_checksum %s: %v",
tsChecksum, rollbackErr)
}
return err
}
}
// if the update included a timestamp, write a change object
if tsChecksum != "" {
return rdb.writeChange(gun.String(), tsVersion, tsChecksum, changeCategoryUpdate)
}
return nil
} | go | func (rdb RethinkDB) UpdateMany(gun data.GUN, updates []MetaUpdate) error {
// find the timestamp first and save its checksum
// then apply the updates in alphabetic role order with the timestamp last
// if there are any failures, we roll back in the same alphabetic order
var (
tsChecksum string
tsVersion int
)
for _, up := range updates {
if up.Role == data.CanonicalTimestampRole {
tsChecksumBytes := sha256.Sum256(up.Data)
tsChecksum = hex.EncodeToString(tsChecksumBytes[:])
tsVersion = up.Version
break
}
}
// alphabetize the updates by Role name
sort.Stable(updateSorter(updates))
for _, up := range updates {
if err := rdb.updateCurrentWithTSChecksum(gun.String(), tsChecksum, up); err != nil {
// roll back with best-effort deletion, and then error out
rollbackErr := rdb.deleteByTSChecksum(tsChecksum)
if rollbackErr != nil {
logrus.Errorf("Unable to rollback DB conflict - items with timestamp_checksum %s: %v",
tsChecksum, rollbackErr)
}
return err
}
}
// if the update included a timestamp, write a change object
if tsChecksum != "" {
return rdb.writeChange(gun.String(), tsVersion, tsChecksum, changeCategoryUpdate)
}
return nil
} | [
"func",
"(",
"rdb",
"RethinkDB",
")",
"UpdateMany",
"(",
"gun",
"data",
".",
"GUN",
",",
"updates",
"[",
"]",
"MetaUpdate",
")",
"error",
"{",
"var",
"(",
"tsChecksum",
"string",
"\n",
"tsVersion",
"int",
"\n",
")",
"\n",
"for",
"_",
",",
"up",
":=",... | // UpdateMany adds multiple new metadata for the given GUN. RethinkDB does
// not support transactions, therefore we will attempt to insert the timestamp
// last as this represents a published version of the repo. However, we will
// insert all other role data in alphabetical order first, and also include the
// associated timestamp checksum so that we can easily roll back this pseudotransaction | [
"UpdateMany",
"adds",
"multiple",
"new",
"metadata",
"for",
"the",
"given",
"GUN",
".",
"RethinkDB",
"does",
"not",
"support",
"transactions",
"therefore",
"we",
"will",
"attempt",
"to",
"insert",
"the",
"timestamp",
"last",
"as",
"this",
"represents",
"a",
"p... | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L182-L219 | train |
theupdateframework/notary | server/storage/rethinkdb.go | Delete | func (rdb RethinkDB) Delete(gun data.GUN) error {
resp, err := gorethink.DB(rdb.dbName).Table(RDBTUFFile{}.TableName()).GetAllByIndex(
"gun", gun.String(),
).Delete().RunWrite(rdb.sess)
if err != nil {
return fmt.Errorf("unable to delete %s from database: %s", gun.String(), err.Error())
}
if resp.Deleted > 0 {
return rdb.writeChange(gun.String(), 0, "", changeCategoryDeletion)
}
return nil
} | go | func (rdb RethinkDB) Delete(gun data.GUN) error {
resp, err := gorethink.DB(rdb.dbName).Table(RDBTUFFile{}.TableName()).GetAllByIndex(
"gun", gun.String(),
).Delete().RunWrite(rdb.sess)
if err != nil {
return fmt.Errorf("unable to delete %s from database: %s", gun.String(), err.Error())
}
if resp.Deleted > 0 {
return rdb.writeChange(gun.String(), 0, "", changeCategoryDeletion)
}
return nil
} | [
"func",
"(",
"rdb",
"RethinkDB",
")",
"Delete",
"(",
"gun",
"data",
".",
"GUN",
")",
"error",
"{",
"resp",
",",
"err",
":=",
"gorethink",
".",
"DB",
"(",
"rdb",
".",
"dbName",
")",
".",
"Table",
"(",
"RDBTUFFile",
"{",
"}",
".",
"TableName",
"(",
... | // Delete removes all metadata for a given GUN. It does not return an
// error if no metadata exists for the given GUN. | [
"Delete",
"removes",
"all",
"metadata",
"for",
"a",
"given",
"GUN",
".",
"It",
"does",
"not",
"return",
"an",
"error",
"if",
"no",
"metadata",
"exists",
"for",
"the",
"given",
"GUN",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L285-L296 | train |
theupdateframework/notary | server/storage/rethinkdb.go | deleteByTSChecksum | func (rdb RethinkDB) deleteByTSChecksum(tsChecksum string) error {
_, err := gorethink.DB(rdb.dbName).Table(RDBTUFFile{}.TableName()).GetAllByIndex(
"timestamp_checksum", tsChecksum,
).Delete().RunWrite(rdb.sess)
if err != nil {
return fmt.Errorf("unable to delete timestamp checksum data: %s from database: %s", tsChecksum, err.Error())
}
// DO NOT WRITE CHANGE! THIS IS USED _ONLY_ TO ROLLBACK A FAILED INSERT
return nil
} | go | func (rdb RethinkDB) deleteByTSChecksum(tsChecksum string) error {
_, err := gorethink.DB(rdb.dbName).Table(RDBTUFFile{}.TableName()).GetAllByIndex(
"timestamp_checksum", tsChecksum,
).Delete().RunWrite(rdb.sess)
if err != nil {
return fmt.Errorf("unable to delete timestamp checksum data: %s from database: %s", tsChecksum, err.Error())
}
// DO NOT WRITE CHANGE! THIS IS USED _ONLY_ TO ROLLBACK A FAILED INSERT
return nil
} | [
"func",
"(",
"rdb",
"RethinkDB",
")",
"deleteByTSChecksum",
"(",
"tsChecksum",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"gorethink",
".",
"DB",
"(",
"rdb",
".",
"dbName",
")",
".",
"Table",
"(",
"RDBTUFFile",
"{",
"}",
".",
"TableName",
"(",... | // deleteByTSChecksum removes all metadata by a timestamp checksum, used for rolling back a "transaction"
// from a call to rethinkdb's UpdateMany | [
"deleteByTSChecksum",
"removes",
"all",
"metadata",
"by",
"a",
"timestamp",
"checksum",
"used",
"for",
"rolling",
"back",
"a",
"transaction",
"from",
"a",
"call",
"to",
"rethinkdb",
"s",
"UpdateMany"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L300-L309 | train |
theupdateframework/notary | server/storage/rethinkdb.go | Bootstrap | func (rdb RethinkDB) Bootstrap() error {
if err := rethinkdb.SetupDB(rdb.sess, rdb.dbName, []rethinkdb.Table{
TUFFilesRethinkTable,
ChangeRethinkTable,
}); err != nil {
return err
}
return rethinkdb.CreateAndGrantDBUser(rdb.sess, rdb.dbName, rdb.user, rdb.password)
} | go | func (rdb RethinkDB) Bootstrap() error {
if err := rethinkdb.SetupDB(rdb.sess, rdb.dbName, []rethinkdb.Table{
TUFFilesRethinkTable,
ChangeRethinkTable,
}); err != nil {
return err
}
return rethinkdb.CreateAndGrantDBUser(rdb.sess, rdb.dbName, rdb.user, rdb.password)
} | [
"func",
"(",
"rdb",
"RethinkDB",
")",
"Bootstrap",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"rethinkdb",
".",
"SetupDB",
"(",
"rdb",
".",
"sess",
",",
"rdb",
".",
"dbName",
",",
"[",
"]",
"rethinkdb",
".",
"Table",
"{",
"TUFFilesRethinkTable",
",",
... | // Bootstrap sets up the database and tables, also creating the notary server user with appropriate db permission | [
"Bootstrap",
"sets",
"up",
"the",
"database",
"and",
"tables",
"also",
"creating",
"the",
"notary",
"server",
"user",
"with",
"appropriate",
"db",
"permission"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L312-L320 | train |
theupdateframework/notary | server/storage/rethinkdb.go | CheckHealth | func (rdb RethinkDB) CheckHealth() error {
res, err := gorethink.DB(rdb.dbName).Table(TUFFilesRethinkTable.Name).Info().Run(rdb.sess)
if err != nil {
return fmt.Errorf("%s is unavailable, or missing one or more tables, or permissions are incorrectly set", rdb.dbName)
}
defer res.Close()
return nil
} | go | func (rdb RethinkDB) CheckHealth() error {
res, err := gorethink.DB(rdb.dbName).Table(TUFFilesRethinkTable.Name).Info().Run(rdb.sess)
if err != nil {
return fmt.Errorf("%s is unavailable, or missing one or more tables, or permissions are incorrectly set", rdb.dbName)
}
defer res.Close()
return nil
} | [
"func",
"(",
"rdb",
"RethinkDB",
")",
"CheckHealth",
"(",
")",
"error",
"{",
"res",
",",
"err",
":=",
"gorethink",
".",
"DB",
"(",
"rdb",
".",
"dbName",
")",
".",
"Table",
"(",
"TUFFilesRethinkTable",
".",
"Name",
")",
".",
"Info",
"(",
")",
".",
"... | // CheckHealth checks that all tables and databases exist and are query-able | [
"CheckHealth",
"checks",
"that",
"all",
"tables",
"and",
"databases",
"exist",
"and",
"are",
"query",
"-",
"able"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L323-L330 | train |
theupdateframework/notary | server/storage/rethinkdb.go | GetChanges | func (rdb RethinkDB) GetChanges(changeID string, pageSize int, filterName string) ([]Change, error) {
var (
lower, upper, bound []interface{}
idx = "rdb_created_at_id"
max = []interface{}{gorethink.Now().Sub(blackoutTime), gorethink.MaxVal}
min = []interface{}{gorethink.MinVal, gorethink.MinVal}
order gorethink.OrderByOpts
reversed bool
)
if filterName != "" {
idx = "rdb_gun_created_at_id"
max = append([]interface{}{filterName}, max...)
min = append([]interface{}{filterName}, min...)
}
switch changeID {
case "0", "-1":
lower = min
upper = max
default:
bound, idx = rdb.bound(changeID, filterName)
if pageSize < 0 {
lower = min
upper = bound
} else {
lower = bound
upper = max
}
}
if changeID == "-1" || pageSize < 0 {
reversed = true
order = gorethink.OrderByOpts{Index: gorethink.Desc(idx)}
} else {
order = gorethink.OrderByOpts{Index: gorethink.Asc(idx)}
}
if pageSize < 0 {
pageSize = pageSize * -1
}
changes := make([]Change, 0, pageSize)
// Between returns a slice of results from the rethinkdb table.
// The results are ordered using BetweenOpts.Index, which will
// default to the index of the immediately preceding OrderBy.
// The lower and upper are the start and end points for the slice
// and the Left/RightBound values determine whether the lower and
// upper values are included in the result per normal set semantics
// of "open" and "closed"
res, err := gorethink.DB(rdb.dbName).
Table(Change{}.TableName(), gorethink.TableOpts{ReadMode: "majority"}).
OrderBy(order).
Between(
lower,
upper,
gorethink.BetweenOpts{
LeftBound: "open",
RightBound: "open",
},
).Limit(pageSize).Run(rdb.sess)
if err != nil {
return nil, err
}
defer res.Close()
defer func() {
if reversed {
// results are currently newest to oldest, should be oldest to newest
for i, j := 0, len(changes)-1; i < j; i, j = i+1, j-1 {
changes[i], changes[j] = changes[j], changes[i]
}
}
}()
return changes, res.All(&changes)
} | go | func (rdb RethinkDB) GetChanges(changeID string, pageSize int, filterName string) ([]Change, error) {
var (
lower, upper, bound []interface{}
idx = "rdb_created_at_id"
max = []interface{}{gorethink.Now().Sub(blackoutTime), gorethink.MaxVal}
min = []interface{}{gorethink.MinVal, gorethink.MinVal}
order gorethink.OrderByOpts
reversed bool
)
if filterName != "" {
idx = "rdb_gun_created_at_id"
max = append([]interface{}{filterName}, max...)
min = append([]interface{}{filterName}, min...)
}
switch changeID {
case "0", "-1":
lower = min
upper = max
default:
bound, idx = rdb.bound(changeID, filterName)
if pageSize < 0 {
lower = min
upper = bound
} else {
lower = bound
upper = max
}
}
if changeID == "-1" || pageSize < 0 {
reversed = true
order = gorethink.OrderByOpts{Index: gorethink.Desc(idx)}
} else {
order = gorethink.OrderByOpts{Index: gorethink.Asc(idx)}
}
if pageSize < 0 {
pageSize = pageSize * -1
}
changes := make([]Change, 0, pageSize)
// Between returns a slice of results from the rethinkdb table.
// The results are ordered using BetweenOpts.Index, which will
// default to the index of the immediately preceding OrderBy.
// The lower and upper are the start and end points for the slice
// and the Left/RightBound values determine whether the lower and
// upper values are included in the result per normal set semantics
// of "open" and "closed"
res, err := gorethink.DB(rdb.dbName).
Table(Change{}.TableName(), gorethink.TableOpts{ReadMode: "majority"}).
OrderBy(order).
Between(
lower,
upper,
gorethink.BetweenOpts{
LeftBound: "open",
RightBound: "open",
},
).Limit(pageSize).Run(rdb.sess)
if err != nil {
return nil, err
}
defer res.Close()
defer func() {
if reversed {
// results are currently newest to oldest, should be oldest to newest
for i, j := 0, len(changes)-1; i < j; i, j = i+1, j-1 {
changes[i], changes[j] = changes[j], changes[i]
}
}
}()
return changes, res.All(&changes)
} | [
"func",
"(",
"rdb",
"RethinkDB",
")",
"GetChanges",
"(",
"changeID",
"string",
",",
"pageSize",
"int",
",",
"filterName",
"string",
")",
"(",
"[",
"]",
"Change",
",",
"error",
")",
"{",
"var",
"(",
"lower",
",",
"upper",
",",
"bound",
"[",
"]",
"inte... | // GetChanges returns up to pageSize changes starting from changeID. It uses the
// blackout to account for RethinkDB's eventual consistency model | [
"GetChanges",
"returns",
"up",
"to",
"pageSize",
"changes",
"starting",
"from",
"changeID",
".",
"It",
"uses",
"the",
"blackout",
"to",
"account",
"for",
"RethinkDB",
"s",
"eventual",
"consistency",
"model"
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L352-L428 | train |
theupdateframework/notary | server/storage/rethinkdb.go | bound | func (rdb RethinkDB) bound(changeID, filterName string) ([]interface{}, string) {
createdAtTerm := gorethink.DB(rdb.dbName).Table(Change{}.TableName()).Get(changeID).Field("created_at")
if filterName != "" {
return []interface{}{filterName, createdAtTerm, changeID}, "rdb_gun_created_at_id"
}
return []interface{}{createdAtTerm, changeID}, "rdb_created_at_id"
} | go | func (rdb RethinkDB) bound(changeID, filterName string) ([]interface{}, string) {
createdAtTerm := gorethink.DB(rdb.dbName).Table(Change{}.TableName()).Get(changeID).Field("created_at")
if filterName != "" {
return []interface{}{filterName, createdAtTerm, changeID}, "rdb_gun_created_at_id"
}
return []interface{}{createdAtTerm, changeID}, "rdb_created_at_id"
} | [
"func",
"(",
"rdb",
"RethinkDB",
")",
"bound",
"(",
"changeID",
",",
"filterName",
"string",
")",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"string",
")",
"{",
"createdAtTerm",
":=",
"gorethink",
".",
"DB",
"(",
"rdb",
".",
"dbName",
")",
".",
"Tabl... | // bound creates the correct boundary based in the index that should be used for
// querying the changefeed. | [
"bound",
"creates",
"the",
"correct",
"boundary",
"based",
"in",
"the",
"index",
"that",
"should",
"be",
"used",
"for",
"querying",
"the",
"changefeed",
"."
] | 8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5 | https://github.com/theupdateframework/notary/blob/8ff3ca06ec48f31e1f1d2685e3e6a9f65b6b92b5/server/storage/rethinkdb.go#L432-L438 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.