forked from moov-io/signedxml
-
Notifications
You must be signed in to change notification settings - Fork 1
/
exclusivecanonicalization.go
305 lines (261 loc) · 7.54 KB
/
exclusivecanonicalization.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
package signedxml
import (
"sort"
"strings"
"github.com/beevik/etree"
)
// the attribute and attributes structs are used to implement the sort.Interface
type attribute struct {
prefix, uri, key, value string
}
type attributes []attribute
func (a attributes) Len() int {
return len(a)
}
// Less is part of the sort.Interface, and is used to order attributes by their
// namespace URIs and then by their keys.
func (a attributes) Less(i, j int) bool {
if a[i].uri == "" && a[j].uri != "" {
return true
}
if a[j].uri == "" && a[i].uri != "" {
return false
}
iQual := a[i].uri + a[i].key
jQual := a[j].uri + a[j].key
return iQual < jQual
}
func (a attributes) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
// ExclusiveCanonicalization implements the CanonicalizationAlgorithm
// interface and is used for processing the
// http://www.w3.org/2001/10/xml-exc-c14n# and
// http://www.w3.org/2001/10/xml-exc-c14n#WithComments transform
// algorithms
type ExclusiveCanonicalization struct {
WithComments bool
inclusiveNamespacePrefixList []string
namespaces map[string]string
}
// Process is called to transfrom the XML using the ExclusiveCanonicalization
// algorithm
func (e ExclusiveCanonicalization) Process(inputXML string,
transformXML string) (outputXML string, err error) {
e.namespaces = make(map[string]string)
doc := etree.NewDocument()
doc.WriteSettings.CanonicalEndTags = true
doc.WriteSettings.CanonicalText = true
doc.WriteSettings.CanonicalAttrVal = true
err = doc.ReadFromString(inputXML)
if err != nil {
return "", err
}
e.loadPrefixList(transformXML)
e.processDocLevelNodes(doc)
e.processRecursive(doc.Root(), nil, "")
outputXML, err = doc.WriteToString()
return outputXML, err
}
func (e *ExclusiveCanonicalization) loadPrefixList(transformXML string) {
if transformXML != "" {
tDoc := etree.NewDocument()
tDoc.ReadFromString(transformXML)
inclNSNode := tDoc.Root().SelectElement("InclusiveNamespaces")
if inclNSNode != nil {
prefixList := inclNSNode.SelectAttrValue("PrefixList", "")
if prefixList != "" {
e.inclusiveNamespacePrefixList = strings.Split(prefixList, " ")
}
}
}
}
// process nodes outside of the root element
func (e ExclusiveCanonicalization) processDocLevelNodes(doc *etree.Document) {
// keep track of the previous node action to manage line returns in CharData
previousNodeRemoved := false
for i := 0; i < len(doc.Child); i++ {
c := doc.Child[i]
switch c := c.(type) {
case *etree.Comment:
if e.WithComments {
previousNodeRemoved = false
} else {
removeTokenFromDocument(c, doc)
i--
previousNodeRemoved = true
}
case *etree.CharData:
if isWhitespace(c.Data) {
if previousNodeRemoved {
removeTokenFromDocument(c, doc)
i--
previousNodeRemoved = true
} else {
c.Data = "\n"
}
}
case *etree.Directive:
removeTokenFromDocument(c, doc)
i--
previousNodeRemoved = true
case *etree.ProcInst:
// remove declaration, but leave other PI's
if c.Target == "xml" {
removeTokenFromDocument(c, doc)
i--
previousNodeRemoved = true
} else {
previousNodeRemoved = false
}
default:
previousNodeRemoved = false
}
}
// if the last line is CharData whitespace, then remove it
if c, ok := doc.Child[len(doc.Child)-1].(*etree.CharData); ok {
if isWhitespace(c.Data) {
removeTokenFromDocument(c, doc)
}
}
}
func (e ExclusiveCanonicalization) processRecursive(node *etree.Element,
prefixesInScope []string, defaultNS string) {
newDefaultNS, newPrefixesInScope :=
e.renderAttributes(node, prefixesInScope, defaultNS)
for i := 0; i < len(node.Child); i++ {
child := node.Child[i]
switch child := child.(type) {
case *etree.Comment:
if !e.WithComments {
removeTokenFromElement(etree.Token(child), node)
i--
}
case *etree.Element:
e.processRecursive(child, newPrefixesInScope, newDefaultNS)
}
}
}
func (e ExclusiveCanonicalization) renderAttributes(node *etree.Element,
prefixesInScope []string, defaultNS string) (newDefaultNS string,
newPrefixesInScope []string) {
currentNS := node.SelectAttrValue("xmlns", defaultNS)
elementAttributes := []etree.Attr{}
nsListToRender := make(map[string]string)
attrListToRender := attributes{}
// load map with for prefix -> uri lookup
for _, attr := range node.Attr {
if attr.Space == "xmlns" {
e.namespaces[attr.Key] = attr.Value
}
}
// handle the namespace of the node itself
if node.Space != "" {
if !contains(prefixesInScope, node.Space) {
nsListToRender["xmlns:"+node.Space] = e.namespaces[node.Space]
prefixesInScope = append(prefixesInScope, node.Space)
}
} else if defaultNS != currentNS {
newDefaultNS = currentNS
elementAttributes = append(elementAttributes,
etree.Attr{Key: "xmlns", Value: currentNS})
}
for _, attr := range node.Attr {
// include the namespaces if they are in the inclusiveNamespacePrefixList
if attr.Space == "xmlns" {
if !contains(prefixesInScope, attr.Key) &&
contains(e.inclusiveNamespacePrefixList, attr.Key) {
nsListToRender["xmlns:"+attr.Key] = attr.Value
prefixesInScope = append(prefixesInScope, attr.Key)
}
}
// include namespaces for qualfied attributes
if attr.Space != "" &&
attr.Space != "xmlns" &&
!contains(prefixesInScope, attr.Space) {
nsListToRender["xmlns:"+attr.Space] = e.namespaces[attr.Space]
prefixesInScope = append(prefixesInScope, attr.Space)
}
// inclued all non-namespace attributes
if attr.Space != "xmlns" && attr.Key != "xmlns" {
attrListToRender = append(attrListToRender,
attribute{
prefix: attr.Space,
uri: e.namespaces[attr.Space],
key: attr.Key,
value: attr.Value,
})
}
}
// sort and add the namespace attributes first
sortedNSList := getSortedNamespaces(nsListToRender)
elementAttributes = append(elementAttributes, sortedNSList...)
// then sort and add the non-namespace attributes
sortedAttributes := getSortedAttributes(attrListToRender)
elementAttributes = append(elementAttributes, sortedAttributes...)
// replace the nodes attributes with the sorted copy
node.Attr = elementAttributes
return currentNS, prefixesInScope
}
func contains(slice []string, value string) bool {
for _, s := range slice {
if s == value {
return true
}
}
return false
}
// getSortedNamespaces sorts the namespace attributes by their prefix
func getSortedNamespaces(list map[string]string) []etree.Attr {
var keys []string
for k := range list {
keys = append(keys, k)
}
sort.Strings(keys)
elem := etree.Element{}
for _, k := range keys {
elem.CreateAttr(k, list[k])
}
return elem.Attr
}
// getSortedAttributes sorts attributes by their namespace URIs
func getSortedAttributes(list attributes) []etree.Attr {
sort.Sort(list)
attrs := make([]etree.Attr, len(list))
for i, a := range list {
attrs[i] = etree.Attr{
Space: a.prefix,
Key: a.key,
Value: a.value,
}
}
return attrs
}
func removeTokenFromElement(token etree.Token, e *etree.Element) *etree.Token {
for i, t := range e.Child {
if t == token {
e.Child = append(e.Child[0:i], e.Child[i+1:]...)
return &t
}
}
return nil
}
func removeTokenFromDocument(token etree.Token, d *etree.Document) *etree.Token {
for i, t := range d.Child {
if t == token {
d.Child = append(d.Child[0:i], d.Child[i+1:]...)
return &t
}
}
return nil
}
// isWhitespace returns true if the byte slice contains only
// whitespace characters.
func isWhitespace(s string) bool {
for i := 0; i < len(s); i++ {
if c := s[i]; c != ' ' && c != '\t' && c != '\n' && c != '\r' {
return false
}
}
return true
}