forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding.go
88 lines (71 loc) · 2.02 KB
/
encoding.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
// Copyright 2017 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package topdown
import (
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/topdown/builtins"
"github.com/open-policy-agent/opa/util"
)
func builtinJSONMarshal(a ast.Value) (ast.Value, error) {
asJSON, err := ast.JSON(a)
if err != nil {
return nil, err
}
bs, err := json.Marshal(asJSON)
if err != nil {
return nil, err
}
return ast.String(string(bs)), nil
}
func builtinJSONUnmarshal(a ast.Value) (ast.Value, error) {
str, err := builtins.StringOperand(a, 1)
if err != nil {
return nil, err
}
var x interface{}
if err := util.UnmarshalJSON([]byte(str), &x); err != nil {
return nil, err
}
return ast.InterfaceToValue(x)
}
func builtinBase64UrlEncode(a ast.Value) (ast.Value, error) {
str, err := builtins.StringOperand(a, 1)
if err != nil {
return nil, err
}
return ast.String(base64.URLEncoding.EncodeToString([]byte(str))), nil
}
func builtinBase64UrlDecode(a ast.Value) (ast.Value, error) {
str, err := builtins.StringOperand(a, 1)
if err != nil {
return nil, err
}
s := string(str)
// Some base64url encoders omit the padding at the end, so this case
// corrects such representations using the method given in RFC 7515
// Appendix C: https://tools.ietf.org/html/rfc7515#appendix-C
if !strings.HasSuffix(s, "=") {
switch len(s) % 4 {
case 0:
case 2:
s += "=="
case 3:
s += "="
default:
return nil, fmt.Errorf("illegal base64url string: %s", s)
}
}
result, err := base64.URLEncoding.DecodeString(s)
return ast.String(result), err
}
func init() {
RegisterFunctionalBuiltin1(ast.JSONMarshal.Name, builtinJSONMarshal)
RegisterFunctionalBuiltin1(ast.JSONUnmarshal.Name, builtinJSONUnmarshal)
RegisterFunctionalBuiltin1(ast.Base64UrlEncode.Name, builtinBase64UrlEncode)
RegisterFunctionalBuiltin1(ast.Base64UrlDecode.Name, builtinBase64UrlDecode)
}