• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

sapcc / limes / 16908757853

12 Aug 2025 12:21PM UTC coverage: 78.932% (+0.008%) from 78.924%
16908757853

Pull #739

github

Varsius
use respondwith.ObfuscatedErrorText in 500 responses
Pull Request #739: use respondwith.ObfuscatedErrorText in 500 responses

126 of 139 new or added lines in 11 files covered. (90.65%)

2 existing lines in 1 file now uncovered.

6845 of 8672 relevant lines covered (78.93%)

59.55 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.45
/internal/api/commitment.go
1
// SPDX-FileCopyrightText: 2023 SAP SE or an SAP affiliate company
2
// SPDX-License-Identifier: Apache-2.0
3

4
package api
5

6
import (
7
        "cmp"
8
        "database/sql"
9
        "encoding/json"
10
        "errors"
11
        "fmt"
12
        "maps"
13
        "net/http"
14
        "slices"
15
        "strings"
16
        "time"
17

18
        "github.com/gorilla/mux"
19
        . "github.com/majewsky/gg/option"
20
        "github.com/majewsky/gg/options"
21
        "github.com/sapcc/go-api-declarations/cadf"
22
        "github.com/sapcc/go-api-declarations/limes"
23
        limesresources "github.com/sapcc/go-api-declarations/limes/resources"
24
        "github.com/sapcc/go-api-declarations/liquid"
25
        "github.com/sapcc/go-bits/audittools"
26
        "github.com/sapcc/go-bits/errext"
27
        "github.com/sapcc/go-bits/gopherpolicy"
28
        "github.com/sapcc/go-bits/httpapi"
29
        "github.com/sapcc/go-bits/logg"
30
        "github.com/sapcc/go-bits/must"
31
        "github.com/sapcc/go-bits/respondwith"
32
        "github.com/sapcc/go-bits/sqlext"
33

34
        "github.com/sapcc/limes/internal/core"
35
        "github.com/sapcc/limes/internal/datamodel"
36
        "github.com/sapcc/limes/internal/db"
37
        "github.com/sapcc/limes/internal/reports"
38
)
39

40
var (
41
        getProjectCommitmentsQuery = sqlext.SimplifyWhitespace(`
42
                SELECT pc.*
43
                  FROM project_commitments pc
44
                  JOIN az_resources cazr ON pc.az_resource_id = cazr.id
45
                  JOIN resources cr ON cazr.resource_id = cr.id {{AND cr.name = $resource_name}}
46
                  JOIN services cs ON cr.service_id = cs.id {{AND cs.type = $service_type}}
47
                 WHERE %s AND pc.state NOT IN ('superseded', 'expired')
48
                 ORDER BY pc.id
49
        `)
50

51
        getAZResourceLocationsQuery = sqlext.SimplifyWhitespace(`
52
                SELECT cazr.id, cs.type, cr.name, cazr.az
53
                  FROM project_az_resources pazr
54
                  JOIN az_resources cazr on pazr.az_resource_id = cazr.id
55
                  JOIN resources cr ON cazr.resource_id = cr.id {{AND cr.name = $resource_name}}
56
                  JOIN services cs ON cr.service_id = cs.id {{AND cs.type = $service_type}}
57
                 WHERE %s
58
        `)
59

60
        findProjectCommitmentByIDQuery = sqlext.SimplifyWhitespace(`
61
                SELECT pc.*
62
                  FROM project_commitments pc
63
                 WHERE pc.id = $1 AND pc.project_id = $2
64
        `)
65

66
        findAZResourceIDByLocationQuery = sqlext.SimplifyWhitespace(`
67
                SELECT cazr.id, pr.forbidden IS NOT TRUE as resource_allows_commitments
68
                  FROM az_resources cazr
69
                  JOIN resources cr ON cazr.resource_id = cr.id
70
                  JOIN services cs ON cr.service_id = cs.id
71
                  JOIN project_resources pr ON pr.resource_id = cr.id
72
                 WHERE pr.project_id = $1 AND cs.type = $2 AND cr.name = $3 AND cazr.az = $4
73
        `)
74

75
        findAZResourceLocationByIDQuery = sqlext.SimplifyWhitespace(`
76
                SELECT cs.type, cr.name, cazr.az
77
                  FROM az_resources cazr
78
                  JOIN resources cr ON cazr.resource_id = cr.id
79
                  JOIN services cs ON cr.service_id = cs.id
80
                 WHERE cazr.id = $1
81
        `)
82
        getCommitmentWithMatchingTransferTokenQuery = sqlext.SimplifyWhitespace(`
83
                SELECT * FROM project_commitments WHERE id = $1 AND transfer_token = $2
84
        `)
85
        findCommitmentByTransferToken = sqlext.SimplifyWhitespace(`
86
                SELECT * FROM project_commitments WHERE transfer_token = $1
87
        `)
88
)
89

90
// GetProjectCommitments handles GET /v1/domains/:domain_id/projects/:project_id/commitments.
91
func (p *v1Provider) GetProjectCommitments(w http.ResponseWriter, r *http.Request) {
15✔
92
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments")
15✔
93
        token := p.CheckToken(r)
15✔
94
        if !token.Require(w, "project:show") {
16✔
95
                return
1✔
96
        }
1✔
97
        dbDomain := p.FindDomainFromRequest(w, r)
14✔
98
        if dbDomain == nil {
15✔
99
                return
1✔
100
        }
1✔
101
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
13✔
102
        if dbProject == nil {
14✔
103
                return
1✔
104
        }
1✔
105
        serviceInfos, err := p.Cluster.AllServiceInfos()
12✔
106
        if respondwith.ObfuscatedErrorText(w, err) {
12✔
107
                return
×
108
        }
×
109

110
        // enumerate project AZ resources
111
        filter := reports.ReadFilter(r, p.Cluster, serviceInfos)
12✔
112
        queryStr, joinArgs := filter.PrepareQuery(getAZResourceLocationsQuery)
12✔
113
        whereStr, whereArgs := db.BuildSimpleWhereClause(map[string]any{"pazr.project_id": dbProject.ID}, len(joinArgs))
12✔
114
        azResourceLocationsByID := make(map[db.AZResourceID]core.AZResourceLocation)
12✔
115
        err = sqlext.ForeachRow(p.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {
137✔
116
                var (
125✔
117
                        id  db.AZResourceID
125✔
118
                        loc core.AZResourceLocation
125✔
119
                )
125✔
120
                err := rows.Scan(&id, &loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
125✔
121
                if err != nil {
125✔
122
                        return err
×
123
                }
×
124
                // this check is defense in depth (the DB should be consistent with our config)
125
                if core.HasResource(serviceInfos, loc.ServiceType, loc.ResourceName) {
250✔
126
                        azResourceLocationsByID[id] = loc
125✔
127
                }
125✔
128
                return nil
125✔
129
        })
130
        if respondwith.ObfuscatedErrorText(w, err) {
12✔
131
                return
×
132
        }
×
133

134
        // enumerate relevant project commitments
135
        queryStr, joinArgs = filter.PrepareQuery(getProjectCommitmentsQuery)
12✔
136
        whereStr, whereArgs = db.BuildSimpleWhereClause(map[string]any{"pc.project_id": dbProject.ID}, len(joinArgs))
12✔
137
        var dbCommitments []db.ProjectCommitment
12✔
138
        _, err = p.DB.Select(&dbCommitments, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...)...)
12✔
139
        if respondwith.ObfuscatedErrorText(w, err) {
12✔
140
                return
×
141
        }
×
142

143
        // render response
144
        result := make([]limesresources.Commitment, 0, len(dbCommitments))
12✔
145
        for _, c := range dbCommitments {
26✔
146
                loc, exists := azResourceLocationsByID[c.AZResourceID]
14✔
147
                if !exists {
14✔
148
                        // defense in depth (the DB should not change that much between those two queries above)
×
149
                        continue
×
150
                }
151
                serviceInfo := core.InfoForService(serviceInfos, loc.ServiceType)
14✔
152
                resInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
14✔
153
                result = append(result, p.convertCommitmentToDisplayForm(c, loc, token, resInfo.Unit))
14✔
154
        }
155

156
        respondwith.JSON(w, http.StatusOK, map[string]any{"commitments": result})
12✔
157
}
158

159
// The state in the db can be directly mapped to the liquid.CommitmentStatus.
160
// However, the state "active" is named "confirmed" in the API. If the persisted
161
// state cannot be mapped to liquid terms, an empty string is returned.
162
func (p *v1Provider) convertCommitmentStateToDisplayForm(c db.ProjectCommitment) liquid.CommitmentStatus {
65✔
163
        var status = liquid.CommitmentStatus(c.State)
65✔
164
        if c.State == "active" {
103✔
165
                status = liquid.CommitmentStatusConfirmed
38✔
166
        }
38✔
167
        if status.IsValid() {
129✔
168
                return status
64✔
169
        }
64✔
170
        return "" // An empty state will be omitted when json serialized.
1✔
171
}
172

173
func (p *v1Provider) convertCommitmentToDisplayForm(c db.ProjectCommitment, loc core.AZResourceLocation, token *gopherpolicy.Token, unit limes.Unit) limesresources.Commitment {
59✔
174
        apiIdentity := p.Cluster.BehaviorForResource(loc.ServiceType, loc.ResourceName).IdentityInV1API
59✔
175
        return limesresources.Commitment{
59✔
176
                ID:               int64(c.ID),
59✔
177
                UUID:             string(c.UUID),
59✔
178
                ServiceType:      apiIdentity.ServiceType,
59✔
179
                ResourceName:     apiIdentity.Name,
59✔
180
                AvailabilityZone: loc.AvailabilityZone,
59✔
181
                Amount:           c.Amount,
59✔
182
                Unit:             unit,
59✔
183
                Duration:         c.Duration,
59✔
184
                CreatedAt:        limes.UnixEncodedTime{Time: c.CreatedAt},
59✔
185
                CreatorUUID:      c.CreatorUUID,
59✔
186
                CreatorName:      c.CreatorName,
59✔
187
                CanBeDeleted:     p.canDeleteCommitment(token, c),
59✔
188
                ConfirmBy:        options.Map(c.ConfirmBy, intoUnixEncodedTime).AsPointer(),
59✔
189
                ConfirmedAt:      options.Map(c.ConfirmedAt, intoUnixEncodedTime).AsPointer(),
59✔
190
                ExpiresAt:        limes.UnixEncodedTime{Time: c.ExpiresAt},
59✔
191
                TransferStatus:   c.TransferStatus,
59✔
192
                TransferToken:    c.TransferToken.AsPointer(),
59✔
193
                Status:           p.convertCommitmentStateToDisplayForm(c),
59✔
194
                NotifyOnConfirm:  c.NotifyOnConfirm,
59✔
195
                WasRenewed:       c.RenewContextJSON.IsSome(),
59✔
196
        }
59✔
197
}
59✔
198

199
// parseAndValidateCommitmentRequest parses and validates the request body for a commitment creation or confirmation.
200
// This function in its current form should only be used if the serviceInfo is not necessary to be used outside
201
// of this validation to avoid unnecessary database queries.
202
func (p *v1Provider) parseAndValidateCommitmentRequest(w http.ResponseWriter, r *http.Request, dbDomain db.Domain) (*limesresources.CommitmentRequest, *core.AZResourceLocation, *core.ScopedCommitmentBehavior) {
46✔
203
        // parse request
46✔
204
        var parseTarget struct {
46✔
205
                Request limesresources.CommitmentRequest `json:"commitment"`
46✔
206
        }
46✔
207
        if !RequireJSON(w, r, &parseTarget) {
47✔
208
                return nil, nil, nil
1✔
209
        }
1✔
210
        req := parseTarget.Request
45✔
211

45✔
212
        // validate request
45✔
213
        serviceInfos, err := p.Cluster.AllServiceInfos()
45✔
214
        if respondwith.ObfuscatedErrorText(w, err) {
45✔
215
                return nil, nil, nil
×
216
        }
×
217
        nm := core.BuildResourceNameMapping(p.Cluster, serviceInfos)
45✔
218
        dbServiceType, dbResourceName, ok := nm.MapFromV1API(req.ServiceType, req.ResourceName)
45✔
219
        if !ok {
47✔
220
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", req.ServiceType, req.ResourceName)
2✔
221
                http.Error(w, msg, http.StatusUnprocessableEntity)
2✔
222
                return nil, nil, nil
2✔
223
        }
2✔
224
        behavior := p.Cluster.CommitmentBehaviorForResource(dbServiceType, dbResourceName).ForDomain(dbDomain.Name)
43✔
225
        serviceInfo := core.InfoForService(serviceInfos, dbServiceType)
43✔
226
        resInfo := core.InfoForResource(serviceInfo, dbResourceName)
43✔
227
        if len(behavior.Durations) == 0 {
44✔
228
                http.Error(w, "commitments are not enabled for this resource", http.StatusUnprocessableEntity)
1✔
229
                return nil, nil, nil
1✔
230
        }
1✔
231
        if resInfo.Topology == liquid.FlatTopology {
45✔
232
                if req.AvailabilityZone != limes.AvailabilityZoneAny {
4✔
233
                        http.Error(w, `resource does not accept AZ-aware commitments, so the AZ must be set to "any"`, http.StatusUnprocessableEntity)
1✔
234
                        return nil, nil, nil
1✔
235
                }
1✔
236
        } else {
39✔
237
                if !slices.Contains(p.Cluster.Config.AvailabilityZones, req.AvailabilityZone) {
43✔
238
                        http.Error(w, "no such availability zone", http.StatusUnprocessableEntity)
4✔
239
                        return nil, nil, nil
4✔
240
                }
4✔
241
        }
242
        if !slices.Contains(behavior.Durations, req.Duration) {
38✔
243
                buf := must.Return(json.Marshal(behavior.Durations)) // panic on error is acceptable here, marshals should never fail
1✔
244
                msg := "unacceptable commitment duration for this resource, acceptable values: " + string(buf)
1✔
245
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
246
                return nil, nil, nil
1✔
247
        }
1✔
248
        if req.Amount == 0 {
37✔
249
                http.Error(w, "amount of committed resource must be greater than zero", http.StatusUnprocessableEntity)
1✔
250
                return nil, nil, nil
1✔
251
        }
1✔
252

253
        loc := core.AZResourceLocation{
35✔
254
                ServiceType:      dbServiceType,
35✔
255
                ResourceName:     dbResourceName,
35✔
256
                AvailabilityZone: req.AvailabilityZone,
35✔
257
        }
35✔
258
        return &req, &loc, &behavior
35✔
259
}
260

261
// CanConfirmNewProjectCommitment handles POST /v1/domains/:domain_id/projects/:project_id/commitments/can-confirm.
262
func (p *v1Provider) CanConfirmNewProjectCommitment(w http.ResponseWriter, r *http.Request) {
7✔
263
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/can-confirm")
7✔
264
        token := p.CheckToken(r)
7✔
265
        if !token.Require(w, "project:edit") {
7✔
266
                return
×
267
        }
×
268
        dbDomain := p.FindDomainFromRequest(w, r)
7✔
269
        if dbDomain == nil {
7✔
270
                return
×
271
        }
×
272
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
7✔
273
        if dbProject == nil {
7✔
274
                return
×
275
        }
×
276
        req, loc, behavior := p.parseAndValidateCommitmentRequest(w, r, *dbDomain)
7✔
277
        if req == nil {
7✔
278
                return
×
279
        }
×
280

281
        var (
7✔
282
                azResourceID              db.AZResourceID
7✔
283
                resourceAllowsCommitments bool
7✔
284
        )
7✔
285
        err := p.DB.QueryRow(findAZResourceIDByLocationQuery, dbProject.ID, loc.ServiceType, loc.ResourceName, loc.AvailabilityZone).
7✔
286
                Scan(&azResourceID, &resourceAllowsCommitments)
7✔
287
        if respondwith.ObfuscatedErrorText(w, err) {
7✔
288
                return
×
289
        }
×
290
        if !resourceAllowsCommitments {
7✔
291
                msg := fmt.Sprintf("resource %s/%s is not enabled in this project", req.ServiceType, req.ResourceName)
×
292
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
293
                return
×
294
        }
×
295
        _ = azResourceID // returned by the above query, but not used in this function
7✔
296

7✔
297
        // commitments can never be confirmed immediately if we are before the min_confirm_date
7✔
298
        now := p.timeNow()
7✔
299
        if !behavior.CanConfirmCommitmentsAt(now) {
8✔
300
                respondwith.JSON(w, http.StatusOK, map[string]bool{"result": false})
1✔
301
                return
1✔
302
        }
1✔
303

304
        // check for committable capacity
305
        result, err := datamodel.CanConfirmNewCommitment(*loc, dbProject.ID, req.Amount, p.Cluster, p.DB)
6✔
306
        if respondwith.ObfuscatedErrorText(w, err) {
6✔
307
                return
×
308
        }
×
309
        respondwith.JSON(w, http.StatusOK, map[string]bool{"result": result})
6✔
310
}
311

312
// CreateProjectCommitment handles POST /v1/domains/:domain_id/projects/:project_id/commitments/new.
313
func (p *v1Provider) CreateProjectCommitment(w http.ResponseWriter, r *http.Request) {
42✔
314
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/new")
42✔
315
        token := p.CheckToken(r)
42✔
316
        if !token.Require(w, "project:edit") {
43✔
317
                return
1✔
318
        }
1✔
319
        dbDomain := p.FindDomainFromRequest(w, r)
41✔
320
        if dbDomain == nil {
42✔
321
                return
1✔
322
        }
1✔
323
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
40✔
324
        if dbProject == nil {
41✔
325
                return
1✔
326
        }
1✔
327
        req, loc, behavior := p.parseAndValidateCommitmentRequest(w, r, *dbDomain)
39✔
328
        if req == nil {
50✔
329
                return
11✔
330
        }
11✔
331

332
        var (
28✔
333
                azResourceID              db.AZResourceID
28✔
334
                resourceAllowsCommitments bool
28✔
335
        )
28✔
336
        err := p.DB.QueryRow(findAZResourceIDByLocationQuery, dbProject.ID, loc.ServiceType, loc.ResourceName, loc.AvailabilityZone).
28✔
337
                Scan(&azResourceID, &resourceAllowsCommitments)
28✔
338
        if respondwith.ObfuscatedErrorText(w, err) {
28✔
339
                return
×
340
        }
×
341
        if !resourceAllowsCommitments {
29✔
342
                msg := fmt.Sprintf("resource %s/%s is not enabled in this project", req.ServiceType, req.ResourceName)
1✔
343
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
344
                return
1✔
345
        }
1✔
346

347
        // if given, confirm_by must definitely after time.Now(), and also after the MinConfirmDate if configured
348
        now := p.timeNow()
27✔
349
        if req.ConfirmBy != nil && req.ConfirmBy.Before(now) {
28✔
350
                http.Error(w, "confirm_by must not be set in the past", http.StatusUnprocessableEntity)
1✔
351
                return
1✔
352
        }
1✔
353
        if minConfirmBy, ok := behavior.MinConfirmDate.Unpack(); ok && minConfirmBy.After(now) {
31✔
354
                if req.ConfirmBy == nil || req.ConfirmBy.Before(minConfirmBy) {
6✔
355
                        msg := "this commitment needs a `confirm_by` timestamp at or after " + minConfirmBy.Format(time.RFC3339)
1✔
356
                        http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
357
                        return
1✔
358
                }
1✔
359
        }
360

361
        // we want to validate committable capacity in the same transaction that creates the commitment
362
        tx, err := p.DB.Begin()
25✔
363
        if respondwith.ObfuscatedErrorText(w, err) {
25✔
364
                return
×
365
        }
×
366
        defer sqlext.RollbackUnlessCommitted(tx)
25✔
367

25✔
368
        // prepare commitment
25✔
369
        confirmBy := options.Map(options.FromPointer(req.ConfirmBy), fromUnixEncodedTime)
25✔
370
        creationContext := db.CommitmentWorkflowContext{Reason: db.CommitmentReasonCreate}
25✔
371
        buf, err := json.Marshal(creationContext)
25✔
372
        if respondwith.ObfuscatedErrorText(w, err) {
25✔
373
                return
×
374
        }
×
375
        dbCommitment := db.ProjectCommitment{
25✔
376
                UUID:                p.generateProjectCommitmentUUID(),
25✔
377
                AZResourceID:        azResourceID,
25✔
378
                ProjectID:           dbProject.ID,
25✔
379
                Amount:              req.Amount,
25✔
380
                Duration:            req.Duration,
25✔
381
                CreatedAt:           now,
25✔
382
                CreatorUUID:         token.UserUUID(),
25✔
383
                CreatorName:         fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
25✔
384
                ConfirmBy:           confirmBy,
25✔
385
                ConfirmedAt:         None[time.Time](), // may be set below
25✔
386
                ExpiresAt:           req.Duration.AddTo(confirmBy.UnwrapOr(now)),
25✔
387
                CreationContextJSON: json.RawMessage(buf),
25✔
388
        }
25✔
389
        if req.NotifyOnConfirm && req.ConfirmBy == nil {
26✔
390
                http.Error(w, "notification on confirm cannot be set for commitments with immediate confirmation", http.StatusConflict)
1✔
391
                return
1✔
392
        }
1✔
393
        dbCommitment.NotifyOnConfirm = req.NotifyOnConfirm
24✔
394

24✔
395
        if req.ConfirmBy == nil {
42✔
396
                // if not planned for confirmation in the future, confirm immediately (or fail)
18✔
397
                ok, err := datamodel.CanConfirmNewCommitment(*loc, dbProject.ID, req.Amount, p.Cluster, tx)
18✔
398
                if respondwith.ObfuscatedErrorText(w, err) {
18✔
399
                        return
×
400
                }
×
401
                if !ok {
18✔
402
                        http.Error(w, "not enough capacity available for immediate confirmation", http.StatusConflict)
×
403
                        return
×
404
                }
×
405
                dbCommitment.ConfirmedAt = Some(now)
18✔
406
                dbCommitment.State = db.CommitmentStateActive
18✔
407
        } else {
6✔
408
                dbCommitment.State = db.CommitmentStatePlanned
6✔
409
        }
6✔
410

411
        // create commitment
412
        err = tx.Insert(&dbCommitment)
24✔
413
        if respondwith.ObfuscatedErrorText(w, err) {
24✔
414
                return
×
415
        }
×
416

417
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
24✔
418
        if respondwith.ObfuscatedErrorText(w, err) {
24✔
419
                return
×
420
        }
×
421
        serviceInfo, ok := maybeServiceInfo.Unpack()
24✔
422
        if !ok {
24✔
423
                http.Error(w, "service not found", http.StatusNotFound)
×
424
                return
×
425
        }
×
426

427
        err = tx.Commit()
24✔
428
        if respondwith.ObfuscatedErrorText(w, err) {
24✔
NEW
429
                return
×
NEW
430
        }
×
431

432
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
24✔
433
        commitment := p.convertCommitmentToDisplayForm(dbCommitment, *loc, token, resourceInfo.Unit)
24✔
434
        p.auditor.Record(audittools.Event{
24✔
435
                Time:       now,
24✔
436
                Request:    r,
24✔
437
                User:       token,
24✔
438
                ReasonCode: http.StatusCreated,
24✔
439
                Action:     cadf.CreateAction,
24✔
440
                Target: commitmentEventTarget{
24✔
441
                        DomainID:        dbDomain.UUID,
24✔
442
                        DomainName:      dbDomain.Name,
24✔
443
                        ProjectID:       dbProject.UUID,
24✔
444
                        ProjectName:     dbProject.Name,
24✔
445
                        Commitments:     []limesresources.Commitment{commitment},
24✔
446
                        WorkflowContext: Some(creationContext),
24✔
447
                },
24✔
448
        })
24✔
449

24✔
450
        // if the commitment is immediately confirmed, trigger a capacity scrape in
24✔
451
        // order to ApplyComputedProjectQuotas based on the new commitment
24✔
452
        if dbCommitment.ConfirmedAt.IsSome() {
42✔
453
                _, err := p.DB.Exec(`UPDATE services SET next_scrape_at = $1 WHERE type = $2`, now, loc.ServiceType)
18✔
454
                if err != nil {
18✔
NEW
455
                        logg.Error("could not trigger a new capacity scrape: %s", err.Error())
×
UNCOV
456
                }
×
457
        }
458

459
        // display the possibly confirmed commitment to the user
460
        err = p.DB.SelectOne(&dbCommitment, `SELECT * FROM project_commitments WHERE id = $1`, dbCommitment.ID)
24✔
461
        if err != nil {
24✔
NEW
462
                logg.Error("could not load commitment: %s", err.Error())
×
UNCOV
463
        }
×
464

465
        respondwith.JSON(w, http.StatusCreated, map[string]any{"commitment": commitment})
24✔
466
}
467

468
// MergeProjectCommitments handles POST /v1/domains/:domain_id/projects/:project_id/commitments/merge.
469
func (p *v1Provider) MergeProjectCommitments(w http.ResponseWriter, r *http.Request) {
12✔
470
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/merge")
12✔
471
        token := p.CheckToken(r)
12✔
472
        if !token.Require(w, "project:edit") {
13✔
473
                return
1✔
474
        }
1✔
475
        dbDomain := p.FindDomainFromRequest(w, r)
11✔
476
        if dbDomain == nil {
12✔
477
                return
1✔
478
        }
1✔
479
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
10✔
480
        if dbProject == nil {
11✔
481
                return
1✔
482
        }
1✔
483
        var parseTarget struct {
9✔
484
                CommitmentIDs []db.ProjectCommitmentID `json:"commitment_ids"`
9✔
485
        }
9✔
486
        if !RequireJSON(w, r, &parseTarget) {
9✔
487
                return
×
488
        }
×
489
        commitmentIDs := parseTarget.CommitmentIDs
9✔
490
        if len(commitmentIDs) < 2 {
10✔
491
                http.Error(w, fmt.Sprintf("merging requires at least two commitments, but %d were given", len(commitmentIDs)), http.StatusBadRequest)
1✔
492
                return
1✔
493
        }
1✔
494

495
        // Load commitments
496
        dbCommitments := make([]db.ProjectCommitment, len(commitmentIDs))
8✔
497
        commitmentUUIDs := make([]db.ProjectCommitmentUUID, len(commitmentIDs))
8✔
498
        for i, commitmentID := range commitmentIDs {
24✔
499
                err := p.DB.SelectOne(&dbCommitments[i], findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
16✔
500
                if errors.Is(err, sql.ErrNoRows) {
17✔
501
                        http.Error(w, "no such commitment", http.StatusNotFound)
1✔
502
                        return
1✔
503
                } else if respondwith.ObfuscatedErrorText(w, err) {
16✔
504
                        return
×
505
                }
×
506
                commitmentUUIDs[i] = dbCommitments[i].UUID
15✔
507
        }
508

509
        // Verify that all commitments agree on resource and AZ and are active
510
        azResourceID := dbCommitments[0].AZResourceID
7✔
511
        for _, dbCommitment := range dbCommitments {
21✔
512
                if dbCommitment.AZResourceID != azResourceID {
16✔
513
                        http.Error(w, "all commitments must be on the same resource and AZ", http.StatusConflict)
2✔
514
                        return
2✔
515
                }
2✔
516
                if dbCommitment.State != db.CommitmentStateActive {
16✔
517
                        http.Error(w, "only active commitments may be merged", http.StatusConflict)
4✔
518
                        return
4✔
519
                }
4✔
520
        }
521

522
        var loc core.AZResourceLocation
1✔
523
        err := p.DB.QueryRow(findAZResourceLocationByIDQuery, azResourceID).
1✔
524
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
1✔
525
        if errors.Is(err, sql.ErrNoRows) {
1✔
526
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
527
                return
×
528
        } else if respondwith.ObfuscatedErrorText(w, err) {
1✔
529
                return
×
530
        }
×
531

532
        // Start transaction for creating new commitment and marking merged commitments as superseded
533
        tx, err := p.DB.Begin()
1✔
534
        if respondwith.ObfuscatedErrorText(w, err) {
1✔
535
                return
×
536
        }
×
537
        defer sqlext.RollbackUnlessCommitted(tx)
1✔
538

1✔
539
        // Create merged template
1✔
540
        now := p.timeNow()
1✔
541
        dbMergedCommitment := db.ProjectCommitment{
1✔
542
                UUID:         p.generateProjectCommitmentUUID(),
1✔
543
                ProjectID:    dbProject.ID,
1✔
544
                AZResourceID: azResourceID,
1✔
545
                Amount:       0,                                   // overwritten below
1✔
546
                Duration:     limesresources.CommitmentDuration{}, // overwritten below
1✔
547
                CreatedAt:    now,
1✔
548
                CreatorUUID:  token.UserUUID(),
1✔
549
                CreatorName:  fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
1✔
550
                ConfirmedAt:  Some(now),
1✔
551
                ExpiresAt:    time.Time{}, // overwritten below
1✔
552
                State:        db.CommitmentStateActive,
1✔
553
        }
1✔
554

1✔
555
        // Fill amount and latest expiration date
1✔
556
        for _, dbCommitment := range dbCommitments {
3✔
557
                dbMergedCommitment.Amount += dbCommitment.Amount
2✔
558
                if dbCommitment.ExpiresAt.After(dbMergedCommitment.ExpiresAt) {
4✔
559
                        dbMergedCommitment.ExpiresAt = dbCommitment.ExpiresAt
2✔
560
                        dbMergedCommitment.Duration = dbCommitment.Duration
2✔
561
                }
2✔
562
        }
563

564
        // Fill workflow context
565
        creationContext := db.CommitmentWorkflowContext{
1✔
566
                Reason:                 db.CommitmentReasonMerge,
1✔
567
                RelatedCommitmentIDs:   commitmentIDs,
1✔
568
                RelatedCommitmentUUIDs: commitmentUUIDs,
1✔
569
        }
1✔
570
        buf, err := json.Marshal(creationContext)
1✔
571
        if respondwith.ObfuscatedErrorText(w, err) {
1✔
572
                return
×
573
        }
×
574
        dbMergedCommitment.CreationContextJSON = json.RawMessage(buf)
1✔
575

1✔
576
        // Insert into database
1✔
577
        err = tx.Insert(&dbMergedCommitment)
1✔
578
        if respondwith.ObfuscatedErrorText(w, err) {
1✔
579
                return
×
580
        }
×
581

582
        // Mark merged commits as superseded
583
        supersedeContext := db.CommitmentWorkflowContext{
1✔
584
                Reason:                 db.CommitmentReasonMerge,
1✔
585
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbMergedCommitment.ID},
1✔
586
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbMergedCommitment.UUID},
1✔
587
        }
1✔
588
        buf, err = json.Marshal(supersedeContext)
1✔
589
        if respondwith.ObfuscatedErrorText(w, err) {
1✔
590
                return
×
591
        }
×
592
        for _, dbCommitment := range dbCommitments {
3✔
593
                dbCommitment.SupersededAt = Some(now)
2✔
594
                dbCommitment.SupersedeContextJSON = Some(json.RawMessage(buf))
2✔
595
                dbCommitment.State = db.CommitmentStateSuperseded
2✔
596
                _, err = tx.Update(&dbCommitment)
2✔
597
                if respondwith.ObfuscatedErrorText(w, err) {
2✔
598
                        return
×
599
                }
×
600
        }
601

602
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
1✔
603
        if respondwith.ObfuscatedErrorText(w, err) {
1✔
604
                return
×
605
        }
×
606
        serviceInfo, ok := maybeServiceInfo.Unpack()
1✔
607
        if !ok {
1✔
608
                http.Error(w, "service not found", http.StatusNotFound)
×
609
                return
×
610
        }
×
611

612
        err = tx.Commit()
1✔
613
        if respondwith.ObfuscatedErrorText(w, err) {
1✔
NEW
614
                return
×
NEW
615
        }
×
616

617
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
1✔
618
        c := p.convertCommitmentToDisplayForm(dbMergedCommitment, loc, token, resourceInfo.Unit)
1✔
619
        auditEvent := commitmentEventTarget{
1✔
620
                DomainID:        dbDomain.UUID,
1✔
621
                DomainName:      dbDomain.Name,
1✔
622
                ProjectID:       dbProject.UUID,
1✔
623
                ProjectName:     dbProject.Name,
1✔
624
                Commitments:     []limesresources.Commitment{c},
1✔
625
                WorkflowContext: Some(creationContext),
1✔
626
        }
1✔
627
        p.auditor.Record(audittools.Event{
1✔
628
                Time:       p.timeNow(),
1✔
629
                Request:    r,
1✔
630
                User:       token,
1✔
631
                ReasonCode: http.StatusAccepted,
1✔
632
                Action:     cadf.UpdateAction,
1✔
633
                Target:     auditEvent,
1✔
634
        })
1✔
635

1✔
636
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
637
}
638

639
// As per the API spec, commitments can be renewed 90 days in advance at the earliest.
640
const commitmentRenewalPeriod = 90 * 24 * time.Hour
641

642
// RenewProjectCommitments handles POST /v1/domains/:domain_id/projects/:project_id/commitments/:id/renew.
643
func (p *v1Provider) RenewProjectCommitments(w http.ResponseWriter, r *http.Request) {
6✔
644
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id/renew")
6✔
645
        token := p.CheckToken(r)
6✔
646
        if !token.Require(w, "project:edit") {
6✔
647
                return
×
648
        }
×
649
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
650
        if dbDomain == nil {
6✔
651
                return
×
652
        }
×
653
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
654
        if dbProject == nil {
6✔
655
                return
×
656
        }
×
657

658
        // Load commitment
659
        var dbCommitment db.ProjectCommitment
6✔
660
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
6✔
661
        if errors.Is(err, sql.ErrNoRows) {
6✔
662
                http.Error(w, "no such commitment", http.StatusNotFound)
×
663
                return
×
664
        } else if respondwith.ObfuscatedErrorText(w, err) {
6✔
665
                return
×
666
        }
×
667
        now := p.timeNow()
6✔
668

6✔
669
        // Check if commitment can be renewed
6✔
670
        var errs errext.ErrorSet
6✔
671
        if dbCommitment.State != db.CommitmentStateActive {
7✔
672
                errs.Addf("invalid state %q", dbCommitment.State)
1✔
673
        } else if now.After(dbCommitment.ExpiresAt) {
7✔
674
                errs.Addf("invalid state %q", db.CommitmentStateExpired)
1✔
675
        }
1✔
676
        if now.Before(dbCommitment.ExpiresAt.Add(-commitmentRenewalPeriod)) {
7✔
677
                errs.Addf("renewal attempt too early")
1✔
678
        }
1✔
679
        if dbCommitment.RenewContextJSON.IsSome() {
7✔
680
                errs.Addf("already renewed")
1✔
681
        }
1✔
682

683
        if !errs.IsEmpty() {
10✔
684
                msg := "cannot renew this commitment: " + errs.Join(", ")
4✔
685
                http.Error(w, msg, http.StatusConflict)
4✔
686
                return
4✔
687
        }
4✔
688

689
        // Create renewed commitment
690
        tx, err := p.DB.Begin()
2✔
691
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
692
                return
×
693
        }
×
694
        defer sqlext.RollbackUnlessCommitted(tx)
2✔
695

2✔
696
        var loc core.AZResourceLocation
2✔
697
        err = p.DB.QueryRow(findAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
2✔
698
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
2✔
699
        if errors.Is(err, sql.ErrNoRows) {
2✔
700
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
701
                return
×
702
        } else if respondwith.ObfuscatedErrorText(w, err) {
2✔
703
                return
×
704
        }
×
705

706
        creationContext := db.CommitmentWorkflowContext{
2✔
707
                Reason:                 db.CommitmentReasonRenew,
2✔
708
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbCommitment.ID},
2✔
709
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbCommitment.UUID},
2✔
710
        }
2✔
711
        buf, err := json.Marshal(creationContext)
2✔
712
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
713
                return
×
714
        }
×
715
        dbRenewedCommitment := db.ProjectCommitment{
2✔
716
                UUID:                p.generateProjectCommitmentUUID(),
2✔
717
                ProjectID:           dbProject.ID,
2✔
718
                AZResourceID:        dbCommitment.AZResourceID,
2✔
719
                Amount:              dbCommitment.Amount,
2✔
720
                Duration:            dbCommitment.Duration,
2✔
721
                CreatedAt:           now,
2✔
722
                CreatorUUID:         token.UserUUID(),
2✔
723
                CreatorName:         fmt.Sprintf("%s@%s", token.UserName(), token.UserDomainName()),
2✔
724
                ConfirmBy:           Some(dbCommitment.ExpiresAt),
2✔
725
                ExpiresAt:           dbCommitment.Duration.AddTo(dbCommitment.ExpiresAt),
2✔
726
                State:               db.CommitmentStatePlanned,
2✔
727
                CreationContextJSON: json.RawMessage(buf),
2✔
728
        }
2✔
729

2✔
730
        err = tx.Insert(&dbRenewedCommitment)
2✔
731
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
732
                return
×
733
        }
×
734

735
        renewContext := db.CommitmentWorkflowContext{
2✔
736
                Reason:                 db.CommitmentReasonRenew,
2✔
737
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbRenewedCommitment.ID},
2✔
738
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbRenewedCommitment.UUID},
2✔
739
        }
2✔
740
        buf, err = json.Marshal(renewContext)
2✔
741
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
742
                return
×
743
        }
×
744
        dbCommitment.RenewContextJSON = Some(json.RawMessage(buf))
2✔
745
        _, err = tx.Update(&dbCommitment)
2✔
746
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
747
                return
×
748
        }
×
749

750
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
2✔
751
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
752
                return
×
753
        }
×
754
        serviceInfo, ok := maybeServiceInfo.Unpack()
2✔
755
        if !ok {
2✔
756
                http.Error(w, "service not found", http.StatusNotFound)
×
757
                return
×
758
        }
×
759

760
        err = tx.Commit()
2✔
761
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
NEW
762
                return
×
NEW
763
        }
×
764

765
        // Create resultset and auditlogs
766
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
2✔
767
        c := p.convertCommitmentToDisplayForm(dbRenewedCommitment, loc, token, resourceInfo.Unit)
2✔
768
        auditEvent := commitmentEventTarget{
2✔
769
                DomainID:        dbDomain.UUID,
2✔
770
                DomainName:      dbDomain.Name,
2✔
771
                ProjectID:       dbProject.UUID,
2✔
772
                ProjectName:     dbProject.Name,
2✔
773
                Commitments:     []limesresources.Commitment{c},
2✔
774
                WorkflowContext: Some(creationContext),
2✔
775
        }
2✔
776

2✔
777
        p.auditor.Record(audittools.Event{
2✔
778
                Time:       p.timeNow(),
2✔
779
                Request:    r,
2✔
780
                User:       token,
2✔
781
                ReasonCode: http.StatusAccepted,
2✔
782
                Action:     cadf.UpdateAction,
2✔
783
                Target:     auditEvent,
2✔
784
        })
2✔
785

2✔
786
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
787
}
788

789
// DeleteProjectCommitment handles DELETE /v1/domains/:domain_id/projects/:project_id/commitments/:id.
790
func (p *v1Provider) DeleteProjectCommitment(w http.ResponseWriter, r *http.Request) {
8✔
791
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id")
8✔
792
        token := p.CheckToken(r)
8✔
793
        if !token.Require(w, "project:edit") { // NOTE: There is a more specific AuthZ check further down below.
8✔
794
                return
×
795
        }
×
796
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
797
        if dbDomain == nil {
9✔
798
                return
1✔
799
        }
1✔
800
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
7✔
801
        if dbProject == nil {
8✔
802
                return
1✔
803
        }
1✔
804

805
        // load commitment
806
        var dbCommitment db.ProjectCommitment
6✔
807
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
6✔
808
        if errors.Is(err, sql.ErrNoRows) {
7✔
809
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
810
                return
1✔
811
        } else if respondwith.ObfuscatedErrorText(w, err) {
6✔
812
                return
×
813
        }
×
814
        var loc core.AZResourceLocation
5✔
815
        err = p.DB.QueryRow(findAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
5✔
816
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
5✔
817
        if errors.Is(err, sql.ErrNoRows) {
5✔
818
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
819
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
820
                return
×
821
        } else if respondwith.ObfuscatedErrorText(w, err) {
5✔
822
                return
×
823
        }
×
824

825
        // check authorization for this specific commitment
826
        if !p.canDeleteCommitment(token, dbCommitment) {
6✔
827
                http.Error(w, "Forbidden", http.StatusForbidden)
1✔
828
                return
1✔
829
        }
1✔
830

831
        // perform deletion
832
        _, err = p.DB.Delete(&dbCommitment)
4✔
833
        if respondwith.ObfuscatedErrorText(w, err) {
4✔
834
                return
×
835
        }
×
836
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
4✔
837
        if respondwith.ObfuscatedErrorText(w, err) {
4✔
838
                return
×
839
        }
×
840
        serviceInfo, ok := maybeServiceInfo.Unpack()
4✔
841
        if !ok {
4✔
842
                http.Error(w, "service not found", http.StatusNotFound)
×
843
                return
×
844
        }
×
845
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
4✔
846
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
4✔
847
        p.auditor.Record(audittools.Event{
4✔
848
                Time:       p.timeNow(),
4✔
849
                Request:    r,
4✔
850
                User:       token,
4✔
851
                ReasonCode: http.StatusNoContent,
4✔
852
                Action:     cadf.DeleteAction,
4✔
853
                Target: commitmentEventTarget{
4✔
854
                        DomainID:    dbDomain.UUID,
4✔
855
                        DomainName:  dbDomain.Name,
4✔
856
                        ProjectID:   dbProject.UUID,
4✔
857
                        ProjectName: dbProject.Name,
4✔
858
                        Commitments: []limesresources.Commitment{c},
4✔
859
                },
4✔
860
        })
4✔
861

4✔
862
        w.WriteHeader(http.StatusNoContent)
4✔
863
}
864

865
func (p *v1Provider) canDeleteCommitment(token *gopherpolicy.Token, commitment db.ProjectCommitment) bool {
64✔
866
        // up to 24 hours after creation of fresh commitments, future commitments can still be deleted by their creators
64✔
867
        if commitment.State == db.CommitmentStatePlanned || commitment.State == db.CommitmentStatePending || commitment.State == db.CommitmentStateActive {
128✔
868
                var creationContext db.CommitmentWorkflowContext
64✔
869
                err := json.Unmarshal(commitment.CreationContextJSON, &creationContext)
64✔
870
                if err == nil && creationContext.Reason == db.CommitmentReasonCreate && p.timeNow().Before(commitment.CreatedAt.Add(24*time.Hour)) {
104✔
871
                        if token.Check("project:edit") {
80✔
872
                                return true
40✔
873
                        }
40✔
874
                }
875
        }
876

877
        // afterwards, a more specific permission is required to delete it
878
        //
879
        // This protects cloud admins making capacity planning decisions based on future commitments
880
        // from having their forecasts ruined by project admins suffering from buyer's remorse.
881
        return token.Check("project:uncommit")
24✔
882
}
883

884
// StartCommitmentTransfer handles POST /v1/domains/:id/projects/:id/commitments/:id/start-transfer
885
func (p *v1Provider) StartCommitmentTransfer(w http.ResponseWriter, r *http.Request) {
8✔
886
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/commitments/:id/start-transfer")
8✔
887
        token := p.CheckToken(r)
8✔
888
        if !token.Require(w, "project:edit") {
8✔
889
                return
×
890
        }
×
891
        dbDomain := p.FindDomainFromRequest(w, r)
8✔
892
        if dbDomain == nil {
8✔
893
                return
×
894
        }
×
895
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
8✔
896
        if dbProject == nil {
8✔
897
                return
×
898
        }
×
899
        // TODO: eventually migrate this struct into go-api-declarations
900
        var parseTarget struct {
8✔
901
                Request struct {
8✔
902
                        Amount         uint64                                  `json:"amount"`
8✔
903
                        TransferStatus limesresources.CommitmentTransferStatus `json:"transfer_status,omitempty"`
8✔
904
                } `json:"commitment"`
8✔
905
        }
8✔
906
        if !RequireJSON(w, r, &parseTarget) {
8✔
907
                return
×
908
        }
×
909
        req := parseTarget.Request
8✔
910

8✔
911
        if req.TransferStatus != limesresources.CommitmentTransferStatusUnlisted && req.TransferStatus != limesresources.CommitmentTransferStatusPublic {
8✔
912
                http.Error(w, fmt.Sprintf("Invalid transfer_status code. Must be %s or %s.", limesresources.CommitmentTransferStatusUnlisted, limesresources.CommitmentTransferStatusPublic), http.StatusBadRequest)
×
913
                return
×
914
        }
×
915

916
        if req.Amount <= 0 {
9✔
917
                http.Error(w, "delivered amount needs to be a positive value.", http.StatusBadRequest)
1✔
918
                return
1✔
919
        }
1✔
920

921
        // load commitment
922
        var dbCommitment db.ProjectCommitment
7✔
923
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, mux.Vars(r)["id"], dbProject.ID)
7✔
924
        if errors.Is(err, sql.ErrNoRows) {
7✔
925
                http.Error(w, "no such commitment", http.StatusNotFound)
×
926
                return
×
927
        } else if respondwith.ObfuscatedErrorText(w, err) {
7✔
928
                return
×
929
        }
×
930

931
        // Mark whole commitment or a newly created, splitted one as transferrable.
932
        tx, err := p.DB.Begin()
7✔
933
        if respondwith.ObfuscatedErrorText(w, err) {
7✔
934
                return
×
935
        }
×
936
        defer sqlext.RollbackUnlessCommitted(tx)
7✔
937
        transferToken := p.generateTransferToken()
7✔
938

7✔
939
        // Deny requests with a greater amount than the commitment.
7✔
940
        if req.Amount > dbCommitment.Amount {
8✔
941
                http.Error(w, "delivered amount exceeds the commitment amount.", http.StatusBadRequest)
1✔
942
                return
1✔
943
        }
1✔
944

945
        if req.Amount == dbCommitment.Amount {
10✔
946
                dbCommitment.TransferStatus = req.TransferStatus
4✔
947
                dbCommitment.TransferToken = Some(transferToken)
4✔
948
                _, err = tx.Update(&dbCommitment)
4✔
949
                if respondwith.ObfuscatedErrorText(w, err) {
4✔
950
                        return
×
951
                }
×
952
        } else {
2✔
953
                now := p.timeNow()
2✔
954
                transferAmount := req.Amount
2✔
955
                remainingAmount := dbCommitment.Amount - req.Amount
2✔
956
                transferCommitment, err := p.buildSplitCommitment(dbCommitment, transferAmount)
2✔
957
                if respondwith.ObfuscatedErrorText(w, err) {
2✔
958
                        return
×
959
                }
×
960
                transferCommitment.TransferStatus = req.TransferStatus
2✔
961
                transferCommitment.TransferToken = Some(transferToken)
2✔
962
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
2✔
963
                if respondwith.ObfuscatedErrorText(w, err) {
2✔
964
                        return
×
965
                }
×
966
                err = tx.Insert(&transferCommitment)
2✔
967
                if respondwith.ObfuscatedErrorText(w, err) {
2✔
968
                        return
×
969
                }
×
970
                err = tx.Insert(&remainingCommitment)
2✔
971
                if respondwith.ObfuscatedErrorText(w, err) {
2✔
972
                        return
×
973
                }
×
974
                supersedeContext := db.CommitmentWorkflowContext{
2✔
975
                        Reason:                 db.CommitmentReasonSplit,
2✔
976
                        RelatedCommitmentIDs:   []db.ProjectCommitmentID{transferCommitment.ID, remainingCommitment.ID},
2✔
977
                        RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{transferCommitment.UUID, remainingCommitment.UUID},
2✔
978
                }
2✔
979
                buf, err := json.Marshal(supersedeContext)
2✔
980
                if respondwith.ObfuscatedErrorText(w, err) {
2✔
981
                        return
×
982
                }
×
983
                dbCommitment.State = db.CommitmentStateSuperseded
2✔
984
                dbCommitment.SupersededAt = Some(now)
2✔
985
                dbCommitment.SupersedeContextJSON = Some(json.RawMessage(buf))
2✔
986
                _, err = tx.Update(&dbCommitment)
2✔
987
                if respondwith.ObfuscatedErrorText(w, err) {
2✔
988
                        return
×
989
                }
×
990
                dbCommitment = transferCommitment
2✔
991
        }
992

993
        var loc core.AZResourceLocation
6✔
994
        err = p.DB.QueryRow(findAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
6✔
995
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
6✔
996
        if errors.Is(err, sql.ErrNoRows) {
6✔
997
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
998
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
999
                return
×
1000
        } else if respondwith.ObfuscatedErrorText(w, err) {
6✔
1001
                return
×
1002
        }
×
1003

1004
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
6✔
1005
        if respondwith.ObfuscatedErrorText(w, err) {
6✔
1006
                return
×
1007
        }
×
1008
        serviceInfo, ok := maybeServiceInfo.Unpack()
6✔
1009
        if !ok {
6✔
1010
                http.Error(w, "service not found", http.StatusNotFound)
×
1011
                return
×
1012
        }
×
1013

1014
        err = tx.Commit()
6✔
1015
        if respondwith.ObfuscatedErrorText(w, err) {
6✔
1016
                return
×
1017
        }
×
1018

1019
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
6✔
1020
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
6✔
1021
        p.auditor.Record(audittools.Event{
6✔
1022
                Time:       p.timeNow(),
6✔
1023
                Request:    r,
6✔
1024
                User:       token,
6✔
1025
                ReasonCode: http.StatusAccepted,
6✔
1026
                Action:     cadf.UpdateAction,
6✔
1027
                Target: commitmentEventTarget{
6✔
1028
                        DomainID:    dbDomain.UUID,
6✔
1029
                        DomainName:  dbDomain.Name,
6✔
1030
                        ProjectID:   dbProject.UUID,
6✔
1031
                        ProjectName: dbProject.Name,
6✔
1032
                        Commitments: []limesresources.Commitment{c},
6✔
1033
                },
6✔
1034
        })
6✔
1035
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
6✔
1036
}
1037

1038
func (p *v1Provider) buildSplitCommitment(dbCommitment db.ProjectCommitment, amount uint64) (db.ProjectCommitment, error) {
5✔
1039
        now := p.timeNow()
5✔
1040
        creationContext := db.CommitmentWorkflowContext{
5✔
1041
                Reason:                 db.CommitmentReasonSplit,
5✔
1042
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbCommitment.ID},
5✔
1043
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbCommitment.UUID},
5✔
1044
        }
5✔
1045
        buf, err := json.Marshal(creationContext)
5✔
1046
        if err != nil {
5✔
1047
                return db.ProjectCommitment{}, err
×
1048
        }
×
1049
        return db.ProjectCommitment{
5✔
1050
                UUID:                p.generateProjectCommitmentUUID(),
5✔
1051
                ProjectID:           dbCommitment.ProjectID,
5✔
1052
                AZResourceID:        dbCommitment.AZResourceID,
5✔
1053
                Amount:              amount,
5✔
1054
                Duration:            dbCommitment.Duration,
5✔
1055
                CreatedAt:           now,
5✔
1056
                CreatorUUID:         dbCommitment.CreatorUUID,
5✔
1057
                CreatorName:         dbCommitment.CreatorName,
5✔
1058
                ConfirmBy:           dbCommitment.ConfirmBy,
5✔
1059
                ConfirmedAt:         dbCommitment.ConfirmedAt,
5✔
1060
                ExpiresAt:           dbCommitment.ExpiresAt,
5✔
1061
                CreationContextJSON: json.RawMessage(buf),
5✔
1062
                State:               dbCommitment.State,
5✔
1063
        }, nil
5✔
1064
}
1065

1066
func (p *v1Provider) buildConvertedCommitment(dbCommitment db.ProjectCommitment, azResourceID db.AZResourceID, amount uint64) (db.ProjectCommitment, error) {
2✔
1067
        now := p.timeNow()
2✔
1068
        creationContext := db.CommitmentWorkflowContext{
2✔
1069
                Reason:                 db.CommitmentReasonConvert,
2✔
1070
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1071
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbCommitment.UUID},
2✔
1072
        }
2✔
1073
        buf, err := json.Marshal(creationContext)
2✔
1074
        if err != nil {
2✔
1075
                return db.ProjectCommitment{}, err
×
1076
        }
×
1077
        return db.ProjectCommitment{
2✔
1078
                UUID:                p.generateProjectCommitmentUUID(),
2✔
1079
                ProjectID:           dbCommitment.ProjectID,
2✔
1080
                AZResourceID:        azResourceID,
2✔
1081
                Amount:              amount,
2✔
1082
                Duration:            dbCommitment.Duration,
2✔
1083
                CreatedAt:           now,
2✔
1084
                CreatorUUID:         dbCommitment.CreatorUUID,
2✔
1085
                CreatorName:         dbCommitment.CreatorName,
2✔
1086
                ConfirmBy:           dbCommitment.ConfirmBy,
2✔
1087
                ConfirmedAt:         dbCommitment.ConfirmedAt,
2✔
1088
                ExpiresAt:           dbCommitment.ExpiresAt,
2✔
1089
                CreationContextJSON: json.RawMessage(buf),
2✔
1090
                State:               dbCommitment.State,
2✔
1091
        }, nil
2✔
1092
}
1093

1094
// GetCommitmentByTransferToken handles GET /v1/commitments/{token}
1095
func (p *v1Provider) GetCommitmentByTransferToken(w http.ResponseWriter, r *http.Request) {
2✔
1096
        httpapi.IdentifyEndpoint(r, "/v1/commitments/:token")
2✔
1097
        token := p.CheckToken(r)
2✔
1098
        if !token.Require(w, "cluster:show_basic") {
2✔
1099
                return
×
1100
        }
×
1101
        transferToken := mux.Vars(r)["token"]
2✔
1102

2✔
1103
        // The token column is a unique key, so we expect only one result.
2✔
1104
        var dbCommitment db.ProjectCommitment
2✔
1105
        err := p.DB.SelectOne(&dbCommitment, findCommitmentByTransferToken, transferToken)
2✔
1106
        if errors.Is(err, sql.ErrNoRows) {
3✔
1107
                http.Error(w, "no matching commitment found.", http.StatusNotFound)
1✔
1108
                return
1✔
1109
        } else if respondwith.ObfuscatedErrorText(w, err) {
2✔
1110
                return
×
1111
        }
×
1112

1113
        var loc core.AZResourceLocation
1✔
1114
        err = p.DB.QueryRow(findAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
1✔
1115
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
1✔
1116
        if errors.Is(err, sql.ErrNoRows) {
1✔
1117
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1118
                http.Error(w, "location data not found.", http.StatusNotFound)
×
1119
                return
×
1120
        } else if respondwith.ObfuscatedErrorText(w, err) {
1✔
1121
                return
×
1122
        }
×
1123

1124
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
1✔
1125
        if respondwith.ObfuscatedErrorText(w, err) {
1✔
1126
                return
×
1127
        }
×
1128
        serviceInfo, ok := maybeServiceInfo.Unpack()
1✔
1129
        if !ok {
1✔
1130
                http.Error(w, "service not found", http.StatusNotFound)
×
1131
                return
×
1132
        }
×
1133
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
1✔
1134
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
1✔
1135
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
1✔
1136
}
1137

1138
// TransferCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/transfer-commitment/{id}?token={token}
1139
func (p *v1Provider) TransferCommitment(w http.ResponseWriter, r *http.Request) {
5✔
1140
        httpapi.IdentifyEndpoint(r, "/v1/domains/:id/projects/:id/transfer-commitment/:id")
5✔
1141
        token := p.CheckToken(r)
5✔
1142
        if !token.Require(w, "project:edit") {
5✔
1143
                return
×
1144
        }
×
1145
        transferToken := r.Header.Get("Transfer-Token")
5✔
1146
        if transferToken == "" {
6✔
1147
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
1✔
1148
                return
1✔
1149
        }
1✔
1150
        commitmentID := mux.Vars(r)["id"]
4✔
1151
        if commitmentID == "" {
4✔
1152
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1153
                return
×
1154
        }
×
1155
        dbDomain := p.FindDomainFromRequest(w, r)
4✔
1156
        if dbDomain == nil {
4✔
1157
                return
×
1158
        }
×
1159
        targetProject := p.FindProjectFromRequest(w, r, dbDomain)
4✔
1160
        if targetProject == nil {
4✔
1161
                return
×
1162
        }
×
1163

1164
        // find commitment by transfer_token
1165
        var dbCommitment db.ProjectCommitment
4✔
1166
        err := p.DB.SelectOne(&dbCommitment, getCommitmentWithMatchingTransferTokenQuery, commitmentID, transferToken)
4✔
1167
        if errors.Is(err, sql.ErrNoRows) {
5✔
1168
                http.Error(w, "no matching commitment found", http.StatusNotFound)
1✔
1169
                return
1✔
1170
        } else if respondwith.ObfuscatedErrorText(w, err) {
4✔
1171
                return
×
1172
        }
×
1173

1174
        var loc core.AZResourceLocation
3✔
1175
        err = p.DB.QueryRow(findAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
3✔
1176
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
3✔
1177
        if errors.Is(err, sql.ErrNoRows) {
3✔
1178
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1179
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1180
                return
×
1181
        } else if respondwith.ObfuscatedErrorText(w, err) {
3✔
1182
                return
×
1183
        }
×
1184

1185
        // check that the target project allows commitments at all
1186
        var (
3✔
1187
                azResourceID              db.AZResourceID
3✔
1188
                resourceAllowsCommitments bool
3✔
1189
        )
3✔
1190
        err = p.DB.QueryRow(findAZResourceIDByLocationQuery, targetProject.ID, loc.ServiceType, loc.ResourceName, loc.AvailabilityZone).
3✔
1191
                Scan(&azResourceID, &resourceAllowsCommitments)
3✔
1192
        if respondwith.ObfuscatedErrorText(w, err) {
3✔
1193
                return
×
1194
        }
×
1195
        if !resourceAllowsCommitments {
3✔
1196
                msg := fmt.Sprintf("resource %s/%s is not enabled in the target project", loc.ServiceType, loc.ResourceName)
×
1197
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1198
                return
×
1199
        }
×
1200
        _ = azResourceID // returned by the above query, but not used in this function
3✔
1201

3✔
1202
        // validate that we have enough committable capacity on the receiving side
3✔
1203
        tx, err := p.DB.Begin()
3✔
1204
        if respondwith.ObfuscatedErrorText(w, err) {
3✔
1205
                return
×
1206
        }
×
1207
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1208
        ok, err := datamodel.CanMoveExistingCommitment(dbCommitment.Amount, loc, dbCommitment.ProjectID, targetProject.ID, p.Cluster, tx)
3✔
1209
        if respondwith.ObfuscatedErrorText(w, err) {
3✔
1210
                return
×
1211
        }
×
1212
        if !ok {
4✔
1213
                http.Error(w, "not enough committable capacity on the receiving side", http.StatusConflict)
1✔
1214
                return
1✔
1215
        }
1✔
1216

1217
        dbCommitment.TransferStatus = ""
2✔
1218
        dbCommitment.TransferToken = None[string]()
2✔
1219
        dbCommitment.ProjectID = targetProject.ID
2✔
1220
        _, err = tx.Update(&dbCommitment)
2✔
1221
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
1222
                return
×
1223
        }
×
1224

1225
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
2✔
1226
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
1227
                return
×
1228
        }
×
1229
        serviceInfo, ok := maybeServiceInfo.Unpack()
2✔
1230
        if !ok {
2✔
1231
                http.Error(w, "service not found", http.StatusNotFound)
×
1232
                return
×
1233
        }
×
1234

1235
        err = tx.Commit()
2✔
1236
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
NEW
1237
                return
×
NEW
1238
        }
×
1239

1240
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
2✔
1241
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
2✔
1242
        p.auditor.Record(audittools.Event{
2✔
1243
                Time:       p.timeNow(),
2✔
1244
                Request:    r,
2✔
1245
                User:       token,
2✔
1246
                ReasonCode: http.StatusAccepted,
2✔
1247
                Action:     cadf.UpdateAction,
2✔
1248
                Target: commitmentEventTarget{
2✔
1249
                        DomainID:    dbDomain.UUID,
2✔
1250
                        DomainName:  dbDomain.Name,
2✔
1251
                        ProjectID:   targetProject.UUID,
2✔
1252
                        ProjectName: targetProject.Name,
2✔
1253
                        Commitments: []limesresources.Commitment{c},
2✔
1254
                },
2✔
1255
        })
2✔
1256

2✔
1257
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1258
}
1259

1260
// GetCommitmentConversion handles GET /v1/commitment-conversion/{service_type}/{resource_name}
1261
func (p *v1Provider) GetCommitmentConversions(w http.ResponseWriter, r *http.Request) {
2✔
1262
        httpapi.IdentifyEndpoint(r, "/v1/commitment-conversion/:service_type/:resource_name")
2✔
1263
        token := p.CheckToken(r)
2✔
1264
        if !token.Require(w, "cluster:show_basic") {
2✔
1265
                return
×
1266
        }
×
1267

1268
        // TODO v2 API: This endpoint should be project-scoped in order to make it
1269
        // easier to select the correct domain scope for the CommitmentBehavior.
1270
        forTokenScope := func(behavior core.CommitmentBehavior) core.ScopedCommitmentBehavior {
13✔
1271
                name := cmp.Or(token.ProjectScopeDomainName(), token.DomainScopeName(), "")
11✔
1272
                if name != "" {
22✔
1273
                        return behavior.ForDomain(name)
11✔
1274
                }
11✔
1275
                return behavior.ForCluster()
×
1276
        }
1277

1278
        // validate request
1279
        vars := mux.Vars(r)
2✔
1280
        serviceInfos, err := p.Cluster.AllServiceInfos()
2✔
1281
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
1282
                return
×
1283
        }
×
1284

1285
        nm := core.BuildResourceNameMapping(p.Cluster, serviceInfos)
2✔
1286
        sourceServiceType, sourceResourceName, exists := nm.MapFromV1API(
2✔
1287
                limes.ServiceType(vars["service_type"]),
2✔
1288
                limesresources.ResourceName(vars["resource_name"]),
2✔
1289
        )
2✔
1290
        if !exists {
2✔
1291
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", vars["service_type"], vars["resource_name"])
×
1292
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1293
                return
×
1294
        }
×
1295
        sourceBehavior := forTokenScope(p.Cluster.CommitmentBehaviorForResource(sourceServiceType, sourceResourceName))
2✔
1296

2✔
1297
        serviceInfo := core.InfoForService(serviceInfos, sourceServiceType)
2✔
1298
        sourceResInfo := core.InfoForResource(serviceInfo, sourceResourceName)
2✔
1299

2✔
1300
        // enumerate possible conversions
2✔
1301
        conversions := make([]limesresources.CommitmentConversionRule, 0)
2✔
1302
        if sourceBehavior.ConversionRule.IsSome() {
4✔
1303
                for _, targetServiceType := range slices.Sorted(maps.Keys(serviceInfos)) {
8✔
1304
                        for targetResourceName, targetResInfo := range serviceInfos[targetServiceType].Resources {
28✔
1305
                                if sourceServiceType == targetServiceType && sourceResourceName == targetResourceName {
24✔
1306
                                        continue
2✔
1307
                                }
1308
                                if sourceResInfo.Unit != targetResInfo.Unit {
31✔
1309
                                        continue
11✔
1310
                                }
1311

1312
                                targetBehavior := forTokenScope(p.Cluster.CommitmentBehaviorForResource(targetServiceType, targetResourceName))
9✔
1313
                                if rate, ok := sourceBehavior.GetConversionRateTo(targetBehavior).Unpack(); ok {
13✔
1314
                                        apiServiceType, apiResourceName, ok := nm.MapToV1API(targetServiceType, targetResourceName)
4✔
1315
                                        if ok {
8✔
1316
                                                conversions = append(conversions, limesresources.CommitmentConversionRule{
4✔
1317
                                                        FromAmount:     rate.FromAmount,
4✔
1318
                                                        ToAmount:       rate.ToAmount,
4✔
1319
                                                        TargetService:  apiServiceType,
4✔
1320
                                                        TargetResource: apiResourceName,
4✔
1321
                                                })
4✔
1322
                                        }
4✔
1323
                                }
1324
                        }
1325
                }
1326
        }
1327

1328
        // use a defined sorting to ensure deterministic behavior in tests
1329
        slices.SortFunc(conversions, func(lhs, rhs limesresources.CommitmentConversionRule) int {
6✔
1330
                result := strings.Compare(string(lhs.TargetService), string(rhs.TargetService))
4✔
1331
                if result != 0 {
7✔
1332
                        return result
3✔
1333
                }
3✔
1334
                return strings.Compare(string(lhs.TargetResource), string(rhs.TargetResource))
1✔
1335
        })
1336

1337
        respondwith.JSON(w, http.StatusOK, map[string]any{"conversions": conversions})
2✔
1338
}
1339

1340
// ConvertCommitment handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/convert
1341
func (p *v1Provider) ConvertCommitment(w http.ResponseWriter, r *http.Request) {
9✔
1342
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/convert")
9✔
1343
        token := p.CheckToken(r)
9✔
1344
        if !token.Require(w, "project:edit") {
9✔
1345
                return
×
1346
        }
×
1347
        commitmentID := mux.Vars(r)["commitment_id"]
9✔
1348
        if commitmentID == "" {
9✔
1349
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1350
                return
×
1351
        }
×
1352
        dbDomain := p.FindDomainFromRequest(w, r)
9✔
1353
        if dbDomain == nil {
9✔
1354
                return
×
1355
        }
×
1356
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
9✔
1357
        if dbProject == nil {
9✔
1358
                return
×
1359
        }
×
1360

1361
        // section: sourceBehavior
1362
        var dbCommitment db.ProjectCommitment
9✔
1363
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
9✔
1364
        if errors.Is(err, sql.ErrNoRows) {
10✔
1365
                http.Error(w, "no such commitment", http.StatusNotFound)
1✔
1366
                return
1✔
1367
        } else if respondwith.ObfuscatedErrorText(w, err) {
9✔
1368
                return
×
1369
        }
×
1370
        var sourceLoc core.AZResourceLocation
8✔
1371
        err = p.DB.QueryRow(findAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
8✔
1372
                Scan(&sourceLoc.ServiceType, &sourceLoc.ResourceName, &sourceLoc.AvailabilityZone)
8✔
1373
        if errors.Is(err, sql.ErrNoRows) {
8✔
1374
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1375
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1376
                return
×
1377
        } else if respondwith.ObfuscatedErrorText(w, err) {
8✔
1378
                return
×
1379
        }
×
1380
        sourceBehavior := p.Cluster.CommitmentBehaviorForResource(sourceLoc.ServiceType, sourceLoc.ResourceName).ForDomain(dbDomain.Name)
8✔
1381

8✔
1382
        // section: targetBehavior
8✔
1383
        var parseTarget struct {
8✔
1384
                Request struct {
8✔
1385
                        TargetService  limes.ServiceType           `json:"target_service"`
8✔
1386
                        TargetResource limesresources.ResourceName `json:"target_resource"`
8✔
1387
                        SourceAmount   uint64                      `json:"source_amount"`
8✔
1388
                        TargetAmount   uint64                      `json:"target_amount"`
8✔
1389
                } `json:"commitment"`
8✔
1390
        }
8✔
1391
        if !RequireJSON(w, r, &parseTarget) {
8✔
1392
                return
×
1393
        }
×
1394
        req := parseTarget.Request
8✔
1395
        serviceInfos, err := p.Cluster.AllServiceInfos()
8✔
1396
        if respondwith.ObfuscatedErrorText(w, err) {
8✔
1397
                return
×
1398
        }
×
1399
        nm := core.BuildResourceNameMapping(p.Cluster, serviceInfos)
8✔
1400
        targetServiceType, targetResourceName, exists := nm.MapFromV1API(req.TargetService, req.TargetResource)
8✔
1401
        if !exists {
8✔
1402
                msg := fmt.Sprintf("no such service and/or resource: %s/%s", req.TargetService, req.TargetResource)
×
1403
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1404
                return
×
1405
        }
×
1406
        targetBehavior := p.Cluster.CommitmentBehaviorForResource(targetServiceType, targetResourceName).ForDomain(dbDomain.Name)
8✔
1407
        if sourceLoc.ResourceName == targetResourceName && sourceLoc.ServiceType == targetServiceType {
9✔
1408
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
1✔
1409
                return
1✔
1410
        }
1✔
1411
        if len(targetBehavior.Durations) == 0 {
7✔
1412
                msg := fmt.Sprintf("commitments are not enabled for resource %s/%s", req.TargetService, req.TargetResource)
×
1413
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1414
                return
×
1415
        }
×
1416
        rate, ok := sourceBehavior.GetConversionRateTo(targetBehavior).Unpack()
7✔
1417
        if !ok {
8✔
1418
                msg := fmt.Sprintf("commitment is not convertible into resource %s/%s", req.TargetService, req.TargetResource)
1✔
1419
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1420
                return
1✔
1421
        }
1✔
1422

1423
        // section: conversion
1424
        if req.SourceAmount > dbCommitment.Amount {
6✔
1425
                msg := fmt.Sprintf("unprocessable source amount. provided: %v, commitment: %v", req.SourceAmount, dbCommitment.Amount)
×
1426
                http.Error(w, msg, http.StatusConflict)
×
1427
                return
×
1428
        }
×
1429
        conversionAmount := (req.SourceAmount / rate.FromAmount) * rate.ToAmount
6✔
1430
        remainderAmount := req.SourceAmount % rate.FromAmount
6✔
1431
        if remainderAmount > 0 {
8✔
1432
                msg := fmt.Sprintf("amount: %v does not fit into conversion rate of: %v", req.SourceAmount, rate.FromAmount)
2✔
1433
                http.Error(w, msg, http.StatusConflict)
2✔
1434
                return
2✔
1435
        }
2✔
1436
        if conversionAmount != req.TargetAmount {
5✔
1437
                msg := fmt.Sprintf("conversion mismatch. provided: %v, calculated: %v", req.TargetAmount, conversionAmount)
1✔
1438
                http.Error(w, msg, http.StatusConflict)
1✔
1439
                return
1✔
1440
        }
1✔
1441

1442
        tx, err := p.DB.Begin()
3✔
1443
        if respondwith.ObfuscatedErrorText(w, err) {
3✔
1444
                return
×
1445
        }
×
1446
        defer sqlext.RollbackUnlessCommitted(tx)
3✔
1447

3✔
1448
        var (
3✔
1449
                targetAZResourceID        db.AZResourceID
3✔
1450
                resourceAllowsCommitments bool
3✔
1451
        )
3✔
1452
        err = p.DB.QueryRow(findAZResourceIDByLocationQuery, dbProject.ID, targetServiceType, targetResourceName, sourceLoc.AvailabilityZone).
3✔
1453
                Scan(&targetAZResourceID, &resourceAllowsCommitments)
3✔
1454
        if respondwith.ObfuscatedErrorText(w, err) {
3✔
1455
                return
×
1456
        }
×
1457
        // defense in depth. ServiceType and ResourceName of source and target are already checked. Here it's possible to explicitly check the ID's.
1458
        if dbCommitment.AZResourceID == targetAZResourceID {
3✔
1459
                http.Error(w, "conversion attempt to the same resource.", http.StatusConflict)
×
1460
                return
×
1461
        }
×
1462
        if !resourceAllowsCommitments {
3✔
1463
                msg := fmt.Sprintf("resource %s/%s is not enabled in this project", targetServiceType, targetResourceName)
×
1464
                http.Error(w, msg, http.StatusUnprocessableEntity)
×
1465
                return
×
1466
        }
×
1467
        targetLoc := core.AZResourceLocation{
3✔
1468
                ServiceType:      targetServiceType,
3✔
1469
                ResourceName:     targetResourceName,
3✔
1470
                AvailabilityZone: sourceLoc.AvailabilityZone,
3✔
1471
        }
3✔
1472
        // The commitment at the source resource was already confirmed and checked.
3✔
1473
        // Therefore only the addition to the target resource has to be checked against.
3✔
1474
        if dbCommitment.ConfirmedAt.IsSome() {
5✔
1475
                ok, err := datamodel.CanConfirmNewCommitment(targetLoc, dbProject.ID, conversionAmount, p.Cluster, p.DB)
2✔
1476
                if respondwith.ObfuscatedErrorText(w, err) {
2✔
1477
                        return
×
1478
                }
×
1479
                if !ok {
3✔
1480
                        http.Error(w, "not enough capacity to confirm the commitment", http.StatusUnprocessableEntity)
1✔
1481
                        return
1✔
1482
                }
1✔
1483
        }
1484

1485
        auditEvent := commitmentEventTarget{
2✔
1486
                DomainID:    dbDomain.UUID,
2✔
1487
                DomainName:  dbDomain.Name,
2✔
1488
                ProjectID:   dbProject.UUID,
2✔
1489
                ProjectName: dbProject.Name,
2✔
1490
        }
2✔
1491

2✔
1492
        var (
2✔
1493
                relatedCommitmentIDs   []db.ProjectCommitmentID
2✔
1494
                relatedCommitmentUUIDs []db.ProjectCommitmentUUID
2✔
1495
        )
2✔
1496
        remainingAmount := dbCommitment.Amount - req.SourceAmount
2✔
1497
        serviceInfo := core.InfoForService(serviceInfos, sourceLoc.ServiceType)
2✔
1498
        resourceInfo := core.InfoForResource(serviceInfo, sourceLoc.ResourceName)
2✔
1499
        if remainingAmount > 0 {
3✔
1500
                remainingCommitment, err := p.buildSplitCommitment(dbCommitment, remainingAmount)
1✔
1501
                if respondwith.ObfuscatedErrorText(w, err) {
1✔
1502
                        return
×
1503
                }
×
1504
                relatedCommitmentIDs = append(relatedCommitmentIDs, remainingCommitment.ID)
1✔
1505
                relatedCommitmentUUIDs = append(relatedCommitmentUUIDs, remainingCommitment.UUID)
1✔
1506
                err = tx.Insert(&remainingCommitment)
1✔
1507
                if respondwith.ObfuscatedErrorText(w, err) {
1✔
1508
                        return
×
1509
                }
×
1510
                auditEvent.Commitments = append(auditEvent.Commitments,
1✔
1511
                        p.convertCommitmentToDisplayForm(remainingCommitment, sourceLoc, token, resourceInfo.Unit),
1✔
1512
                )
1✔
1513
        }
1514

1515
        convertedCommitment, err := p.buildConvertedCommitment(dbCommitment, targetAZResourceID, conversionAmount)
2✔
1516
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
1517
                return
×
1518
        }
×
1519
        relatedCommitmentIDs = append(relatedCommitmentIDs, convertedCommitment.ID)
2✔
1520
        relatedCommitmentUUIDs = append(relatedCommitmentUUIDs, convertedCommitment.UUID)
2✔
1521
        err = tx.Insert(&convertedCommitment)
2✔
1522
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
1523
                return
×
1524
        }
×
1525

1526
        // supersede the original commitment
1527
        now := p.timeNow()
2✔
1528
        supersedeContext := db.CommitmentWorkflowContext{
2✔
1529
                Reason:                 db.CommitmentReasonConvert,
2✔
1530
                RelatedCommitmentIDs:   relatedCommitmentIDs,
2✔
1531
                RelatedCommitmentUUIDs: relatedCommitmentUUIDs,
2✔
1532
        }
2✔
1533
        buf, err := json.Marshal(supersedeContext)
2✔
1534
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
1535
                return
×
1536
        }
×
1537
        dbCommitment.State = db.CommitmentStateSuperseded
2✔
1538
        dbCommitment.SupersededAt = Some(now)
2✔
1539
        dbCommitment.SupersedeContextJSON = Some(json.RawMessage(buf))
2✔
1540
        _, err = tx.Update(&dbCommitment)
2✔
1541
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
1542
                return
×
1543
        }
×
1544

1545
        err = tx.Commit()
2✔
1546
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
1547
                return
×
1548
        }
×
1549

1550
        c := p.convertCommitmentToDisplayForm(convertedCommitment, targetLoc, token, resourceInfo.Unit)
2✔
1551
        auditEvent.Commitments = append([]limesresources.Commitment{c}, auditEvent.Commitments...)
2✔
1552
        auditEvent.WorkflowContext = Some(db.CommitmentWorkflowContext{
2✔
1553
                Reason:                 db.CommitmentReasonSplit,
2✔
1554
                RelatedCommitmentIDs:   []db.ProjectCommitmentID{dbCommitment.ID},
2✔
1555
                RelatedCommitmentUUIDs: []db.ProjectCommitmentUUID{dbCommitment.UUID},
2✔
1556
        })
2✔
1557
        p.auditor.Record(audittools.Event{
2✔
1558
                Time:       p.timeNow(),
2✔
1559
                Request:    r,
2✔
1560
                User:       token,
2✔
1561
                ReasonCode: http.StatusAccepted,
2✔
1562
                Action:     cadf.UpdateAction,
2✔
1563
                Target:     auditEvent,
2✔
1564
        })
2✔
1565

2✔
1566
        respondwith.JSON(w, http.StatusAccepted, map[string]any{"commitment": c})
2✔
1567
}
1568

1569
// ExtendCommitmentDuration handles POST /v1/domains/{domain_id}/projects/{project_id}/commitments/{commitment_id}/update-duration
1570
func (p *v1Provider) UpdateCommitmentDuration(w http.ResponseWriter, r *http.Request) {
6✔
1571
        httpapi.IdentifyEndpoint(r, "/v1/domains/:domain_id/projects/:project_id/commitments/:commitment_id/update-duration")
6✔
1572
        token := p.CheckToken(r)
6✔
1573
        if !token.Require(w, "project:edit") {
6✔
1574
                return
×
1575
        }
×
1576
        commitmentID := mux.Vars(r)["commitment_id"]
6✔
1577
        if commitmentID == "" {
6✔
1578
                http.Error(w, "no transfer token provided", http.StatusBadRequest)
×
1579
                return
×
1580
        }
×
1581
        dbDomain := p.FindDomainFromRequest(w, r)
6✔
1582
        if dbDomain == nil {
6✔
1583
                return
×
1584
        }
×
1585
        dbProject := p.FindProjectFromRequest(w, r, dbDomain)
6✔
1586
        if dbProject == nil {
6✔
1587
                return
×
1588
        }
×
1589
        var Request struct {
6✔
1590
                Duration limesresources.CommitmentDuration `json:"duration"`
6✔
1591
        }
6✔
1592
        req := Request
6✔
1593
        if !RequireJSON(w, r, &req) {
6✔
1594
                return
×
1595
        }
×
1596

1597
        var dbCommitment db.ProjectCommitment
6✔
1598
        err := p.DB.SelectOne(&dbCommitment, findProjectCommitmentByIDQuery, commitmentID, dbProject.ID)
6✔
1599
        if errors.Is(err, sql.ErrNoRows) {
6✔
1600
                http.Error(w, "no such commitment", http.StatusNotFound)
×
1601
                return
×
1602
        } else if respondwith.ObfuscatedErrorText(w, err) {
6✔
1603
                return
×
1604
        }
×
1605

1606
        now := p.timeNow()
6✔
1607
        if dbCommitment.ExpiresAt.Before(now) || dbCommitment.ExpiresAt.Equal(now) {
7✔
1608
                http.Error(w, "unable to process expired commitment", http.StatusForbidden)
1✔
1609
                return
1✔
1610
        }
1✔
1611

1612
        if dbCommitment.State == db.CommitmentStateSuperseded {
6✔
1613
                msg := fmt.Sprintf("unable to operate on commitment with a state of %s", dbCommitment.State)
1✔
1614
                http.Error(w, msg, http.StatusForbidden)
1✔
1615
                return
1✔
1616
        }
1✔
1617

1618
        var loc core.AZResourceLocation
4✔
1619
        err = p.DB.QueryRow(findAZResourceLocationByIDQuery, dbCommitment.AZResourceID).
4✔
1620
                Scan(&loc.ServiceType, &loc.ResourceName, &loc.AvailabilityZone)
4✔
1621
        if errors.Is(err, sql.ErrNoRows) {
4✔
1622
                // defense in depth: this should not happen because all the relevant tables are connected by FK constraints
×
1623
                http.Error(w, "no route to this commitment", http.StatusNotFound)
×
1624
                return
×
1625
        } else if respondwith.ObfuscatedErrorText(w, err) {
4✔
1626
                return
×
1627
        }
×
1628
        behavior := p.Cluster.CommitmentBehaviorForResource(loc.ServiceType, loc.ResourceName).ForDomain(dbDomain.Name)
4✔
1629
        if !slices.Contains(behavior.Durations, req.Duration) {
5✔
1630
                msg := fmt.Sprintf("provided duration: %s does not match the config %v", req.Duration, behavior.Durations)
1✔
1631
                http.Error(w, msg, http.StatusUnprocessableEntity)
1✔
1632
                return
1✔
1633
        }
1✔
1634

1635
        newExpiresAt := req.Duration.AddTo(dbCommitment.ConfirmBy.UnwrapOr(dbCommitment.CreatedAt))
3✔
1636
        if newExpiresAt.Before(dbCommitment.ExpiresAt) {
4✔
1637
                msg := fmt.Sprintf("duration change from %s to %s forbidden", dbCommitment.Duration, req.Duration)
1✔
1638
                http.Error(w, msg, http.StatusForbidden)
1✔
1639
                return
1✔
1640
        }
1✔
1641

1642
        dbCommitment.Duration = req.Duration
2✔
1643
        dbCommitment.ExpiresAt = newExpiresAt
2✔
1644
        _, err = p.DB.Update(&dbCommitment)
2✔
1645
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
1646
                return
×
1647
        }
×
1648

1649
        maybeServiceInfo, err := p.Cluster.InfoForService(loc.ServiceType)
2✔
1650
        if respondwith.ObfuscatedErrorText(w, err) {
2✔
1651
                return
×
1652
        }
×
1653
        serviceInfo, ok := maybeServiceInfo.Unpack()
2✔
1654
        if !ok {
2✔
1655
                http.Error(w, "service not found", http.StatusNotFound)
×
1656
                return
×
1657
        }
×
1658
        resourceInfo := core.InfoForResource(serviceInfo, loc.ResourceName)
2✔
1659
        c := p.convertCommitmentToDisplayForm(dbCommitment, loc, token, resourceInfo.Unit)
2✔
1660
        p.auditor.Record(audittools.Event{
2✔
1661
                Time:       p.timeNow(),
2✔
1662
                Request:    r,
2✔
1663
                User:       token,
2✔
1664
                ReasonCode: http.StatusOK,
2✔
1665
                Action:     cadf.UpdateAction,
2✔
1666
                Target: commitmentEventTarget{
2✔
1667
                        DomainID:    dbDomain.UUID,
2✔
1668
                        DomainName:  dbDomain.Name,
2✔
1669
                        ProjectID:   dbProject.UUID,
2✔
1670
                        ProjectName: dbProject.Name,
2✔
1671
                        Commitments: []limesresources.Commitment{c},
2✔
1672
                },
2✔
1673
        })
2✔
1674

2✔
1675
        respondwith.JSON(w, http.StatusOK, map[string]any{"commitment": c})
2✔
1676
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc