File: zc_sas_query_params.go

package info (click to toggle)
golang-github-azure-azure-storage-blob-go 0.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,084 kB
  • sloc: makefile: 3
file content (393 lines) | stat: -rw-r--r-- 11,376 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package azblob

import (
	"errors"
	"net"
	"net/url"
	"strings"
	"time"
)

// SASVersion indicates the SAS version.
const SASVersion = ServiceVersion

type SASProtocol string

const (
	// SASProtocolHTTPS can be specified for a SAS protocol
	SASProtocolHTTPS SASProtocol = "https"

	// SASProtocolHTTPSandHTTP can be specified for a SAS protocol
	SASProtocolHTTPSandHTTP SASProtocol = "https,http"
)

// FormatTimesForSASSigning converts a time.Time to a snapshotTimeFormat string suitable for a
// SASField's StartTime or ExpiryTime fields. Returns "" if value.IsZero().
func FormatTimesForSASSigning(startTime, expiryTime, snapshotTime time.Time) (string, string, string) {
	ss := ""
	if !startTime.IsZero() {
		ss = formatSASTimeWithDefaultFormat(&startTime)
	}
	se := ""
	if !expiryTime.IsZero() {
		se = formatSASTimeWithDefaultFormat(&expiryTime)
	}
	sh := ""
	if !snapshotTime.IsZero() {
		sh = snapshotTime.Format(SnapshotTimeFormat)
	}
	return ss, se, sh
}

// SASTimeFormat represents the format of a SAS start or expiry time. Use it when formatting/parsing a time.Time.
const SASTimeFormat = "2006-01-02T15:04:05Z"                                                                    //"2017-07-27T00:00:00Z" // ISO 8601
var SASTimeFormats = []string{"2006-01-02T15:04:05.0000000Z", SASTimeFormat, "2006-01-02T15:04Z", "2006-01-02"} // ISO 8601 formats, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas for more details.

// formatSASTimeWithDefaultFormat format time with ISO 8601 in "yyyy-MM-ddTHH:mm:ssZ".
func formatSASTimeWithDefaultFormat(t *time.Time) string {
	return formatSASTime(t, SASTimeFormat) // By default, "yyyy-MM-ddTHH:mm:ssZ" is used
}

// formatSASTime format time with given format, use ISO 8601 in "yyyy-MM-ddTHH:mm:ssZ" by default.
func formatSASTime(t *time.Time, format string) string {
	if format != "" {
		return t.Format(format)
	}
	return t.Format(SASTimeFormat) // By default, "yyyy-MM-ddTHH:mm:ssZ" is used
}

// parseSASTimeString try to parse sas time string.
func parseSASTimeString(val string) (t time.Time, timeFormat string, err error) {
	for _, sasTimeFormat := range SASTimeFormats {
		t, err = time.Parse(sasTimeFormat, val)
		if err == nil {
			timeFormat = sasTimeFormat
			break
		}
	}

	if err != nil {
		err = errors.New("fail to parse time with IOS 8601 formats, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas for more details")
	}

	return
}

// https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas

// A SASQueryParameters object represents the components that make up an Azure Storage SAS' query parameters.
// You parse a map of query parameters into its fields by calling NewSASQueryParameters(). You add the components
// to a query parameter map by calling AddToValues().
// NOTE: Changing any field requires computing a new SAS signature using a XxxSASSignatureValues type.
//
// This type defines the components used by all Azure Storage resources (Containers, Blobs, Files, & Queues).
type SASQueryParameters struct {
	// All members are immutable or values so copies of this struct are goroutine-safe.
	version                    string      `param:"sv"`
	services                   string      `param:"ss"`
	resourceTypes              string      `param:"srt"`
	protocol                   SASProtocol `param:"spr"`
	startTime                  time.Time   `param:"st"`
	expiryTime                 time.Time   `param:"se"`
	snapshotTime               time.Time   `param:"snapshot"`
	ipRange                    IPRange     `param:"sip"`
	identifier                 string      `param:"si"`
	resource                   string      `param:"sr"`
	permissions                string      `param:"sp"`
	signature                  string      `param:"sig"`
	cacheControl               string      `param:"rscc"`
	contentDisposition         string      `param:"rscd"`
	contentEncoding            string      `param:"rsce"`
	contentLanguage            string      `param:"rscl"`
	contentType                string      `param:"rsct"`
	signedOid                  string      `param:"skoid"`
	signedTid                  string      `param:"sktid"`
	signedStart                time.Time   `param:"skt"`
	signedService              string      `param:"sks"`
	signedExpiry               time.Time   `param:"ske"`
	signedVersion              string      `param:"skv"`
	signedDirectoryDepth       string      `param:"sdd"`
	preauthorizedAgentObjectId string      `param:"saoid"`
	agentObjectId              string      `param:"suoid"`
	correlationId              string      `param:"scid"`
	// private member used for startTime and expiryTime formatting.
	stTimeFormat string
	seTimeFormat string
}

func (p *SASQueryParameters) PreauthorizedAgentObjectId() string {
	return p.preauthorizedAgentObjectId
}

func (p *SASQueryParameters) AgentObjectId() string {
	return p.agentObjectId
}

func (p *SASQueryParameters) SignedCorrelationId() string {
	return p.correlationId
}

func (p *SASQueryParameters) SignedTid() string {
	return p.signedTid
}

func (p *SASQueryParameters) SignedStart() time.Time {
	return p.signedStart
}

func (p *SASQueryParameters) SignedExpiry() time.Time {
	return p.signedExpiry
}

func (p *SASQueryParameters) SignedService() string {
	return p.signedService
}

func (p *SASQueryParameters) SignedVersion() string {
	return p.signedVersion
}

func (p *SASQueryParameters) SnapshotTime() time.Time {
	return p.snapshotTime
}

func (p *SASQueryParameters) Version() string {
	return p.version
}

func (p *SASQueryParameters) Services() string {
	return p.services
}
func (p *SASQueryParameters) ResourceTypes() string {
	return p.resourceTypes
}
func (p *SASQueryParameters) Protocol() SASProtocol {
	return p.protocol
}
func (p *SASQueryParameters) StartTime() time.Time {
	return p.startTime
}
func (p *SASQueryParameters) ExpiryTime() time.Time {
	return p.expiryTime
}

func (p *SASQueryParameters) IPRange() IPRange {
	return p.ipRange
}

func (p *SASQueryParameters) Identifier() string {
	return p.identifier
}

func (p *SASQueryParameters) Resource() string {
	return p.resource
}
func (p *SASQueryParameters) Permissions() string {
	return p.permissions
}

func (p *SASQueryParameters) Signature() string {
	return p.signature
}

func (p *SASQueryParameters) CacheControl() string {
	return p.cacheControl
}

func (p *SASQueryParameters) ContentDisposition() string {
	return p.contentDisposition
}

func (p *SASQueryParameters) ContentEncoding() string {
	return p.contentEncoding
}

func (p *SASQueryParameters) ContentLanguage() string {
	return p.contentLanguage
}

func (p *SASQueryParameters) ContentType() string {
	return p.contentType
}

func (p *SASQueryParameters) SignedDirectoryDepth() string {
	return p.signedDirectoryDepth
}

// IPRange represents a SAS IP range's start IP and (optionally) end IP.
type IPRange struct {
	Start net.IP // Not specified if length = 0
	End   net.IP // Not specified if length = 0
}

// String returns a string representation of an IPRange.
func (ipr *IPRange) String() string {
	if len(ipr.Start) == 0 {
		return ""
	}
	start := ipr.Start.String()
	if len(ipr.End) == 0 {
		return start
	}
	return start + "-" + ipr.End.String()
}

// NewSASQueryParameters creates and initializes a SASQueryParameters object based on the
// query parameter map's passed-in values. If deleteSASParametersFromValues is true,
// all SAS-related query parameters are removed from the passed-in map. If
// deleteSASParametersFromValues is false, the map passed-in map is unaltered.
func newSASQueryParameters(values url.Values, deleteSASParametersFromValues bool) SASQueryParameters {
	p := SASQueryParameters{}
	for k, v := range values {
		val := v[0]
		isSASKey := true
		switch strings.ToLower(k) {
		case "sv":
			p.version = val
		case "ss":
			p.services = val
		case "srt":
			p.resourceTypes = val
		case "spr":
			p.protocol = SASProtocol(val)
		case "snapshot":
			p.snapshotTime, _ = time.Parse(SnapshotTimeFormat, val)
		case "st":
			p.startTime, p.stTimeFormat, _ = parseSASTimeString(val)
		case "se":
			p.expiryTime, p.seTimeFormat, _ = parseSASTimeString(val)
		case "sip":
			dashIndex := strings.Index(val, "-")
			if dashIndex == -1 {
				p.ipRange.Start = net.ParseIP(val)
			} else {
				p.ipRange.Start = net.ParseIP(val[:dashIndex])
				p.ipRange.End = net.ParseIP(val[dashIndex+1:])
			}
		case "si":
			p.identifier = val
		case "sr":
			p.resource = val
		case "sp":
			p.permissions = val
		case "sig":
			p.signature = val
		case "rscc":
			p.cacheControl = val
		case "rscd":
			p.contentDisposition = val
		case "rsce":
			p.contentEncoding = val
		case "rscl":
			p.contentLanguage = val
		case "rsct":
			p.contentType = val
		case "skoid":
			p.signedOid = val
		case "sktid":
			p.signedTid = val
		case "skt":
			p.signedStart, _ = time.Parse(SASTimeFormat, val)
		case "ske":
			p.signedExpiry, _ = time.Parse(SASTimeFormat, val)
		case "sks":
			p.signedService = val
		case "skv":
			p.signedVersion = val
		case "sdd":
			p.signedDirectoryDepth = val
		case "saoid":
			p.preauthorizedAgentObjectId = val
		case "suoid":
			p.agentObjectId = val
		case "scid":
			p.correlationId = val
		default:
			isSASKey = false // We didn't recognize the query parameter
		}
		if isSASKey && deleteSASParametersFromValues {
			delete(values, k)
		}
	}
	return p
}

// AddToValues adds the SAS components to the specified query parameters map.
func (p *SASQueryParameters) addToValues(v url.Values) url.Values {
	if p.version != "" {
		v.Add("sv", p.version)
	}
	if p.services != "" {
		v.Add("ss", p.services)
	}
	if p.resourceTypes != "" {
		v.Add("srt", p.resourceTypes)
	}
	if p.protocol != "" {
		v.Add("spr", string(p.protocol))
	}
	if !p.startTime.IsZero() {
		v.Add("st", formatSASTime(&(p.startTime), p.stTimeFormat))
	}
	if !p.expiryTime.IsZero() {
		v.Add("se", formatSASTime(&(p.expiryTime), p.seTimeFormat))
	}
	if len(p.ipRange.Start) > 0 {
		v.Add("sip", p.ipRange.String())
	}
	if p.identifier != "" {
		v.Add("si", p.identifier)
	}
	if p.resource != "" {
		v.Add("sr", p.resource)
	}
	if p.permissions != "" {
		v.Add("sp", p.permissions)
	}
	if p.signedOid != "" {
		v.Add("skoid", p.signedOid)
		v.Add("sktid", p.signedTid)
		v.Add("skt", p.signedStart.Format(SASTimeFormat))
		v.Add("ske", p.signedExpiry.Format(SASTimeFormat))
		v.Add("sks", p.signedService)
		v.Add("skv", p.signedVersion)
	}
	if p.signature != "" {
		v.Add("sig", p.signature)
	}
	if p.cacheControl != "" {
		v.Add("rscc", p.cacheControl)
	}
	if p.contentDisposition != "" {
		v.Add("rscd", p.contentDisposition)
	}
	if p.contentEncoding != "" {
		v.Add("rsce", p.contentEncoding)
	}
	if p.contentLanguage != "" {
		v.Add("rscl", p.contentLanguage)
	}
	if p.contentType != "" {
		v.Add("rsct", p.contentType)
	}
	if p.signedDirectoryDepth != "" {
		v.Add("sdd", p.signedDirectoryDepth)
	}
	if p.preauthorizedAgentObjectId != "" {
		v.Add("saoid", p.preauthorizedAgentObjectId)
	}
	if p.agentObjectId != "" {
		v.Add("suoid", p.agentObjectId)
	}
	if p.correlationId != "" {
		v.Add("scid", p.correlationId)
	}
	return v
}

// Encode encodes the SAS query parameters into URL encoded form sorted by key.
func (p *SASQueryParameters) Encode() string {
	v := url.Values{}
	p.addToValues(v)
	return v.Encode()
}