本文整理匯總了Golang中github.com/endophage/gotuf/keys.NewDB函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewDB函數的具體用法?Golang NewDB怎麽用?Golang NewDB使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewDB函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: tufLookup
func tufLookup(cmd *cobra.Command, args []string) {
if len(args) < 2 {
cmd.Usage()
fatalf("must specify a GUN and target")
}
gun := args[0]
targetName := args[1]
kdb := keys.NewDB()
repo := tuf.NewTufRepo(kdb, nil)
remote, err := getRemoteStore(gun)
c, err := bootstrapClient(gun, remote, repo, kdb)
if err != nil {
return
}
err = c.Update()
if err != nil {
logrus.Error("Error updating client: ", err.Error())
return
}
meta := c.TargetMeta(targetName)
if meta == nil {
logrus.Infof("Target %s not found in %s.", targetName, gun)
return
}
if rawOutput {
fmt.Println(targetName, fmt.Sprintf("sha256:%s", meta.Hashes["sha256"]), meta.Length)
} else {
fmt.Println(targetName, fmt.Sprintf("sha256:%s", meta.Hashes["sha256"]), meta.Length)
}
}
示例2: TestUpdateDelegations
func TestUpdateDelegations(t *testing.T) {
ed25519 := signed.NewEd25519()
keyDB := keys.NewDB()
repo := initRepo(t, ed25519, keyDB)
testKey, err := ed25519.Create("targets/test", data.ED25519Key)
if err != nil {
t.Fatal(err)
}
role, err := data.NewRole("targets/test", 1, []string{testKey.ID()}, []string{"test"}, []string{})
if err != nil {
t.Fatal(err)
}
err = repo.UpdateDelegations(role, []data.Key{testKey}, "")
if err != nil {
t.Fatal(err)
}
testDeepKey, err := ed25519.Create("targets/test/deep", data.ED25519Key)
if err != nil {
t.Fatal(err)
}
roleDeep, err := data.NewRole("targets/test/deep", 1, []string{testDeepKey.ID()}, []string{"test/deep"}, []string{})
if err != nil {
t.Fatal(err)
}
err = repo.UpdateDelegations(roleDeep, []data.Key{testDeepKey}, "")
if err != nil {
t.Fatal(err)
}
writeRepo(t, "/tmp/tufdelegation", repo)
}
示例3: bootstrapClient
func (r *NotaryRepository) bootstrapClient() (*tufclient.Client, error) {
remote, err := getRemoteStore(r.baseURL, r.Gun)
if err != nil {
return nil, err
}
rootJSON, err := remote.GetMeta("root", 5<<20)
if err != nil {
return nil, err
}
root := &data.Signed{}
err = json.Unmarshal(rootJSON, root)
if err != nil {
return nil, err
}
err = r.validateRoot(root)
if err != nil {
return nil, err
}
kdb := keys.NewDB()
r.tufRepo = tuf.NewTufRepo(kdb, r.signer)
err = r.tufRepo.SetRoot(root)
if err != nil {
return nil, err
}
return tufclient.NewClient(
r.tufRepo,
remote,
kdb,
), nil
}
示例4: tufList
func tufList(cmd *cobra.Command, args []string) {
if len(args) < 1 {
cmd.Usage()
fatalf("must specify a GUN")
}
gun := args[0]
kdb := keys.NewDB()
repo := tuf.NewTufRepo(kdb, nil)
remote, err := store.NewHTTPStore(
"https://notary:4443/v2/"+gun+"/_trust/tuf/",
"",
"json",
"",
)
c, err := bootstrapClient(remote, repo, kdb)
if err != nil {
return
}
err = c.Update()
if err != nil {
logrus.Error("Error updating client: ", err.Error())
return
}
if rawOutput {
for name, meta := range repo.Targets["targets"].Signed.Targets {
fmt.Println(name, " ", meta.Hashes["sha256"], " ", meta.Length)
}
} else {
for name, meta := range repo.Targets["targets"].Signed.Targets {
fmt.Println(name, " ", meta.Hashes["sha256"], " ", meta.Length)
}
}
}
示例5: tufAdd
func tufAdd(cmd *cobra.Command, args []string) {
if len(args) < 3 {
cmd.Usage()
fatalf("must specify a GUN, target, and path to target data")
}
gun := args[0]
targetName := args[1]
targetPath := args[2]
kdb := keys.NewDB()
signer := signed.NewSigner(NewCryptoService(gun))
repo := tuf.NewTufRepo(kdb, signer)
b, err := ioutil.ReadFile(targetPath)
if err != nil {
fatalf(err.Error())
}
filestore := bootstrapRepo(gun, repo)
fmt.Println("Generating metadata for target")
meta, err := data.NewFileMeta(bytes.NewBuffer(b))
if err != nil {
fatalf(err.Error())
}
fmt.Printf("Adding target \"%s\" with sha256 \"%s\" and size %d bytes.\n", targetName, meta.Hashes["sha256"], meta.Length)
_, err = repo.AddTargets("targets", data.Files{targetName: meta})
if err != nil {
fatalf(err.Error())
}
saveRepo(repo, filestore)
}
示例6: TestRotationNewSigMissing
func TestRotationNewSigMissing(t *testing.T) {
logrus.SetLevel(logrus.DebugLevel)
kdb := keys.NewDB()
signer := signed.NewEd25519()
repo := tuf.NewRepo(kdb, signer)
remote := store.NewMemoryStore(nil, nil)
cache := store.NewMemoryStore(nil, nil)
// Generate initial root key and role and add to key DB
rootKey, err := signer.Create("root", data.ED25519Key)
assert.NoError(t, err, "Error creating root key")
rootRole, err := data.NewRole("root", 1, []string{rootKey.ID()}, nil, nil)
assert.NoError(t, err, "Error creating root role")
kdb.AddKey(rootKey)
err = kdb.AddRole(rootRole)
assert.NoError(t, err, "Error adding root role to db")
// Generate new key and role. These will appear in the root.json
// but will not be added to the keyDB.
replacementKey, err := signer.Create("root", data.ED25519Key)
assert.NoError(t, err, "Error creating replacement root key")
replacementRole, err := data.NewRole("root", 1, []string{replacementKey.ID()}, nil, nil)
assert.NoError(t, err, "Error creating replacement root role")
assert.NotEqual(t, rootKey.ID(), replacementKey.ID(), "Key IDs are the same")
// Generate a new root with the replacement key and role
testRoot, err := data.NewRoot(
map[string]data.PublicKey{replacementKey.ID(): replacementKey},
map[string]*data.RootRole{"root": &replacementRole.RootRole},
false,
)
assert.NoError(t, err, "Failed to create new root")
_, ok := testRoot.Signed.Keys[rootKey.ID()]
assert.False(t, ok, "Old root key appeared in test root")
// Sign testRoot with both old and new keys
signedRoot, err := testRoot.ToSigned()
err = signed.Sign(signer, signedRoot, rootKey)
assert.NoError(t, err, "Failed to sign root")
var origKeySig bool
var replKeySig bool
for _, sig := range signedRoot.Signatures {
if sig.KeyID == rootKey.ID() {
origKeySig = true
} else if sig.KeyID == replacementKey.ID() {
replKeySig = true
}
}
assert.True(t, origKeySig, "Original root key signature not present")
assert.False(t, replKeySig, "Replacement root key signature was present and shouldn't be")
client := NewClient(repo, remote, kdb, cache)
err = client.verifyRoot("root", signedRoot, 0)
assert.Error(t, err, "Should have errored on verify as replacement signature was missing.")
}
示例7: TestInitRepo
func TestInitRepo(t *testing.T) {
ed25519 := signed.NewEd25519()
signer := signed.NewSigner(ed25519)
keyDB := keys.NewDB()
repo := initRepo(t, signer, keyDB)
writeRepo(t, "/tmp/tufrepo", repo)
}
示例8: bootstrapClient
func (r *NotaryRepository) bootstrapClient() (*tufclient.Client, error) {
var rootJSON []byte
remote, err := getRemoteStore(r.baseURL, r.gun, r.roundTrip)
if err == nil {
// if remote store successfully set up, try and get root from remote
rootJSON, err = remote.GetMeta("root", maxSize)
}
// if remote store couldn't be setup, or we failed to get a root from it
// load the root from cache (offline operation)
if err != nil {
if err, ok := err.(store.ErrMetaNotFound); ok {
// if the error was MetaNotFound then we successfully contacted
// the store and it doesn't know about the repo.
return nil, err
}
rootJSON, err = r.fileStore.GetMeta("root", maxSize)
if err != nil {
// if cache didn't return a root, we cannot proceed
return nil, store.ErrMetaNotFound{}
}
}
// can't just unmarshal into SignedRoot because validate root
// needs the root.Signed field to still be []byte for signature
// validation
root := &data.Signed{}
err = json.Unmarshal(rootJSON, root)
if err != nil {
return nil, err
}
err = r.KeyStoreManager.ValidateRoot(root, r.gun)
if err != nil {
return nil, err
}
kdb := keys.NewDB()
r.tufRepo = tuf.NewTufRepo(kdb, r.cryptoService)
signedRoot, err := data.RootFromSigned(root)
if err != nil {
return nil, err
}
err = r.tufRepo.SetRoot(signedRoot)
if err != nil {
return nil, err
}
return tufclient.NewClient(
r.tufRepo,
remote,
kdb,
r.fileStore,
), nil
}
示例9: verify
func verify(cmd *cobra.Command, args []string, output io.WriteCloser) {
if len(args) < 2 {
cmd.Usage()
fatalf("must specify a GUN and target")
}
// Reads all of the data on STDIN
//TODO (diogo): Change this to do a streaming hash
payload, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fatalf("error reading content from STDIN: %v", err)
}
//TODO (diogo): This code is copy/pasted from lookup.
gun := args[0]
targetName := args[1]
kdb := keys.NewDB()
repo := tuf.NewTufRepo(kdb, nil)
remote, err := store.NewHTTPStore(
"https://notary:4443/v2/"+gun+"/_trust/tuf/",
"",
"json",
"",
)
c, err := bootstrapClient(remote, repo, kdb)
if err != nil {
logrus.Error("Unable to setup client.")
return
}
err = c.Update()
if err != nil {
fmt.Println("Update failed")
fatalf(err.Error())
}
meta := c.TargetMeta(targetName)
if meta == nil {
logrus.Error("notary: data not present in the trusted collection.")
os.Exit(1)
}
// Create hasher and hash data
stdinHash := fmt.Sprintf("sha256:%x", sha256.Sum256(payload))
serverHash := fmt.Sprintf("sha256:%s", meta.Hashes["sha256"])
if stdinHash != serverHash {
logrus.Error("notary: data not present in the trusted collection.")
os.Exit(1)
} else {
_, _ = output.Write(payload)
output.Close()
}
return
}
示例10: download
func download(ctx *cli.Context) {
if len(ctx.Args()) < 1 {
fmt.Println("At least one target name must be provided.")
return
}
var root []byte
r := &data.Signed{}
err := json.Unmarshal(root, r)
if err != nil {
fmt.Println("Could not read initial root.json")
return
}
kdb := keys.NewDB()
repo := tuf.NewTufRepo(kdb, nil)
repo.SetRoot(r)
remote, err := store.NewHTTPStore(
ctx.String("host"),
ctx.String("meta"),
ctx.String("ext"),
ctx.String("targets"),
)
cached := store.NewFileCacheStore(remote, "/tmp/tuf")
if err != nil {
fmt.Println(err)
return
}
client := client.NewClient(repo, cached, kdb)
err = client.Update()
if err != nil {
fmt.Println(err)
return
}
filename := filepath.Base(ctx.Args()[0])
f, err := os.OpenFile(filename, os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
m := client.TargetMeta(ctx.Args()[0])
if m == nil {
fmt.Println("Requested package not found.")
return
}
err = client.DownloadTarget(f, ctx.Args()[0], m)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Requested pacakge downloaded.")
}
示例11: bootstrapRepo
func (r *NotaryRepository) bootstrapRepo() error {
fileStore, err := store.NewFilesystemStore(
r.tufRepoPath,
"metadata",
"json",
"targets",
)
if err != nil {
return err
}
kdb := keys.NewDB()
tufRepo := tuf.NewTufRepo(kdb, r.signer)
fmt.Println("Loading trusted collection.")
rootJSON, err := fileStore.GetMeta("root", 0)
if err != nil {
return err
}
root := &data.Signed{}
err = json.Unmarshal(rootJSON, root)
if err != nil {
return err
}
tufRepo.SetRoot(root)
targetsJSON, err := fileStore.GetMeta("targets", 0)
if err != nil {
return err
}
targets := &data.Signed{}
err = json.Unmarshal(targetsJSON, targets)
if err != nil {
return err
}
tufRepo.SetTargets("targets", targets)
snapshotJSON, err := fileStore.GetMeta("snapshot", 0)
if err != nil {
return err
}
snapshot := &data.Signed{}
err = json.Unmarshal(snapshotJSON, snapshot)
if err != nil {
return err
}
tufRepo.SetSnapshot(snapshot)
r.tufRepo = tufRepo
r.fileStore = fileStore
return nil
}
示例12: EmptyRepo
// EmptyRepo creates an in memory key database, crypto service
// and initializes a repo with no targets or delegations.
func EmptyRepo() (*keys.KeyDB, *tuf.Repo, signed.CryptoService) {
c := signed.NewEd25519()
kdb := keys.NewDB()
r := tuf.NewRepo(kdb, c)
for _, role := range []string{"root", "targets", "snapshot", "timestamp"} {
key, _ := c.Create(role, data.ED25519Key)
role, _ := data.NewRole(role, 1, []string{key.ID()}, nil, nil)
kdb.AddKey(key)
kdb.AddRole(role)
}
r.InitRepo(false)
return kdb, r, c
}
示例13: TestApplyChangelist
func TestApplyChangelist(t *testing.T) {
kdb := keys.NewDB()
role, err := data.NewRole("targets", 1, nil, nil, nil)
assert.NoError(t, err)
kdb.AddRole(role)
repo := tuf.NewTufRepo(kdb, nil)
err = repo.InitTargets()
assert.NoError(t, err)
hash := sha256.Sum256([]byte{})
f := &data.FileMeta{
Length: 1,
Hashes: map[string][]byte{
"sha256": hash[:],
},
}
fjson, err := json.Marshal(f)
assert.NoError(t, err)
cl := changelist.NewMemChangelist()
addChange := &changelist.TufChange{
Actn: changelist.ActionCreate,
Role: changelist.ScopeTargets,
ChangeType: "target",
ChangePath: "latest",
Data: fjson,
}
cl.Add(addChange)
err = applyChangelist(repo, cl)
assert.NoError(t, err)
assert.NotNil(t, repo.Targets["targets"].Signed.Targets["latest"])
cl.Clear("")
removeChange := &changelist.TufChange{
Actn: changelist.ActionDelete,
Role: changelist.ScopeTargets,
ChangeType: "target",
ChangePath: "latest",
Data: nil,
}
cl.Add(removeChange)
err = applyChangelist(repo, cl)
assert.NoError(t, err)
_, ok := repo.Targets["targets"].Signed.Targets["latest"]
assert.False(t, ok)
}
示例14: bootstrapRepo
func (r *NotaryRepository) bootstrapRepo() error {
kdb := keys.NewDB()
tufRepo := tuf.NewTufRepo(kdb, r.cryptoService)
logrus.Debugf("Loading trusted collection.")
rootJSON, err := r.fileStore.GetMeta("root", 0)
if err != nil {
return err
}
root := &data.SignedRoot{}
err = json.Unmarshal(rootJSON, root)
if err != nil {
return err
}
err = tufRepo.SetRoot(root)
if err != nil {
return err
}
targetsJSON, err := r.fileStore.GetMeta("targets", 0)
if err != nil {
return err
}
targets := &data.SignedTargets{}
err = json.Unmarshal(targetsJSON, targets)
if err != nil {
return err
}
tufRepo.SetTargets("targets", targets)
snapshotJSON, err := r.fileStore.GetMeta("snapshot", 0)
if err != nil {
return err
}
snapshot := &data.SignedSnapshot{}
err = json.Unmarshal(snapshotJSON, snapshot)
if err != nil {
return err
}
tufRepo.SetSnapshot(snapshot)
r.tufRepo = tufRepo
return nil
}
示例15: tufRemove
func tufRemove(cmd *cobra.Command, args []string) {
if len(args) < 2 {
cmd.Usage()
fatalf("must specify a GUN and target")
}
gun := args[0]
targetName := args[1]
kdb := keys.NewDB()
signer := signed.NewSigner(NewCryptoService(gun))
repo := tuf.NewTufRepo(kdb, signer)
fmt.Println("Removing target ", targetName, " from ", gun)
filestore := bootstrapRepo(gun, repo)
err := repo.RemoveTargets("targets", targetName)
if err != nil {
fatalf(err.Error())
}
saveRepo(repo, filestore)
}