-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathchanges.go
197 lines (175 loc) · 5.2 KB
/
changes.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
//
// Copyright 2014, Sander van Harmelen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"github.com/gorilla/mux"
)
// Name of the entity we are changing
type Name struct {
Name string `json:"name"`
RawData struct {
ID string `json:"id"`
} `json:"raw_data"`
}
func unmarshalName(body []byte) (*Name, error) {
var n Name
if err := json.Unmarshal(body, &n); err != nil {
return nil, err
}
// Needed to get the correct name from data bag items
if n.RawData.ID != "" {
n.Name = n.RawData.ID
}
return &n, nil
}
func processChange(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
cg, err := newChefGuard(r)
if err != nil {
errorHandler(w, fmt.Sprintf(
"Failed to create a new ChefGuard structure: %s", err), http.StatusInternalServerError)
return
}
reqBody, err := dumpBody(r)
if err != nil {
errorHandler(w, fmt.Sprintf(
"Failed to get body from call to %s: %s", r.URL.String(), err), http.StatusBadRequest)
return
}
if getEffectiveConfig("ValidateChanges", cg.ChefOrg).(string) == "enforced" &&
r.Method != "DELETE" {
if errCode, err := cg.validateConstraints(reqBody); err != nil {
errorHandler(w, err.Error(), errCode)
return
}
}
// So, this is kind of an ugly one...
// 1. If we don't want to commit any changes, just return here.
// 2. If we do want to commit the changes, but we are a node updating itself also return
// here unless this is a client or node creation as we do want to see those ones.
if getEffectiveConfig("CommitChanges", cg.ChefOrg).(bool) == false ||
strings.HasPrefix(r.Header.Get("User-Agent"), "Chef Client") &&
r.Header.Get("X-Ops-Request-Source") != "web" &&
!((mux.Vars(r)["type"] == "clients" || mux.Vars(r)["type"] == "nodes") && r.Method == "POST") {
p.ServeHTTP(w, r)
return
}
u := fmt.Sprintf(
"http://%s:%d%s?%s",
cfg.Chef.ErchefIP,
cfg.Chef.ErchefPort,
r.URL.Path,
r.URL.RawQuery,
)
r.URL, err = url.Parse(u)
if err != nil {
errorHandler(w, fmt.Sprintf("Failed to parse URL %s: %s", u, err), http.StatusBadRequest)
return
}
resp, err := http.DefaultTransport.RoundTrip(r)
if err != nil {
errorHandler(w, fmt.Sprintf(
"Call to %s failed: %s", r.URL.String(), err), http.StatusBadRequest)
return
}
defer resp.Body.Close()
if err := checkHTTPResponse(resp, []int{http.StatusOK, http.StatusCreated}); err != nil {
if resp.StatusCode == http.StatusForbidden {
err = fmt.Errorf("%s %s for %s", r.Header.Get("X-Ops-Userid"), err, r.URL.Path)
}
errorHandler(w, err.Error(), resp.StatusCode)
return
}
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
errorHandler(w, fmt.Sprintf(
"Failed to get body from call to %s: %s", r.URL.String(), err), http.StatusBadRequest)
return
}
cg.ChangeDetails, err = getChangeDetails(r, reqBody)
if err != nil {
errorHandler(w, fmt.Sprintf(
"Failed to parse variables from %s: %s", r.URL.String(), err), http.StatusBadRequest)
return
}
if r.Method == "PUT" {
go cg.syncedGitUpdate(r.Method, respBody)
} else {
go cg.syncedGitUpdate(r.Method, reqBody)
}
if getEffectiveConfig("ValidateChanges", cg.ChefOrg).(string) == "permissive" &&
r.Method != "DELETE" {
if errCode, err := cg.validateConstraints(reqBody); err != nil {
errorHandler(w, err.Error(), errCode)
return
}
}
copyHeaders(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
w.Write(respBody)
}
}
type changeDetails struct {
Item string
Type string
}
func getChangeDetails(r *http.Request, body []byte) (*changeDetails, error) {
cd := &changeDetails{}
v := mux.Vars(r)
// Resolve the name either directly or by unmarshalling the request body
if _, found := v["name"]; found {
cd.Item = fmt.Sprintf("%s.json", v["name"])
} else {
if len(body) > 0 {
n, err := unmarshalName(body)
if err != nil {
return nil, err
}
cd.Item = fmt.Sprintf("%s.json", n.Name)
}
}
// When changing data bags, the name of the bag should also be in cd.Item
// and the type should be set to "data_bags"
if _, found := v["bag"]; found {
// If no item is found by now, set the item to the whole bag instead of a single item
if cd.Item == "" {
cd.Item = fmt.Sprintf("%s", v["bag"])
} else {
cd.Item = fmt.Sprintf("%s/%s", v["bag"], cd.Item)
}
cd.Type = "data_bags"
} else {
cd.Type = v["type"]
}
return cd, nil
}
func copyHeaders(dst, src http.Header) {
for key, values := range src {
if key == "Content-Length" {
continue
}
for _, value := range values {
dst.Add(key, value)
}
}
}