I am trying to connect to use the Azure SDK for Golang to download files from a container online to my device and am using the connection string provided from azure to connect. For context this is running on a version of embedded Linux
I have two questions, first how do I pass a specific certificate to the azure SDK to use to connect, as currently when I connect, I get this issue
Get "https://transaction.blob.core.windows.net/transactions?comp=list&restype=container": x509: certificate signed by unknown authority
or failing that how do I generate the correct certificate to put it in /etc/ssl? Which I think is where go is looking for certificates as far as I understand.
Also second question what function from the azure sdk for go should I be using to download from a blob online if my folder structure looks like /transaction/my-libs/images/1.0.0/libimage.bin where transaction is my blob container.
func testConnection(){
Println("TESTING CONNECTION")
connStr := "..." // actual connection string hidden
serviceClient, err := azblob.NewServiceClientFromConnectionString(connStr, nil)
// crashes here <------------
//ctx := context.Background()
//container := serviceClient.NewContainerClient("transactions")
//
//_, err = container.Create(ctx, nil)
//
//blockBlob := container.NewBlockBlobClient("erebor-libraries")
//_, err = blockBlob.Download(ctx, nil)
//Open a buffer, reader, and then download!
downloadedData := &bytes.Buffer{}
reader := get.Body(RetryReaderOptions{}) // RetryReaderOptions has a lot of in-depth tuning abilities, but for the sake of simplicity, we'll omit those here.
_, err = downloadedData.ReadFrom(reader)
err = reader.Close()
if data != downloadedData.String() {
err := errors.New("downloaded data doesn't match uploaded data")
if err != nil {
return
}
}
pager := container.ListBlobsFlat(nil)
for pager.NextPage(ctx) {
resp := pager.PageResponse()
for _, v := range resp.ContainerListBlobFlatSegmentResult.Segment.BlobItems {
fmt.Println(*v.Name)
}
}
• You can use the following Azure SDK for Go command for passing a specific certificate to the Azure SDK to connect to other Azure resources by creating a service principal for it: -
‘ type ClientCertificateConfig struct {
ClientID string
CertificatePath string
CertificatePassword string
TenantID string
AuxTenants []string
AADEndpoint string
Resource string
} ‘
For more information on the creation of the client certificate and its usage, please refer to the documentation link below for more details: -
https://pkg.go.dev/github.com/Azure/go-autorest/autorest/azure/auth#ClientCertificateConfig
Also, even if your folder structure is ‘/transaction/my-libs/images/1.0.0/libimage.bin’, but the blob URL is unique with folder hierarchy mentioned in the blob URL, thus when connecting to the Azure storage account to download the blob, mention the URL in single inverted comma notation for the blob path to be specific.
Please refer to the sample code below for downloading the blobs through Azure SDK for Go: -
https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/storage/azblob#example-package
https://pkg.go.dev/github.com/Azure/azure-storage-blob-go/azblob#pkg-examples
Related
I am writing a job in golang that sets up an Azure user assigned managed identity using the Azure Go SDK, specifically github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/msi/armmsi, a Kubernetes service account using the go-client for Kubernetes k8s.io/client-go/kubernetes and then using the Azure SDK to set up a Federated Identity Credential on the new user assigned managed identity.
In order to set up a federated credential on azure I need to get the oidc issuer uri.
I know how to get it using the Azure CLI, and I can simply paste a string. But I expect this code to be running on any cluster and i would expect the issuer to change. Id rather just get the issuer from a config file on the cluster itself or through the azure sdk. I am not sure how to do that. any help...
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
....some code here to set up azure clients and Kubernetes client...
//creating a new managed identity using azure client
msi, err := azureMsiClient.CreateOrUpdate(ctx, "new-umid-resource-group", "new-umid", armmsi.Identity{Location: strPtr(`East US`)}, &armmsi.UserAssignedIdentitiesClientCreateOrUpdateOptions{})
if err != nil {
fmt.Printf("could not create a managed identity", err.Error())
return err
}
....
//creating the new service account
annotations := make(map[string]string)
annotations["azure.workload.identity/client-id"] = *msi.Properties.ClientID
annotations["azure.workload.identity/tenant-id"] = "<myazuretenantid>"
labels := make(map[string]string)
labels["azure.workload.identity/use"] = "true"
mainSA := &v1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: "myserviceaccount",
Namespace: "my-namespace",
Annotations: annotations,
Labels: labels,
},
_, err = kubeClientSet.CoreV1().ServiceAccounts("my-namespace").Create(ctx, mainSA, metav1.CreateOptions{})
if err != nil {
fmt.Println("could not create k8 service account")
return err
}
....
//creating the federated credential
aud := make([]*string, 1)
aud[0] = strPtr("api://AzureADTokenExchange")
beParms := armmsi.FederatedIdentityCredential{
Properties: &armmsi.FederatedIdentityCredentialProperties{
Audiences: aud,
Issuer: strPtr(<my cluster's OidcIssuerUri>),
Subject: strPtr(`system:serviceaccount:my-namespace:myserviceaccount`),
},
}
_, err := azureFedIdClient.CreateOrUpdate(ctx, "new-umid-resource-group","new-umid", "new-umid-fed-id", beParms, nil)
if err != nil {
fmt.Println("could not create a new federation between be auth service account and federated identity")
return err
}
How can we get the Azure storage account key from storage account name and other parameters ?
I tried to build the storage account client but it requires, storage account name and key to build the client. I want to fetch programatically storage account key using storage account name and other parameters. Equivalent Go Sample code to below Azure CLI command.
az storage account keys list --resource-group --account-name
Can you please give some pointer, how can i fetch using Go sample code ?
Thank you
To get keys for a storage account, you will need to make use of Azure SDK for Go especially armstorage`.
Here's the code sample for listing account keys:
func ExampleStorageAccountsClient_ListKeys() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
client := armstorage.NewStorageAccountsClient(arm.NewDefaultConnection(cred, nil), "<subscription ID>")
resp, err := client.ListKeys(context.Background(), "<resource group name>", "<storage account name>", nil)
if err != nil {
log.Fatalf("failed to delete account: %v", err)
}
for _, k := range resp.StorageAccountListKeysResult.Keys {
log.Printf("account key: %v", *k.KeyName)
}
}
This sample and more code examples are available here: https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/storage/armstorage/example_storageaccounts_test.go.
I am trying to upload files to azure storage container using Go SDK for Azure storage from an Azure VM which has Azure Managed Identity attached to it. I am also using Azure auth to create a ServicePrincipalToken using MSIConfig. However I am receiving an error
RESPONSE Status: 400 Authentication information is not given in the correct format. Check the value of Authorization header.
Can someone please help me understand what I am missing?
Script I have used (modified form of the example ):
// main.go
package main
import (
"log"
"fmt"
"context"
"net/url"
"strings"
"github.com/Azure/azure-storage-blob-go/azblob"
"github.com/Azure/go-autorest/autorest/azure/auth"
)
func main() {
azureServicePrincipalToken, err := auth.NewMSIConfig().ServicePrincipalToken()
if err != nil {
log.Fatal(err)
}
accountName := "<TESTSA>"
containerName := "<TESTCONTAINER>"
// Create a BlockBlobURL object to a blob in the container (we assume the container already exists).
u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/%s/readme.txt", accountName, containerName))
credential := azblob.NewTokenCredential(azureServicePrincipalToken.Token().AccessToken, nil)
if err != nil {
log.Fatal(err)
}
blockBlobURL := azblob.NewBlockBlobURL(*u, azblob.NewPipeline(credential, azblob.PipelineOptions{}))
log.Println(blockBlobURL)
ctx := context.Background() // This example uses a never-expiring context
// Perform UploadStreamToBlockBlob
bufferSize := 2 * 1024 * 1024
maxBuffers := 3
_, err = azblob.UploadStreamToBlockBlob(ctx, strings.NewReader("Hello azblob"), blockBlobURL,
azblob.UploadStreamToBlockBlobOptions{BufferSize: bufferSize, MaxBuffers: maxBuffers})
if err != nil {
log.Fatal(err)
}
}
When I execute go run main.go, I receive the following error:
2020/12/26 17:58:07 https://<TESTSA>.blob.core.windows.net/<TESTCONTAINER>/readme.txt
2020/12/26 17:58:07 write error: -> github.com/Azure/azure-storage-blob-go/azblob.newStorageError, /home/<MYUSER>/go/pkg/mod/github.com/!azure/azure-storage-blob-go#v0.12.0/azblob/zc_storage_error.go:42
===== RESPONSE ERROR (ServiceCode=) =====
Description=Authentication information is not given in the correct format. Check the value of Authorization header.
RequestId:f30c063e-901e-0046-2cb0-db4781000000
Time:2020-12-26T17:58:07.7810745Z, Details:
Code: InvalidAuthenticationInfo
PUT https://<TESTSA>.blob.core.windows.net/<TESTCONTAINER>/readme.txt?blockid=j%2BItsAdqRN6EScZ3S2r8QwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%3D%3D&comp=block&timeout=61
Authorization: REDACTED
Content-Length: [12]
User-Agent: [Azure-Storage/0.12 (go1.13.9; linux)]
X-Ms-Client-Request-Id: [21638ec4-138c-434d-4b53-d13924e51966]
X-Ms-Version: [2019-12-12]
--------------------------------------------------------------------------------
RESPONSE Status: 400 Authentication information is not given in the correct format. Check the value of Authorization header.
Content-Length: [298]
Content-Type: [application/xml]
Date: [Sat, 26 Dec 2020 17:58:07 GMT]
Server: [Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0]
X-Ms-Request-Id: [f30c063e-901e-0046-2cb0-db4781000000]
exit status 1
I have also verified with the azcli command and I was able to upload a sample txt file helloworld to the storage container without any challenge. The commands I used:
az login --identity
az storage blob upload --container-name <TESTCONTAINER> --account-name <TESTSA> --name helloworld --file helloworld --auth-mode login
Response:
Finished[#############################################################] 100.0000%
{
"etag": "\"0x8D8A9CCDD921BA7\"",
"lastModified": "2020-12-26T18:34:22+00:00"
}
Thank you.
The code sample you refer to authorizes with Shared Key and Put Blob API, but not Azure AD.
credential, err := NewSharedKeyCredential(accountName, accountKey)
If you would like to authorize with Azure AD by ServicePrincipalToken, see Azure Active Directory authentication for Go.
applicationSecret := "APPLICATION_SECRET"
spt, err := adal.NewServicePrincipalToken(
*oauthConfig,
appliationID,
applicationSecret,
resource,
callbacks...)
if err != nil {
return nil, err
}
// Acquire a new access token
err = spt.Refresh()
if (err == nil) {
token := spt.Token
}
I am trying to use Azure Golang SDK to pull the list of Azure AD users.
Few things to Note:
1. Authentication is successful. "Authorization successful." is displayed when I use below code to fetch bearer token for Azure SPN.
This is pretty much vanilla code picked from Azure-Go-SDK repo.
//GetGraphAuthorizer gets an OAuthTokenAuthorizer for graphrbac API.
func GetGraphAuthorizer(fs auth.FileSettings) (autorest.Authorizer, error) {
if graphAuthorizer != nil {
return graphAuthorizer, nil
}
var a autorest.Authorizer
var err error
a, err = getAuthorizerForResource(grantType(), Environment().GraphEndpoint, fs)
if err == nil {
// cache
graphAuthorizer = a
fmt.Println("Authorization successful.")
} else {
graphAuthorizer = nil
fmt.Println ("Authorization failed.")
}
return graphAuthorizer, err
}
Defined a wrapper on around GetGraphAuthorizer function to instantiate userClient object:
func getADUserClient(fs auth.FileSettings) graphrbac.UsersClient {
userClient := graphrbac.NewUsersClient(azure.GetTenantId(fs))
a, _ := azure.GetGraphAuthorizer(fs)
userClient.Authorizer = a
userClient.AddToUserAgent(azure.UserAgent())
return userClient
}
Then I use the token to list users in Azure AD in below function:
adUserClient := getADUserClient(fs)
// if auth failed, then it should've displayed the failure message here but prints "Authorization successful instead"
for list, err := adUserClient.ListComplete(context.Background(), ""); list.NotDone(); err = list.Next() {
if err != nil {
fmt.Print("got error while traversing User list: ", err)
}
i := list.Value()
fmt.Println(*i.DisplayName)
fmt.Println(*i.GivenName)
}
No output what so ever!!
FYI:- I have users in Azure tenant.
I have granted SPN access to Graph API.
Any help is appreciated.
Not 100% sure but for some reason I had to grant Azure SPN "Delegated" permission to:
Directory.ReadWrite.All
Groups.ReadWrite.All
Surprisingly, Once the program listed users, I removed above "Delegated" permissions off SPN and just left the Application permissions and it continues to work!
I am creating an app using Go and I am trying to start a https server using the ListenAndServeTLS function. Here is my code:
func StartServer() {
defer config.CapturePanic()
c := config.GetInstance()
serverAddress := fmt.Sprintf(":%s", c.GetConfig().ServerPort)
server := http.Server{Addr: serverAddress}
log.Info("Starting local server")
http.HandleFunc("/", login.Handler)
http.HandleFunc("/login", login.Handler)
http.HandleFunc("/settings", settings.Handler)
//cert, _ := data.Asset("my-cert.pem")
//key, _ := data.Asset("my-key.pem")
err := server.ListenAndServeTLS("my-cert.crt", "my-cert.key")
if err != nil {
log.WithError(err).Fatal("Error stopping local server")
}
}
The thing is that I would like to embed my certificate and its key inside my executable file and then pass them to the the server.ListeAndServeTLS function as a string or a byte array. However this function does not take these types of arguments. Is there another way to do this?
Note: I am aware that it is a bad practice to embed a private key inside a client application, however what I am trying to do here is just to create a config webpage that will be hosted as https://localhost:8080.
You can build your own server object and still call ListenAndServeTLS. Since your tls config has certificates, it will ignore the passed-in filenames.
I'm omitting the return on error for conciseness, please do not:
// Generate a key pair from your pem-encoded cert and key ([]byte).
cert, err := tls.X509KeyPair(<cert contents>, <key contents>)
// Construct a tls.config
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert}
// Other options
}
// Build a server:
server := http.Server{
// Other options
TLSConfig: tlsConfig,
}
// Finally: serve.
err = server.ListenAndServeTLS("", "")
In my case, I was unable to load files from disk, but did have the certificates passed in to the environment as variables ([]byte).
Adding on to Marc's answer, I had to only change the top line.
// Append signed leaf certificate and intermediate to a single
certChain := append(leaf.PublicBytes, intermediate.PublicBytes...)
// Generate a key pair from your pem-encoded cert and key ([]byte).
cert, err := tls.X509KeyPair(certChain, leaf.PrivateBytes)
...