Skip to content

Commit

Permalink
initial change to keyvault tests . (#282)
Browse files Browse the repository at this point in the history
* initial.

* Initial version

* Initial version

* Initial version

* Removed unused code.
  • Loading branch information
mayelms authored Aug 10, 2020
1 parent 8a3b761 commit ff3a409
Show file tree
Hide file tree
Showing 8 changed files with 322 additions and 44 deletions.
57 changes: 57 additions & 0 deletions keyvault/examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Using GO Keyvault SDK with Managed identities

In order to run examples/go-keyvault-msi-example.go, follow these steps:
- Create a keyvaul and a secret
- Create a managed identity
- Set the environment variables
- go run examples/go-keyvault-msi-example.go

## Create a vault and a secret
- Logon to the azure portal in to your subscription and create an user assigned managed id.
- Create a vault, a secret and set a value for that secret
- Take a note of the keyvault name and set the **KVAULT_NAME** environment variable.
- Take a note of the secret name and set the **KVAULT_SECRET_NAME** environment variable.

## Create a managed identity
- Logon to the azure portal in to your subscription and create an user assigned managed id.
![create-user-assigned-id](images/gosdk-msid-02.png)
- Assign a contributor role to the managed identity.
![msid-role-assignemnt-contributor](images/gosdk-msid-04.png)
- Assign managed id to VM.
![add-id-to-vm](images/gosdk-msid-01.png)
- Copy client ID and assign is to the environment **AZURE_CLIENT_ID** variable.
![msid-client-id](images/gosdk-msid-03.png)

## Set the environment variables
```code
AZURE_TENANT_ID: Your Azure tenant ID
AZURE_CLIENT_ID: Your Azure client ID. This will be an app ID from your AAD.
KVAULT_NAME: The name of your vault (just the name, not the full URL/path)
KVAULT_SECRET_NAME to the secret's name.
**Important note:** Do NOT set AZURE_CLIENT_SECRET. This example uses Managed identities.
```

## Run examples/go-keyvault-msi-example.go
On your terminal where you have the environment variables set:

```code
$cd ~/go/src/azure-sdk-for-go-samples/keyvault/examples
$go run go-keyvault-msi-example.go
KVAULT_NAME: mekv01
Listing secret names in keyvault:
string
mesecret
newsecret
KVAULT_SECRET_NAME: mesecret
KVAULT_SECRET Value: mesecretvalue
Setting 'newsecret' to 'newvalue'
added/updated: https://mekv01.vault.azure.net/secrets/newsecret/13cd55828aaf40e990b970c3c4cd07cf
Listing secret names in keyvault:
string
mesecret
newsecret
```
163 changes: 163 additions & 0 deletions keyvault/examples/go-keyvault-msi-example.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
package main

// Copyright (c) Microsoft and contributors. All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
//
//
// You need to set four environment variables before using the app:
// AZURE_TENANT_ID: Your Azure tenant ID
// AZURE_CLIENT_ID: Your Azure client ID. This will be an app ID from your AAD.
// KVAULT_NAME: The name of your vault (just the name, not the full URL/path)
//
// Optional command line argument:
// If you have a secret already, set KVAULT_SECRET_NAME to the secret's name.
//
// NOTE: Do NOT set AZURE_CLIENT_SECRET. This example uses Managed identities.
// The README.md provides more information.
//
//

import (
"context"
"fmt"
"log"
"net/http"
"net/http/httputil"
"os"
"path"

"github.com/Azure/azure-sdk-for-go/profiles/latest/keyvault/keyvault"
kvauth "github.com/Azure/azure-sdk-for-go/services/keyvault/auth"
"github.com/Azure/go-autorest/autorest"
)

var (
vaultName string
secretName string
)


func listSecrets(basicClient keyvault.BaseClient) {
secretList, err := basicClient.GetSecrets(context.Background(), "https://"+vaultName+".vault.azure.net", nil)
if err != nil {
fmt.Printf("unable to get list of secrets: %v\n", err)
os.Exit(1)
}

// group by ContentType
secWithType := make(map[string][]string)
secWithoutType := make([]string, 1)
for _, secret := range secretList.Values() {
if secret.ContentType != nil {
_, exists := secWithType[*secret.ContentType]
if exists {
secWithType[*secret.ContentType] = append(secWithType[*secret.ContentType], path.Base(*secret.ID))
} else {
tempSlice := make([]string, 1)
tempSlice[0] = path.Base(*secret.ID)
secWithType[*secret.ContentType] = tempSlice
}
} else {
secWithoutType = append(secWithoutType, path.Base(*secret.ID))
}
}

for k, v := range secWithType {
fmt.Println(k)
for _, sec := range v {
fmt.Println(sec)
}
}
for _, wov := range secWithoutType {
fmt.Println(wov)
}
}

func getSecret(basicClient keyvault.BaseClient, secname string) {
secretResp, err := basicClient.GetSecret(context.Background(), "https://"+vaultName+".vault.azure.net", secname, "")
if err != nil {
fmt.Printf("unable to get value for secret: %v\n", err)
os.Exit(1)
}
fmt.Println(*secretResp.Value)
}

func createUpdateSecret(basicClient keyvault.BaseClient, secname, secvalue string) {
var secParams keyvault.SecretSetParameters
secParams.Value = &secvalue
newBundle, err := basicClient.SetSecret(context.Background(), "https://"+vaultName+".vault.azure.net", secname, secParams)
if err != nil {
fmt.Printf("unable to add/update secret: %v\n", err)
os.Exit(1)
}
fmt.Println("added/updated: " + *newBundle.ID)
}

func deleteSecret(basicClient keyvault.BaseClient, secname string) {
_, err := basicClient.DeleteSecret(context.Background(), "https://"+vaultName+".vault.azure.net", secname)
if err != nil {
fmt.Printf("error deleting secret: %v\n", err)
os.Exit(1)
}
fmt.Println(secname + " deleted successfully")
}

func logRequest() autorest.PrepareDecorator {
return func(p autorest.Preparer) autorest.Preparer {
return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) {
r, err := p.Prepare(r)
if err != nil {
log.Println(err)
}
dump, _ := httputil.DumpRequestOut(r, true)
log.Println(string(dump))
return r, err
})
}
}

func logResponse() autorest.RespondDecorator {
return func(p autorest.Responder) autorest.Responder {
return autorest.ResponderFunc(func(r *http.Response) error {
err := p.Respond(r)
if err != nil {
log.Println(err)
}
dump, _ := httputil.DumpResponse(r, true)
log.Println(string(dump))
return err
})
}
}

func main() {
vaultName = os.Getenv("KVAULT_NAME")
fmt.Printf("KVAULT_NAME: %s\n", vaultName)

authorizer, err := kvauth.NewAuthorizerFromEnvironment()
if err != nil {
fmt.Printf("unable to create vault authorizer: %v\n", err)
os.Exit(1)
}

basicClient := keyvault.New()
basicClient.Authorizer = authorizer

fmt.Println("\nListing secret names in keyvault:")
listSecrets(basicClient)

if secretName = os.Getenv("KVAULT_SECRET_NAME"); secretName != "" {
fmt.Printf("KVAULT_SECRET_NAME: %s\n", secretName)
fmt.Print("KVAULT_SECRET Value: ")
getSecret(basicClient, secretName)
} else {
fmt.Println("KVAULT_SECRET_NAME not set.\n")
}

fmt.Println("Setting 'newsecret' to 'newvalue'")
createUpdateSecret(basicClient, "newsecret", "newvalue")
fmt.Println("\nListing secret names in keyvault:")
listSecrets(basicClient)
}
Binary file added keyvault/examples/images/gosdk-msid-01.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added keyvault/examples/images/gosdk-msid-02.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added keyvault/examples/images/gosdk-msid-03.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added keyvault/examples/images/gosdk-msid-04.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
86 changes: 42 additions & 44 deletions keyvault/keyvault_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,76 +6,74 @@
package keyvault

import (
"context"
"flag"
"fmt"
"log"
"os"
"testing"

"github.com/marstr/randname"

"github.com/Azure-Samples/azure-sdk-for-go-samples/internal/config"
"github.com/Azure-Samples/azure-sdk-for-go-samples/internal/util"
"github.com/Azure-Samples/azure-sdk-for-go-samples/resources"
)

var (
kvName = randname.GenerateWithPrefix("vault-sample-go-", 5)
keyName = randname.GenerateWithPrefix("key-sample-go-", 5)
)

// TestMain sets up the environment and initiates tests.
func TestMain(m *testing.M) {
var err error
err = config.ParseEnvironment()
func addLocalEnvAndParse() error {
// parse env at top-level (also controls dotenv load)
err := config.ParseEnvironment()
if err != nil {
log.Fatalf("failed to parse env: %+v", err)
return fmt.Errorf("failed to add top-level env: %+v", err)
}

err = config.AddFlags()
return nil
}

func addLocalFlagsAndParse() error {
// add top-level flags
err := config.AddFlags()
if err != nil {
log.Fatalf("failed to parse flags: %+v", err)
return fmt.Errorf("failed to add top-level flags: %+v", err)
}
flag.Parse()

code := m.Run()
os.Exit(code)
// parse all flags
flag.Parse()
return nil
}

func ExampleSetVaultPermissions() {
var groupName = config.GenerateGroupName("KeyVault")
config.SetGroupName(groupName)

ctx := context.Background()
defer resources.Cleanup(ctx)

_, err := resources.CreateGroup(ctx, config.GroupName())
func setup() error {
var err error
err = addLocalEnvAndParse()
if err != nil {
util.LogAndPanic(err)
return err
}
util.PrintAndLog("resource group created")

_, err = CreateVault(ctx, kvName)
err = addLocalFlagsAndParse()
if err != nil {
util.LogAndPanic(err)
return err
}
util.PrintAndLog("vault created")

_, err = SetVaultPermissions(ctx, kvName)
return nil
}

func teardown() error {
return nil
}

// TestMain sets up the environment and initiates tests.
func TestMain(m *testing.M) {
var err error
var code int

err = setup()
if err != nil {
util.LogAndPanic(err)
log.Fatalf("could not set up environment: %+v", err)
}
util.PrintAndLog("set vault permissions")

_, err = CreateKey(ctx, kvName, keyName)
code = m.Run()

err = teardown()
if err != nil {
util.LogAndPanic(err)
log.Fatalf(
"could not tear down environment: %v\n; original exit code: %v\n",
err, code)
}
util.PrintAndLog("created key")

// Output:
// resource group created
// vault created
// set vault permissions
// created key
os.Exit(code)
}
Loading

0 comments on commit ff3a409

Please sign in to comment.