forked from foomo/soap
-
Notifications
You must be signed in to change notification settings - Fork 17
/
client.go
341 lines (302 loc) · 9.13 KB
/
client.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
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
package soap
import (
"bytes"
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"mime"
"mime/multipart"
"net/http"
"net/url"
"strings"
"time"
)
// UserAgent is the default user agent
const userAgent = "go-soap-1.3"
// XMLMarshaller lets you inject your favourite custom xml implementation
type XMLMarshaller interface {
Marshal(v interface{}) ([]byte, error)
Unmarshal(xml []byte, v interface{}) error
}
type defaultMarshaller struct{}
func (dm defaultMarshaller) Marshal(v interface{}) ([]byte, error) {
return xml.MarshalIndent(v, "", " ")
}
func (dm defaultMarshaller) Unmarshal(xmlBytes []byte, v interface{}) error {
return xml.Unmarshal(xmlBytes, v)
}
// BasicAuth credentials for the client
type BasicAuth struct {
Login string
Password string
}
// Client generic SOAP client
type Client struct {
Log func(msg string, keyString_ValueInterface ...interface{}) // optional
url string
urlMasked string
tls bool
auth *BasicAuth
Marshaller XMLMarshaller
UserAgent string // optional, falls back to "go-soap-0.1"
ContentType string // optional, falls back to SOAP 1.1
RequestHeaderFn func(http.Header) // optional, allows to modify the request header before it gets submitted.
SoapVersion string
HTTPClientDoFn func(req *http.Request) (*http.Response, error)
LogRemoveHeaderNames []string
}
// NewClient constructor. SOAP 1.1 is used by default. Switch to SOAP 1.2 with
// UseSoap12(). Argument rt can be nil and it will fall back to the default
// http.Transport.
func NewClient(postToURL string, auth *BasicAuth) *Client {
var urlMasked string
if pURL, err := url.Parse(postToURL); err == nil {
pURL.User = url.UserPassword(pURL.User.Username(), "********")
urlMasked = pURL.String()
}
return &Client{
url: postToURL,
urlMasked: urlMasked,
auth: auth,
Marshaller: defaultMarshaller{},
ContentType: SoapContentType11, // default is SOAP 1.1
SoapVersion: SoapVersion11,
HTTPClientDoFn: http.DefaultClient.Do,
LogRemoveHeaderNames: []string{"Authorization", "Apikey"},
}
}
func (c *Client) UseSoap11() {
c.SoapVersion = SoapVersion11
c.ContentType = SoapContentType11
}
func (c *Client) UseSoap12() {
c.SoapVersion = SoapVersion12
c.ContentType = SoapContentType12
}
// Call makes a SOAP call
func (c *Client) Call(ctx context.Context, soapAction string, request, response interface{}) (*http.Response, error) {
envelope := Envelope{
Body: Body{Content: request},
}
xmlBytes, err := c.Marshaller.Marshal(envelope)
if err != nil {
return nil, err
}
// Adjust namespaces for SOAP 1.2
if c.SoapVersion == SoapVersion12 {
xmlBytes = replaceSoap11to12(xmlBytes)
}
req, err := http.NewRequestWithContext(ctx, "POST", c.url, bytes.NewReader(xmlBytes))
if err != nil {
return nil, err
}
if c.auth != nil {
req.SetBasicAuth(c.auth.Login, c.auth.Password)
}
req.Header.Add("Content-Type", c.ContentType)
ua := c.UserAgent
if ua == "" {
ua = userAgent
}
req.Header.Set("User-Agent", ua)
if soapAction != "" {
req.Header.Add("SOAPAction", soapAction)
}
req.Close = true
if c.RequestHeaderFn != nil {
c.RequestHeaderFn(req.Header)
}
var logTraceID string
if c.Log != nil {
logTraceID = randString(12)
c.Log("Request", "log_trace_id", logTraceID, "url", c.urlMasked, "request_bytes", string(xmlBytes))
hdr := req.Header.Clone()
for _, n := range c.LogRemoveHeaderNames {
hdr.Set(n, "removed")
}
c.Log("Header", "log_trace_id", logTraceID, "Header", hdr)
}
httpResponse, err := c.HTTPClientDoFn(req)
if err != nil {
return nil, err
}
defer httpResponse.Body.Close()
if c.Log != nil {
c.Log("Response header", "log_trace_id", logTraceID, "header", httpResponse.Header)
}
mediaType, params, err := mime.ParseMediaType(httpResponse.Header.Get("Content-Type"))
if err != nil {
if c.Log != nil {
c.Log("WARNING", "log_trace_id", logTraceID, "error", err)
}
}
if c.Log != nil {
c.Log("MIMETYPE", "log_trace_id", logTraceID, "mediaType", mediaType)
}
var rawBody []byte
if strings.HasPrefix(mediaType, "multipart/") { // MULTIPART MESSAGE
mr := multipart.NewReader(httpResponse.Body, params["boundary"])
// If this is a multipart message, search for the soapy part
foundSoap := false
for {
p, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
slurp, err := ioutil.ReadAll(p)
if err != nil {
return nil, err
}
if bytes.HasPrefix(slurp, soapPrefixTagLC) || bytes.HasPrefix(slurp, soapPrefixTagUC) {
rawBody = slurp
foundSoap = true
break
}
}
if !foundSoap {
return nil, errors.New("multipart message does contain a soapy part")
}
} else { // SINGLE PART MESSAGE
rawBody, err = ioutil.ReadAll(httpResponse.Body)
if err != nil {
return httpResponse, err // return both
}
// Check if there is a body and if yes if it's a soapy one.
if len(rawBody) == 0 {
if c.Log != nil {
c.Log("INFO: Response Body is empty!", "log_trace_id", logTraceID)
}
return httpResponse, nil // Empty responses are ok. Sometimes Sometimes only a Status 200 or 202 comes back
}
// There is a message body, but it's not SOAP. We cannot handle this!
switch c.SoapVersion {
case SoapVersion12:
if !bytes.Contains(rawBody, []byte(`soap-envelope`)) { // not quite sure if correct to assert on soap-...
if c.Log != nil {
c.Log("This is not a 1.2 SOAP-Message", "log_trace_id", logTraceID, "response_bytes", rawBody)
}
return nil, fmt.Errorf("this is not a 1.2 SOAP-Message: %q", string(rawBody))
}
default:
if !(bytes.Contains(rawBody, soapPrefixTagLC) || bytes.Contains(rawBody, soapPrefixTagUC)) {
if c.Log != nil {
c.Log("This is not a 1.1 SOAP-Message", "log_trace_id", logTraceID, "response_bytes", rawBody)
}
return nil, fmt.Errorf("this is not a 1.1 SOAP-Message: %q", string(rawBody))
}
}
}
// We have an empty body or a SOAP body
if c.Log != nil {
c.Log("response raw body", "log_trace_id", logTraceID, "response_bytes", rawBody)
}
// Our structs for Envelope, Header, Body and Fault are tagged with namespace
// for SOAP 1.1. Therefore we must adjust namespaces for incoming SOAP 1.2
// messages
rawBody = replaceSoap12to11(rawBody)
respEnvelope := &Envelope{
Body: Body{Content: response},
}
// Response struct may be nil, e.g. if only a Status 200 is expected. In this
// case, we need a Dummy response to avoid a nil pointer if we receive a
// SOAP-Fault instead of the empty message (unmarshalling would fail).
if response == nil {
respEnvelope.Body = Body{Content: &dummyContent{}} // must be a pointer in dummyContent
}
if err := xml.Unmarshal(rawBody, respEnvelope); err != nil {
return nil, fmt.Errorf("soap/client.go Call(): COULD NOT UNMARSHAL: %w\n", err)
}
// If a SOAP Fault is received, try to jsonMarshal it and return it via the
// error.
if fault := respEnvelope.Body.Fault; fault != nil {
return nil, fmt.Errorf("SOAP FAULT: %q", formatFaultXML(rawBody, 1))
}
return httpResponse, nil
}
// Format the Soap Fault as indented string. Namespaces are dropped for better
// readability. Tags with lower level than start level is omitted.
func formatFaultXML(xmlBytes []byte, startLevel int) string {
indent := " "
d := xml.NewDecoder(bytes.NewBuffer(xmlBytes))
level := 0
var out bytes.Buffer
out.Grow(len(xmlBytes))
ind := func() {
n := 0
if level-startLevel-1 > 0 {
n = level - startLevel - 1
}
out.Write([]byte(strings.Repeat(indent, n)))
}
lf := func() {
out.Write([]byte("\n"))
}
lastWasStart := false
lastWasCharData := false
lastWasEnd := false
for token, err := d.Token(); token != nil && err == nil; token, err = d.Token() {
switch tt := token.(type) {
case xml.StartElement:
lastWasCharData = false
if lastWasEnd || lastWasStart {
lf()
}
lastWasStart = true
ind()
elementName := tt.Name.Local
if level > startLevel {
out.WriteString("<" + elementName)
out.WriteString(">")
}
level++
lastWasEnd = false
case xml.CharData:
lastWasCharData = true
_ = lastWasCharData
lastWasStart = false
xml.EscapeText(&out, tt)
lastWasEnd = false
case xml.EndElement:
level--
if lastWasEnd {
lf()
ind()
}
lastWasEnd = true
lastWasStart = false
if level > startLevel {
endTagName := tt.Name.Local
out.WriteString("</" + endTagName + ">")
}
}
}
return string(bytes.Trim(out.Bytes(), " \n"))
}
var (
soapPrefixTagUC = []byte("<SOAP")
soapPrefixTagLC = []byte("<soap")
)
func replaceSoap12to11(data []byte) []byte {
return bytes.ReplaceAll(data, bNamespaceSoap12, bNamespaceSoap11)
}
func replaceSoap11to12(data []byte) []byte {
return bytes.ReplaceAll(data, bNamespaceSoap11, bNamespaceSoap12)
}
const charset = "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var seededRand = rand.New(
rand.NewSource(time.Now().UnixNano()))
func randString(length int) string {
b := make([]byte, length)
for i := range b {
b[i] = charset[seededRand.Intn(len(charset))]
}
return string(b)
}