/
rate_updater.go
277 lines (246 loc) · 8.63 KB
/
rate_updater.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
/*******************************************************************************
*
* Copyright 2022 SAP SE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You should have received a copy of the License along with this
* program. If not, 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 api
import (
"fmt"
"net/http"
"sort"
"strings"
"time"
"github.com/sapcc/go-api-declarations/limes"
limesrates "github.com/sapcc/go-api-declarations/limes/rates"
"github.com/sapcc/go-bits/gopherpolicy"
"github.com/sapcc/go-bits/respondwith"
"github.com/sapcc/limes/internal/core"
"github.com/sapcc/limes/internal/db"
"github.com/sapcc/limes/internal/reports"
)
// RateLimitUpdater contains most of the business logic for PUT on rate limits.
type RateLimitUpdater struct {
// scope (all fields are always set since rate limits can only be updated on
// the project level)
Cluster *core.Cluster
Domain *db.Domain
Project *db.Project
// AuthZ info
CanSetRateLimit func(limes.ServiceType) bool
// Filled by ValidateInput() with the keys being the service type and the rate name.
Requests map[limes.ServiceType]map[limesrates.RateName]RateLimitRequest
}
// RateLimitRequest describes a single rate limit that a PUT requests wants to change.
// It appears in type RateLimitUpdater.
type RateLimitRequest struct {
Unit limes.Unit
OldLimit uint64
NewLimit uint64
OldWindow limesrates.Window
NewWindow limesrates.Window
ValidationError *RateValidationError
}
// RateValidationError appears in the Limes API in the POST .../simulate-put responses.
type RateValidationError struct {
Status int `json:"status"` // an HTTP status code, e.g. http.StatusForbidden
Message string `json:"message"`
}
// ValidateInput reads the given input and validates the quotas contained therein.
// Results are collected into u.Requests. The return value is only set for unexpected
// errors, not for validation errors.
func (u *RateLimitUpdater) ValidateInput(input limesrates.RateRequest, dbi db.Interface) error {
projectReport, err := GetProjectRateReport(u.Cluster, *u.Domain, *u.Project, dbi, reports.Filter{})
if err != nil {
return err
}
u.Requests = make(map[limes.ServiceType]map[limesrates.RateName]RateLimitRequest)
// Go through all services and validate the requested rate limits.
for svcType, in := range input {
svcConfig, err := u.Cluster.Config.GetServiceConfigurationForType(svcType)
if err != nil {
// Skip service if not configured.
continue
}
if _, ok := u.Requests[svcType]; !ok {
u.Requests[svcType] = make(map[limesrates.RateName]RateLimitRequest)
}
for rateName, newRateLimit := range in {
req := RateLimitRequest{
NewLimit: newRateLimit.Limit,
NewWindow: newRateLimit.Window,
}
// only allow setting rate limits for which a default exists
defaultRateLimit, exists := svcConfig.RateLimits.GetProjectDefaultRateLimit(rateName)
if exists {
req.Unit = defaultRateLimit.Unit
} else {
req.ValidationError = &RateValidationError{
Status: http.StatusForbidden,
Message: "user is not allowed to create new rate limits",
}
u.Requests[svcType][rateName] = req
continue
}
if projectService, exists := projectReport.Services[svcType]; exists {
projectRate, exists := projectService.Rates[rateName]
if exists && projectRate.Limit != 0 && projectRate.Window != nil {
req.OldLimit = projectRate.Limit
req.OldWindow = *projectRate.Window
} else {
req.OldLimit = defaultRateLimit.Limit
req.OldWindow = defaultRateLimit.Window
}
}
// skip if rate limit was not changed
if req.OldLimit == req.NewLimit && req.OldWindow == req.NewWindow {
continue
}
// value is valid and novel -> perform further validation
req.ValidationError = u.validateRateLimit(u.Cluster.InfoForService(svcType))
u.Requests[svcType][rateName] = req
}
}
return nil
}
func (u RateLimitUpdater) validateRateLimit(srv limes.ServiceInfo) *RateValidationError {
if u.CanSetRateLimit(srv.Type) {
return nil
}
return &RateValidationError{
Status: http.StatusForbidden,
Message: fmt.Sprintf("user is not allowed to set %q rate limits", srv.Type),
}
}
// IsValid returns true if all u.LimitRequests are valid (i.e. ValidationError == nil).
func (u RateLimitUpdater) IsValid() bool {
for _, reqs := range u.Requests {
for _, req := range reqs {
if req.ValidationError != nil {
return false
}
}
}
return true
}
// WriteSimulationReport produces the HTTP response for the POST /simulate-put
// endpoints.
func (u RateLimitUpdater) WriteSimulationReport(w http.ResponseWriter) {
type unacceptableRateLimit struct {
ServiceType limes.ServiceType `json:"service_type"`
Name limesrates.RateName `json:"name"`
RateValidationError
}
var result struct {
IsValid bool `json:"success"`
UnacceptableRateLimits []unacceptableRateLimit `json:"unacceptable_rates,omitempty"`
}
result.IsValid = true // until proven otherwise
for srvType, reqs := range u.Requests {
for rateName, req := range reqs {
if req.ValidationError != nil {
result.IsValid = false
result.UnacceptableRateLimits = append(result.UnacceptableRateLimits,
unacceptableRateLimit{
ServiceType: srvType,
Name: rateName,
RateValidationError: *req.ValidationError,
},
)
}
}
}
// deterministic ordering for unit tests
sort.Slice(result.UnacceptableRateLimits, func(i, j int) bool {
srvType1 := result.UnacceptableRateLimits[i].ServiceType
srvType2 := result.UnacceptableRateLimits[j].ServiceType
if srvType1 != srvType2 {
return srvType1 < srvType2
}
rateName1 := result.UnacceptableRateLimits[i].Name
rateName2 := result.UnacceptableRateLimits[j].Name
return rateName1 < rateName2
})
respondwith.JSON(w, http.StatusOK, result)
}
// WritePutErrorResponse produces a negative HTTP response for this PUT request.
// It may only be used when `u.IsValid()` is false.
func (u RateLimitUpdater) WritePutErrorResponse(w http.ResponseWriter) {
var lines []string
hasSubstatus := make(map[int]bool)
// collect error messages
for srvType, reqs := range u.Requests {
for rateName, req := range reqs {
if err := req.ValidationError; err != nil {
hasSubstatus[err.Status] = true
lines = append(
lines,
fmt.Sprintf("cannot change %s/%s rate limits: %s", srvType, rateName, err.Message),
)
}
}
}
sort.Strings(lines) // for determinism in unit test
msg := strings.Join(lines, "\n")
// when all errors have the same status, report that; otherwise use 422
// (Unprocessable Entity) as a reasonable overall default
status := http.StatusUnprocessableEntity
if len(hasSubstatus) == 1 {
for s := range hasSubstatus {
status = s
}
}
http.Error(w, msg, status)
}
////////////////////////////////////////////////////////////////////////////////
// integration with package audit
// CommitAuditTrail prepares an audit.Trail instance for this updater and
// commits it.
func (u RateLimitUpdater) CommitAuditTrail(token *gopherpolicy.Token, r *http.Request, requestTime time.Time) {
invalid := !u.IsValid()
statusCode := http.StatusOK
if invalid {
statusCode = http.StatusUnprocessableEntity
}
for srvType, reqs := range u.Requests {
for rateName, req := range reqs {
// if !u.IsValid(), then all requested quotas in this PUT are considered
// invalid (and none are committed), so set the rejectReason to explain this
rejectReason := ""
if invalid {
if req.ValidationError == nil {
rejectReason = "cannot commit this because other values in this request are unacceptable"
} else {
rejectReason = req.ValidationError.Message
}
}
logAndPublishEvent(requestTime, r, token, statusCode,
rateLimitEventTarget{
DomainID: u.Domain.UUID,
DomainName: u.Domain.Name,
ProjectID: u.Project.UUID,
ProjectName: u.Project.Name,
ServiceType: srvType,
Name: rateName,
OldLimit: req.OldLimit,
NewLimit: req.NewLimit,
OldWindow: req.OldWindow,
NewWindow: req.NewWindow,
Unit: req.Unit,
RejectReason: rejectReason,
})
}
}
}