-
Notifications
You must be signed in to change notification settings - Fork 1
/
cloudfront.go
122 lines (99 loc) · 2.29 KB
/
cloudfront.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
package cfsigner
import (
"crypto"
"crypto/rsa"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"errors"
"strings"
"time"
)
type CloudFront struct {
domain string
KeyPairId string
key *rsa.PrivateKey
}
type Policy struct {
policy []byte
cf *CloudFront
}
type policy struct {
Statement []statement
}
type statement struct {
Resource string
Condition conditions
}
type conditions struct {
DateLessThan epochTime
DateGreaterThan *epochTime `json:",omitempty"`
IpAddress *ipAddress `json:",omitempty"`
}
type epochTime struct {
Timestamp int64 `json:"AWS:EpochTime"`
}
type ipAddress struct {
Addr string `json:"AWS:SourceIp"`
}
// Will convert values from base64 encoded string to be URL safe
var invalidReplacer = strings.NewReplacer("+", "-", "=", "_", "/", "~")
var ErrMissingRequiredParam = errors.New("Missing required parameter")
func New(key *rsa.PrivateKey, keyPairId string) *CloudFront {
return &CloudFront{
KeyPairId: keyPairId,
key: key,
}
}
func (p *Policy) Encode() string {
return invalidReplacer.Replace(base64.StdEncoding.EncodeToString(p.policy))
}
func (p *Policy) Sign() (string, error) {
hash := hashSha(p.policy)
signed, err := rsa.SignPKCS1v15(nil, p.cf.key, crypto.SHA1, hash)
if err != nil {
return "", err
}
return invalidReplacer.Replace(base64.StdEncoding.EncodeToString(signed)), nil
}
func (cf *CloudFront) CreatePolicy(resource string, expiry time.Time, validAt *time.Time, ip *string) (*Policy, error) {
if expiry.IsZero() {
return nil, ErrMissingRequiredParam
}
conds := conditions{
DateLessThan: epochTime{
Timestamp: expiry.Truncate(time.Millisecond).Unix(),
},
}
if validAt != nil {
conds.DateGreaterThan = &epochTime{
Timestamp: validAt.Truncate(time.Millisecond).Unix(),
}
}
if ip != nil {
conds.IpAddress = &ipAddress{
Addr: *ip,
}
}
policy, err := buildPolicy(resource, conds)
if err != nil {
return nil, err
}
return &Policy{cf: cf, policy: policy}, nil
}
func hashSha(policy []byte) []byte {
hash := sha1.New()
hash.Write(policy)
return hash.Sum(nil)
}
func buildPolicy(resource string, conditions conditions) ([]byte, error) {
p := &policy{
Statement: []statement{
statement{
Resource: resource,
Condition: conditions,
},
},
}
return json.Marshal(p)
}