Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ go 1.25.7
toolchain go1.26.3

require (
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1
github.com/kubernetes-csi/external-snapshotter/client/v8 v8.4.0
github.com/onsi/gomega v1.41.0
github.com/openshift/hive/apis v0.0.0-20260519181045-ab4b2490385a
Expand All @@ -17,6 +19,8 @@ require (
)

require (
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/evanphx/json-patch/v5 v5.9.11 // indirect
Expand All @@ -33,12 +37,15 @@ require (
github.com/go-openapi/swag/stringutils v0.26.0 // indirect
github.com/go-openapi/swag/typeutils v0.26.0 // indirect
github.com/go-openapi/swag/yamlutils v0.26.0 // indirect
github.com/golang-jwt/jwt/v5 v5.3.0 // indirect
github.com/google/btree v1.1.3 // indirect
github.com/google/gnostic-models v0.7.1 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/openshift/api v0.0.0-20260521125114-09730f85d883 // indirect
github.com/openshift/installer v1.4.22-ec5 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_golang v1.23.2 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
Expand All @@ -47,6 +54,7 @@ require (
github.com/x448/float16 v0.8.4 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/crypto v0.51.0 // indirect
golang.org/x/sync v0.20.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect
gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect
Expand Down
22 changes: 22 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
github.com/Azure/azure-sdk-for-go v68.0.0+incompatible h1:fcYLmCpyNYRnvJbPerq7U0hS+6+I79yEDJBqVNcqUzU=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1 h1:jHb/wfvRikGdxMXYV3QG/SzUOPYN9KEUUuC0Yd0/vC0=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1/go.mod h1:pzBXCYn05zvYIrwLgtK8Ap8QcjRg+0i76tMQdWN6wOk=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 h1:Hk5QBxZQC1jb2Fwj6mpzme37xbCDdNTxU7O9eb5+LB4=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1/go.mod h1:IYus9qsFobWIc2YVwe/WPjcnyCkPKtnHAqUYeebc8z0=
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2 h1:yz1bePFlP5Vws5+8ez6T3HWXPmwOK7Yvq8QxDBD3SKY=
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2/go.mod h1:Pa9ZNPuoNu/GztvBSKk9J1cDJW6vk/n0zLtV4mgd8N8=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY=
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs=
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk=
github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
Expand Down Expand Up @@ -68,6 +81,8 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v
github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=
Expand Down Expand Up @@ -95,6 +110,8 @@ github.com/jhump/protoreflect v1.17.0 h1:qOEr613fac2lOuTgWN4tPAtLL7fUSbuJL5X5Xum
github.com/jhump/protoreflect v1.17.0/go.mod h1:h9+vUUL38jiBzck8ck+6G/aeMX8Z4QUY/NiJPwPNi+8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRtuthU=
github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k=
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
Expand Down Expand Up @@ -137,6 +154,8 @@ github.com/openshift/installer v1.4.22-ec5 h1:NG9X2iZG5mbUVZIBhpMtMrGNK7Tbm9dDGA
github.com/openshift/installer v1.4.22-ec5/go.mod h1:PbGvWlLRbmmSsaTQBAjhXPzliz9XJAYUdXcY0t/3UiY=
github.com/openshift/velero v0.10.2-0.20260323191807-216dd62a1caf h1:idCUwNL/RfZIeS1bpUvf6LaYZJSmKCSE2GP6tc1caYI=
github.com/openshift/velero v0.10.2-0.20260323191807-216dd62a1caf/go.mod h1:vrmFMtokf4UjYmykfPvmI/xinTU3Ljz4F6JO3pLYxKs=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
Expand Down Expand Up @@ -193,6 +212,8 @@ go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
Expand All @@ -206,6 +227,7 @@ golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
Expand Down
178 changes: 178 additions & 0 deletions pkg/azblobsas/delegation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
package azblobsas

import (
"bytes"
"context"
"encoding/base64"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)

var httpDo = http.DefaultClient.Do

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: It looks like this httpDo is used only once. Probably makes sense to use http.DefaultClient.Do directly and get rid of this variable.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — it is only called once, but the var is intentional: delegation_test.go replaces httpDo with a fake to avoid real HTTP calls (see TestGetUserDelegationKey). It's the same pattern we use with var nowFunc = time.Now in the SAS package. I can add a short comment above the var if that helps clarify the intent.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No action needed.


// UserDelegationKey holds the key returned by the Azure Storage
// Get User Delegation Key API.
type UserDelegationKey struct {
SignedOID string `xml:"SignedOid"`
SignedTID string `xml:"SignedTid"`
SignedStart string `xml:"SignedStart"`
SignedExpiry string `xml:"SignedExpiry"`
SignedService string `xml:"SignedService"`
SignedVersion string `xml:"SignedVersion"`
Value string `xml:"Value"`
}

type keyInfoRequest struct {
XMLName xml.Name `xml:"KeyInfo"`
Start string `xml:"Start"`
Expiry string `xml:"Expiry"`
}

// GetUserDelegationKey calls the Azure Storage REST API to obtain a user
// delegation key signed by the AAD identity represented by bearerToken.
func GetUserDelegationKey(ctx context.Context, account, bearerToken string, start, expiry time.Time, endpoint string) (*UserDelegationKey, error) {
var host string
if endpoint != "" {
parsed, err := url.Parse(strings.TrimRight(endpoint, "/"))
if err != nil {
return nil, fmt.Errorf("invalid endpoint %q: %w", endpoint, err)
}
host = parsed.Scheme + "://" + parsed.Host
} else {
host = fmt.Sprintf("https://%s.blob.core.windows.net", account)
}

reqURL := host + "/?restype=service&comp=userdelegationkey"

body, err := xml.Marshal(keyInfoRequest{
Start: start.UTC().Format("2006-01-02T15:04:05Z"),
Expiry: expiry.UTC().Format("2006-01-02T15:04:05Z"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is strange to see this old date here hardcoded. Does it have any meaning or effect? Is it necessary?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's Go's reference time — it's how time.Format works in Go. The magic date 2006-01-02T15:04:05Z is the layout string (Mon Jan 2 15:04:05 MST 2006), not an actual hardcoded date. The output at runtime is the real current timestamp formatted as ISO 8601.

})
if err != nil {
return nil, fmt.Errorf("marshalling delegation key request: %w", err)
}

req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("creating delegation key request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+bearerToken)
req.Header.Set("x-ms-version", sasVersion)
req.Header.Set("Content-Type", "application/xml")

resp, err := httpDo(req)
if err != nil {
return nil, fmt.Errorf("calling Get User Delegation Key: %w", err)
}
defer resp.Body.Close()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Check the error from resp.Body.Close().

The deferred resp.Body.Close() call's error return value is not checked, which could silently hide cleanup failures.

🛡️ Proposed fix
-	defer resp.Body.Close()
+	defer func() {
+		if cerr := resp.Body.Close(); cerr != nil && err == nil {
+			err = fmt.Errorf("closing response body: %w", cerr)
+		}
+	}()

Alternatively, if you prefer to just log the error:

-	defer resp.Body.Close()
+	defer func() {
+		if cerr := resp.Body.Close(); cerr != nil {
+			// Log the error if needed
+		}
+	}()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
defer resp.Body.Close()
defer func() {
if cerr := resp.Body.Close(); cerr != nil && err == nil {
err = fmt.Errorf("closing response body: %w", cerr)
}
}()
🧰 Tools
🪛 golangci-lint (2.12.2)

[error] 72-72: Error return value of resp.Body.Close is not checked

(errcheck)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/azblobsas/delegation.go` at line 72, The deferred resp.Body.Close() call
in delegation.go currently ignores its error; wrap the defer in an anonymous
function that calls resp.Body.Close(), captures its returned error, and handle
it (return it up the stack or log it via the existing logger) so cleanup
failures aren’t swallowed—look for the resp variable and the line with defer
resp.Body.Close() and replace it with a deferred closure that checks and handles
the Close() error.


respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading delegation key response: %w", err)
}

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Get User Delegation Key returned %d: %s", resp.StatusCode, string(respBody))
}

var key UserDelegationKey
if err := xml.Unmarshal(respBody, &key); err != nil {
return nil, fmt.Errorf("parsing delegation key response: %w", err)
}

return &key, nil
}

// UserDelegationSASOptions holds parameters for generating a User Delegation SAS URL.
type UserDelegationSASOptions struct {
Account string
Container string
Blob string
DelegationKey *UserDelegationKey
Expiry time.Duration
Endpoint string
}

// GenerateUserDelegationSASBlobURL creates a User Delegation SAS URL with
// read permission for a single blob.
func GenerateUserDelegationSASBlobURL(opts UserDelegationSASOptions) (string, error) {
if opts.Account == "" || opts.Container == "" || opts.Blob == "" {
return "", fmt.Errorf("account, container, and blob are required")
}
if opts.DelegationKey == nil {
return "", fmt.Errorf("delegation key is required")
}

keyBytes, err := base64.StdEncoding.DecodeString(opts.DelegationKey.Value)
if err != nil {
return "", fmt.Errorf("invalid base64 delegation key: %w", err)
}

now := nowFunc().UTC()
expiry := opts.Expiry
if expiry <= 0 {
expiry = DefaultSASExpiry
}
expiryTime := now.Add(expiry)

signedStart := now.Format("2006-01-02T15:04:05Z")
signedExpiry := expiryTime.Format("2006-01-02T15:04:05Z")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is strange to see this old date here hardcoded. Does it have any meaning or effect?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Answered above — same Go reference time layout.

canonicalizedResource := fmt.Sprintf("/blob/%s/%s/%s", opts.Account, opts.Container, opts.Blob)

// String to sign for User Delegation SAS, version 2020-12-06+
// https://learn.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas#version-2020-12-06-and-later
stringToSign := strings.Join([]string{
"r", // signedPermissions
signedStart, // signedStart
signedExpiry, // signedExpiry
canonicalizedResource, // canonicalizedResource
opts.DelegationKey.SignedOID, // signedKeyObjectId
opts.DelegationKey.SignedTID, // signedKeyTenantId
opts.DelegationKey.SignedStart, // signedKeyStart
opts.DelegationKey.SignedExpiry, // signedKeyExpiry
opts.DelegationKey.SignedService, // signedKeyService
opts.DelegationKey.SignedVersion, // signedKeyVersion
"", // signedAuthorizedUserObjectId
"", // signedUnauthorizedUserObjectId
"", // signedCorrelationId
"", // signedIP
"https", // signedProtocol
sasVersion, // signedVersion
"b", // signedResource (blob)
"", // signedSnapshotTime
"", // signedEncryptionScope
"", // rscc (Cache-Control)
"", // rscd (Content-Disposition)
"", // rsce (Content-Encoding)
"", // rscl (Content-Language)
"", // rsct (Content-Type)
}, "\n")

sig := hmacSHA256(keyBytes, []byte(stringToSign))
signature := base64.StdEncoding.EncodeToString(sig)

host, scheme := buildHostScheme(opts.Account, opts.Endpoint)

params := url.Values{}
params.Set("sv", sasVersion)
params.Set("st", signedStart)
params.Set("se", signedExpiry)
params.Set("sr", "b")
params.Set("sp", "r")
params.Set("spr", "https")
params.Set("skoid", opts.DelegationKey.SignedOID)
params.Set("sktid", opts.DelegationKey.SignedTID)
params.Set("skt", opts.DelegationKey.SignedStart)
params.Set("ske", opts.DelegationKey.SignedExpiry)
params.Set("sks", opts.DelegationKey.SignedService)
params.Set("skv", opts.DelegationKey.SignedVersion)
params.Set("sig", signature)

blobPath := "/" + uriEncode(opts.Container) + "/" + uriEncode(opts.Blob)
return fmt.Sprintf("%s://%s%s?%s", scheme, host, blobPath, params.Encode()), nil
}
Loading