forked from Azure/azure-service-bus-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
namespace.go
258 lines (221 loc) · 7.5 KB
/
namespace.go
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
package servicebus
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
import (
"context"
"crypto/tls"
"fmt"
"runtime"
"strings"
"github.com/Azure/azure-amqp-common-go/v3/aad"
"github.com/Azure/azure-amqp-common-go/v3/auth"
"github.com/Azure/azure-amqp-common-go/v3/cbs"
"github.com/Azure/azure-amqp-common-go/v3/conn"
"github.com/Azure/azure-amqp-common-go/v3/sas"
"github.com/Azure/go-amqp"
"github.com/Azure/go-autorest/autorest/azure"
"golang.org/x/net/websocket"
)
const (
// banner = `
// _____ _ ____
// / ___/___ ______ __(_)________ / __ )__ _______
// \__ \/ _ \/ ___/ | / / // ___/ _ \ / __ / / / / ___/
// ___/ / __/ / | |/ / // /__/ __/ / /_/ / /_/ (__ )
///____/\___/_/ |___/_/ \___/\___/ /_____/\__,_/____/
//`
// Version is the semantic version number
Version = "0.10.0"
rootUserAgent = "/golang-service-bus"
)
type (
// Namespace provides a simplified facade over the AMQP implementation of Azure Service Bus and is the entry point
// for using Queues, Topics and Subscriptions
Namespace struct {
Name string
Suffix string
TokenProvider auth.TokenProvider
Environment azure.Environment
tlsConfig *tls.Config
userAgent string
useWebSocket bool
}
// NamespaceOption provides structure for configuring a new Service Bus namespace
NamespaceOption func(h *Namespace) error
)
const (
serviceBusResourceURI = "https://servicebus.azure.net/"
)
// NamespaceWithConnectionString configures a namespace with the information provided in a Service Bus connection string
func NamespaceWithConnectionString(connStr string) NamespaceOption {
return func(ns *Namespace) error {
parsed, err := conn.ParsedConnectionFromStr(connStr)
if err != nil {
return err
}
if parsed.Namespace != "" {
ns.Name = parsed.Namespace
}
if parsed.Suffix != "" {
ns.Suffix = parsed.Suffix
}
provider, err := sas.NewTokenProvider(sas.TokenProviderWithKey(parsed.KeyName, parsed.Key))
if err != nil {
return err
}
ns.TokenProvider = provider
return nil
}
}
// NamespaceWithTLSConfig appends to the TLS config.
func NamespaceWithTLSConfig(tlsConfig *tls.Config) NamespaceOption {
return func(ns *Namespace) error {
ns.tlsConfig = tlsConfig
return nil
}
}
// NamespaceWithUserAgent appends to the root user-agent value.
func NamespaceWithUserAgent(userAgent string) NamespaceOption {
return func(ns *Namespace) error {
ns.userAgent = userAgent
return nil
}
}
// NamespaceWithWebSocket configures the namespace and all entities to use wss:// rather than amqps://
func NamespaceWithWebSocket() NamespaceOption {
return func(ns *Namespace) error {
ns.useWebSocket = true
return nil
}
}
// NamespaceWithEnvironmentBinding configures a namespace using the environment details. It uses one of the following methods:
//
// 1. Client Credentials: attempt to authenticate with a Service Principal via "AZURE_TENANT_ID", "AZURE_CLIENT_ID" and
// "AZURE_CLIENT_SECRET"
//
// 2. Client Certificate: attempt to authenticate with a Service Principal via "AZURE_TENANT_ID", "AZURE_CLIENT_ID",
// "AZURE_CERTIFICATE_PATH" and "AZURE_CERTIFICATE_PASSWORD"
//
// 3. Managed Identity (MI): attempt to authenticate via the MI assigned to the Azure resource
//
//
// The Azure Environment used can be specified using the name of the Azure Environment set in "AZURE_ENVIRONMENT" var.
func NamespaceWithEnvironmentBinding(name string) NamespaceOption {
return func(ns *Namespace) error {
provider, err := aad.NewJWTProvider(
aad.JWTProviderWithEnvironmentVars(),
aad.JWTProviderWithResourceURI(serviceBusResourceURI),
)
if err != nil {
return err
}
ns.TokenProvider = provider
ns.Name = name
return nil
}
}
// NewNamespace creates a new namespace configured through NamespaceOption(s)
func NewNamespace(opts ...NamespaceOption) (*Namespace, error) {
ns := &Namespace{
Environment: azure.PublicCloud,
}
for _, opt := range opts {
err := opt(ns)
if err != nil {
return nil, err
}
}
return ns, nil
}
func (ns *Namespace) newClient() (*amqp.Client, error) {
defaultConnOptions := []amqp.ConnOption{
amqp.ConnSASLAnonymous(),
amqp.ConnMaxSessions(65535),
amqp.ConnProperty("product", "MSGolangClient"),
amqp.ConnProperty("version", Version),
amqp.ConnProperty("platform", runtime.GOOS),
amqp.ConnProperty("framework", runtime.Version()),
amqp.ConnProperty("user-agent", ns.getUserAgent()),
}
if ns.tlsConfig != nil {
defaultConnOptions = append(
defaultConnOptions,
amqp.ConnTLS(true),
amqp.ConnTLSConfig(ns.tlsConfig),
)
}
if ns.useWebSocket {
wssHost := ns.getWSSHostURI() + "$servicebus/websocket"
wssConn, err := websocket.Dial(wssHost, "amqp", "http://localhost/")
if err != nil {
return nil, err
}
wssConn.PayloadType = websocket.BinaryFrame
return amqp.New(wssConn, append(defaultConnOptions, amqp.ConnServerHostname(ns.getHostname()))...)
}
return amqp.Dial(ns.getAMQPHostURI(), defaultConnOptions...)
}
func (ns *Namespace) negotiateClaim(ctx context.Context, client *amqp.Client, entityPath string) error {
ctx, span := ns.startSpanFromContext(ctx, "sb.namespace.negotiateClaim")
defer span.End()
audience := ns.getEntityAudience(entityPath)
return cbs.NegotiateClaim(ctx, audience, client, ns.TokenProvider)
}
func (ns *Namespace) getWSSHostURI() string {
suffix := ns.resolveSuffix()
if strings.HasSuffix(suffix, "onebox.windows-int.net") {
return fmt.Sprintf("wss://%s:4446/", ns.getHostname())
}
return fmt.Sprintf("wss://%s/", ns.getHostname())
}
func (ns *Namespace) getAMQPHostURI() string {
return fmt.Sprintf("amqps://%s/", ns.getHostname())
}
func (ns *Namespace) getHTTPSHostURI() string {
suffix := ns.resolveSuffix()
if strings.HasSuffix(suffix, "onebox.windows-int.net") {
return fmt.Sprintf("https://%s:4446/", ns.getHostname())
}
return fmt.Sprintf("https://%s/", ns.getHostname())
}
func (ns *Namespace) getHostname() string {
return strings.Join([]string{ns.Name, ns.resolveSuffix()}, ".")
}
func (ns *Namespace) getEntityAudience(entityPath string) string {
return ns.getAMQPHostURI() + entityPath
}
func (ns *Namespace) getUserAgent() string {
userAgent := rootUserAgent
if ns.userAgent != "" {
userAgent = fmt.Sprintf("%s/%s", userAgent, ns.userAgent)
}
return userAgent
}
func (ns *Namespace) resolveSuffix() string {
var suffix string
if ns.Suffix != "" {
suffix = ns.Suffix
} else {
suffix = azure.PublicCloud.ServiceBusEndpointSuffix
}
return suffix
}