本文整理汇总了Golang中github.com/hashicorp/uuid.GenerateUUID函数的典型用法代码示例。如果您正苦于以下问题:Golang GenerateUUID函数的具体用法?Golang GenerateUUID怎么用?Golang GenerateUUID使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了GenerateUUID函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: pathCredsCreateRead
func (b *backend) pathCredsCreateRead(
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
name := data.Get("name").(string)
// Get the role
role, err := getRole(req.Storage, name)
if err != nil {
return nil, err
}
if role == nil {
return logical.ErrorResponse(fmt.Sprintf("Unknown role: %s", name)), nil
}
displayName := req.DisplayName
username := fmt.Sprintf("vault_%s_%s_%s_%d", name, displayName, strings.Replace(uuid.GenerateUUID(), "-", "_", -1), time.Now().Unix())
password := uuid.GenerateUUID()
// Get our connection
session, err := b.DB(req.Storage)
if err != nil {
return nil, err
}
// Execute each query
for _, query := range splitSQL(role.CreationCQL) {
err = session.Query(substQuery(query, map[string]string{
"username": username,
"password": password,
})).Exec()
if err != nil {
for _, query := range splitSQL(role.RollbackCQL) {
session.Query(substQuery(query, map[string]string{
"username": username,
"password": password,
})).Exec()
}
return nil, err
}
}
// Return the secret
resp := b.Secret(SecretCredsType).Response(map[string]interface{}{
"username": username,
"password": password,
}, map[string]interface{}{
"username": username,
"role": name,
})
resp.Secret.TTL = role.Lease
resp.Secret.GracePeriod = role.LeaseGracePeriod
return resp, nil
}
示例2: TestRouter_Mount
func TestRouter_Mount(t *testing.T) {
r := NewRouter()
_, barrier, _ := mockBarrier(t)
view := NewBarrierView(barrier, "logical/")
n := &NoopBackend{}
err := r.Mount(n, "prod/aws/", &MountEntry{UUID: uuid.GenerateUUID()}, view)
if err != nil {
t.Fatalf("err: %v", err)
}
err = r.Mount(n, "prod/aws/", &MountEntry{UUID: uuid.GenerateUUID()}, view)
if !strings.Contains(err.Error(), "cannot mount under existing mount") {
t.Fatalf("err: %v", err)
}
if path := r.MatchingMount("prod/aws/foo"); path != "prod/aws/" {
t.Fatalf("bad: %s", path)
}
if v := r.MatchingStorageView("prod/aws/foo"); v != view {
t.Fatalf("bad: %s", v)
}
if path := r.MatchingMount("stage/aws/foo"); path != "" {
t.Fatalf("bad: %s", path)
}
if v := r.MatchingStorageView("stage/aws/foo"); v != nil {
t.Fatalf("bad: %s", v)
}
req := &logical.Request{
Path: "prod/aws/foo",
}
resp, err := r.Route(req)
if err != nil {
t.Fatalf("err: %v", err)
}
if resp != nil {
t.Fatalf("bad: %v", resp)
}
// Verify the path
if len(n.Paths) != 1 || n.Paths[0] != "foo" {
t.Fatalf("bad: %v", n.Paths)
}
}
示例3: TestRadix_HugeTxn
func TestRadix_HugeTxn(t *testing.T) {
r := New()
// Insert way more nodes than the cache can fit
txn1 := r.Txn()
var expect []string
for i := 0; i < defaultModifiedCache*100; i++ {
gen := uuid.GenerateUUID()
txn1.Insert([]byte(gen), i)
expect = append(expect, gen)
}
r = txn1.Commit()
sort.Strings(expect)
// Collect the output, should be sorted
var out []string
fn := func(k []byte, v interface{}) bool {
out = append(out, string(k))
return false
}
r.Root().Walk(fn)
// Verify the match
if len(out) != len(expect) {
t.Fatalf("length mis-match: %d vs %d", len(out), len(expect))
}
for i := 0; i < len(out); i++ {
if out[i] != expect[i] {
t.Fatalf("mis-match: %v %v", out[i], expect[i])
}
}
}
示例4: TestCubbyholeBackend_Delete
func TestCubbyholeBackend_Delete(t *testing.T) {
b := testCubbyholeBackend()
req := logical.TestRequest(t, logical.WriteOperation, "foo")
req.Data["raw"] = "test"
storage := req.Storage
clientToken := uuid.GenerateUUID()
req.ClientToken = clientToken
if _, err := b.HandleRequest(req); err != nil {
t.Fatalf("err: %v", err)
}
req = logical.TestRequest(t, logical.DeleteOperation, "foo")
req.Storage = storage
req.ClientToken = clientToken
resp, err := b.HandleRequest(req)
if err != nil {
t.Fatalf("err: %v", err)
}
if resp != nil {
t.Fatalf("bad: %v", resp)
}
req = logical.TestRequest(t, logical.ReadOperation, "foo")
req.Storage = storage
req.ClientToken = clientToken
resp, err = b.HandleRequest(req)
if err != nil {
t.Fatalf("err: %v", err)
}
if resp != nil {
t.Fatalf("bad: %v", resp)
}
}
示例5: TestCubbyholeBackend_Read
func TestCubbyholeBackend_Read(t *testing.T) {
b := testCubbyholeBackend()
req := logical.TestRequest(t, logical.WriteOperation, "foo")
req.Data["raw"] = "test"
storage := req.Storage
clientToken := uuid.GenerateUUID()
req.ClientToken = clientToken
if _, err := b.HandleRequest(req); err != nil {
t.Fatalf("err: %v", err)
}
req = logical.TestRequest(t, logical.ReadOperation, "foo")
req.Storage = storage
req.ClientToken = clientToken
resp, err := b.HandleRequest(req)
if err != nil {
t.Fatalf("err: %v", err)
}
expected := &logical.Response{
Data: map[string]interface{}{
"raw": "test",
},
}
if !reflect.DeepEqual(resp, expected) {
t.Fatalf("bad response.\n\nexpected: %#v\n\nGot: %#v", expected, resp)
}
}
示例6: TestExpiration_RevokeByToken
func TestExpiration_RevokeByToken(t *testing.T) {
exp := mockExpiration(t)
noop := &NoopBackend{}
_, barrier, _ := mockBarrier(t)
view := NewBarrierView(barrier, "logical/")
exp.router.Mount(noop, "prod/aws/", &MountEntry{UUID: uuid.GenerateUUID()}, view)
paths := []string{
"prod/aws/foo",
"prod/aws/sub/bar",
"prod/aws/zip",
}
for _, path := range paths {
req := &logical.Request{
Operation: logical.ReadOperation,
Path: path,
ClientToken: "foobarbaz",
}
resp := &logical.Response{
Secret: &logical.Secret{
LeaseOptions: logical.LeaseOptions{
TTL: 20 * time.Millisecond,
},
},
Data: map[string]interface{}{
"access_key": "xyz",
"secret_key": "abcd",
},
}
_, err := exp.Register(req, resp)
if err != nil {
t.Fatalf("err: %v", err)
}
}
// Should nuke all the keys
if err := exp.RevokeByToken("foobarbaz"); err != nil {
t.Fatalf("err: %v", err)
}
if len(noop.Requests) != 3 {
t.Fatalf("Bad: %v", noop.Requests)
}
for _, req := range noop.Requests {
if req.Operation != logical.RevokeOperation {
t.Fatalf("Bad: %v", req)
}
}
expect := []string{
"foo",
"sub/bar",
"zip",
}
sort.Strings(noop.Paths)
sort.Strings(expect)
if !reflect.DeepEqual(noop.Paths, expect) {
t.Fatalf("bad: %v", noop.Paths)
}
}
示例7: mockTokenStore
func mockTokenStore(t *testing.T) (*Core, *TokenStore, string) {
c, _, root := TestCoreUnsealed(t)
me := &MountEntry{
Path: "token/",
Type: "token",
Description: "token based credentials",
}
me.UUID = uuid.GenerateUUID()
view := NewBarrierView(c.barrier, credentialBarrierPrefix+me.UUID+"/")
tokenstore, _ := c.newCredentialBackend("token", c.mountEntrySysView(me), view, nil)
ts := tokenstore.(*TokenStore)
router := NewRouter()
router.Mount(ts, "auth/token/", &MountEntry{UUID: ""}, ts.view)
subview := c.systemBarrierView.SubView(expirationSubPath)
logger := log.New(os.Stderr, "", log.LstdFlags)
exp := NewExpirationManager(router, subview, ts, logger)
ts.SetExpirationManager(exp)
return c, ts, root
}
示例8: TestRouter_Untaint
func TestRouter_Untaint(t *testing.T) {
r := NewRouter()
_, barrier, _ := mockBarrier(t)
view := NewBarrierView(barrier, "logical/")
n := &NoopBackend{}
err := r.Mount(n, "prod/aws/", &MountEntry{UUID: uuid.GenerateUUID()}, view)
if err != nil {
t.Fatalf("err: %v", err)
}
err = r.Taint("prod/aws/")
if err != nil {
t.Fatalf("err: %v", err)
}
err = r.Untaint("prod/aws/")
if err != nil {
t.Fatalf("err: %v", err)
}
req := &logical.Request{
Operation: logical.ReadOperation,
Path: "prod/aws/foo",
}
_, err = r.Route(req)
if err != nil {
t.Fatalf("err: %v", err)
}
}
示例9: TestRouter_LoginPath
func TestRouter_LoginPath(t *testing.T) {
r := NewRouter()
_, barrier, _ := mockBarrier(t)
view := NewBarrierView(barrier, "auth/")
n := &NoopBackend{
Login: []string{
"login",
"oauth/*",
},
}
err := r.Mount(n, "auth/foo/", &MountEntry{UUID: uuid.GenerateUUID()}, view)
if err != nil {
t.Fatalf("err: %v", err)
}
type tcase struct {
path string
expect bool
}
tcases := []tcase{
{"random", false},
{"auth/foo/bar", false},
{"auth/foo/login", true},
{"auth/foo/oauth", false},
{"auth/foo/oauth/redirect", true},
}
for _, tc := range tcases {
out := r.LoginPath(tc.path)
if out != tc.expect {
t.Fatalf("bad: path: %s expect: %v got %v", tc.path, tc.expect, out)
}
}
}
示例10: enableCredential
// enableCredential is used to enable a new credential backend
func (c *Core) enableCredential(entry *MountEntry) error {
// Ensure we end the path in a slash
if !strings.HasSuffix(entry.Path, "/") {
entry.Path += "/"
}
// Ensure there is a name
if entry.Path == "/" {
return fmt.Errorf("backend path must be specified")
}
c.authLock.Lock()
defer c.authLock.Unlock()
// Look for matching name
for _, ent := range c.auth.Entries {
switch {
// Existing is oauth/github/ new is oauth/ or
// existing is oauth/ and new is oauth/github/
case strings.HasPrefix(ent.Path, entry.Path):
fallthrough
case strings.HasPrefix(entry.Path, ent.Path):
return logical.CodedError(409, "path is already in use")
}
}
// Ensure the token backend is a singleton
if entry.Type == "token" {
return fmt.Errorf("token credential backend cannot be instantiated")
}
// Generate a new UUID and view
entry.UUID = uuid.GenerateUUID()
view := NewBarrierView(c.barrier, credentialBarrierPrefix+entry.UUID+"/")
// Create the new backend
backend, err := c.newCredentialBackend(entry.Type, c.mountEntrySysView(entry), view, nil)
if err != nil {
return err
}
// Update the auth table
newTable := c.auth.ShallowClone()
newTable.Entries = append(newTable.Entries, entry)
if err := c.persistAuth(newTable); err != nil {
return errors.New("failed to update auth table")
}
c.auth = newTable
// Mount the backend
path := credentialRoutePrefix + entry.Path
if err := c.router.Mount(backend, path, entry, view); err != nil {
return err
}
c.logger.Printf("[INFO] core: enabled credential backend '%s' type: %s",
entry.Path, entry.Type)
return nil
}
示例11: requiredMountTable
// requiredMountTable() creates a mount table with entries required
// to be available
func requiredMountTable() *MountTable {
table := &MountTable{}
cubbyholeMount := &MountEntry{
Path: "cubbyhole/",
Type: "cubbyhole",
Description: "per-token private secret storage",
UUID: uuid.GenerateUUID(),
}
sysMount := &MountEntry{
Path: "sys/",
Type: "system",
Description: "system endpoints used for control, policy and debugging",
UUID: uuid.GenerateUUID(),
}
table.Entries = append(table.Entries, cubbyholeMount)
table.Entries = append(table.Entries, sysMount)
return table
}
示例12: defaultAuthTable
// defaultAuthTable creates a default auth table
func defaultAuthTable() *MountTable {
table := &MountTable{}
tokenAuth := &MountEntry{
Path: "token/",
Type: "token",
Description: "token based credentials",
UUID: uuid.GenerateUUID(),
}
table.Entries = append(table.Entries, tokenAuth)
return table
}
示例13: defaultMountTable
// defaultMountTable creates a default mount table
func defaultMountTable() *MountTable {
table := &MountTable{}
genericMount := &MountEntry{
Path: "secret/",
Type: "generic",
Description: "generic secret storage",
UUID: uuid.GenerateUUID(),
}
table.Entries = append(table.Entries, genericMount)
table.Entries = append(table.Entries, requiredMountTable().Entries...)
return table
}
示例14: NewSalt
// NewSalt creates a new salt based on the configuration
func NewSalt(view logical.Storage, config *Config) (*Salt, error) {
// Setup the configuration
if config == nil {
config = &Config{}
}
if config.Location == "" {
config.Location = DefaultLocation
}
if config.HashFunc == nil {
config.HashFunc = SHA256Hash
}
// Create the salt
s := &Salt{
config: config,
}
// Look for the salt
raw, err := view.Get(config.Location)
if err != nil {
return nil, fmt.Errorf("failed to read salt: %v", err)
}
// Restore the salt if it exists
if raw != nil {
s.salt = string(raw.Value)
}
// Generate a new salt if necessary
if s.salt == "" {
s.salt = uuid.GenerateUUID()
s.generated = true
if view != nil {
raw := &logical.StorageEntry{
Key: config.Location,
Value: []byte(s.salt),
}
if err := view.Put(raw); err != nil {
return nil, fmt.Errorf("failed to persist salt: %v", err)
}
}
}
if config.HMAC != nil {
if len(config.HMACType) == 0 {
return nil, fmt.Errorf("HMACType must be defined")
}
s.hmacType = config.HMACType
}
return s, nil
}
示例15: mount
// Mount is used to mount a new backend to the mount table.
func (c *Core) mount(me *MountEntry) error {
// Ensure we end the path in a slash
if !strings.HasSuffix(me.Path, "/") {
me.Path += "/"
}
// Prevent protected paths from being mounted
for _, p := range protectedMounts {
if strings.HasPrefix(me.Path, p) {
return logical.CodedError(403, fmt.Sprintf("cannot mount '%s'", me.Path))
}
}
// Do not allow more than one instance of a singleton mount
for _, p := range singletonMounts {
if me.Type == p {
return logical.CodedError(403, fmt.Sprintf("Cannot mount more than one instance of '%s'", me.Type))
}
}
// Verify there is no conflicting mount
if match := c.router.MatchingMount(me.Path); match != "" {
return logical.CodedError(409, fmt.Sprintf("existing mount at %s", match))
}
c.mountsLock.Lock()
defer c.mountsLock.Unlock()
// Generate a new UUID and view
me.UUID = uuid.GenerateUUID()
view := NewBarrierView(c.barrier, backendBarrierPrefix+me.UUID+"/")
backend, err := c.newLogicalBackend(me.Type, c.mountEntrySysView(me), view, nil)
if err != nil {
return err
}
// Update the mount table
newTable := c.mounts.ShallowClone()
newTable.Entries = append(newTable.Entries, me)
if err := c.persistMounts(newTable); err != nil {
return errors.New("failed to update mount table")
}
c.mounts = newTable
// Mount the backend
if err := c.router.Mount(backend, me.Path, me, view); err != nil {
return err
}
c.logger.Printf("[INFO] core: mounted '%s' type: %s", me.Path, me.Type)
return nil
}