Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/users/api-spec-resources.md
Original file line number Diff line number Diff line change
Expand Up @@ -930,3 +930,9 @@ Requires the `?service_type` query parameter.

Generates the request body payload for querying the LIQUID API endpoint /v1/projects/:uuid/report-usage of a specific service and project.
Requires the `?service_type` and `?project_id` query parameters.

### GET /admin/mail/render

Renders the mail template of the respective type using dummy values and
verifies that the generated content is valid HTML.
Requires the `?template_type` query parameter.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Requires the `?template_type` query parameter.
Requires the `template_type` query parameter.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ? was added to be consistent with the existing admin endpoints documentation

3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ require (
github.com/rs/cors v1.11.1
github.com/sapcc/go-api-declarations v1.18.0
github.com/sapcc/go-bits v0.0.0-20260205162534-c193fd73ad83
golang.org/x/net v0.49.0
)

require (
Expand All @@ -35,6 +36,6 @@ require (
github.com/rabbitmq/amqp091-go v1.10.0 // indirect
github.com/sergi/go-diff v1.4.0 // indirect
go.yaml.in/yaml/v2 v2.4.3 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/sys v0.40.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
)
12 changes: 6 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,8 @@ golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnf
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
Expand All @@ -206,11 +206,11 @@ golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
Expand Down
1 change: 1 addition & 0 deletions internal/api/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ func (p *v1Provider) AddTo(r *mux.Router) {

r.Methods("GET").Path("/admin/liquid/service-capacity-request").HandlerFunc(p.GetServiceCapacityRequest)
r.Methods("GET").Path("/admin/liquid/service-usage-request").HandlerFunc(p.GetServiceUsageRequest)
r.Methods("GET").Path("/admin/mail/render").HandlerFunc(p.RenderMailTemplate)
}

// RequireJSON will parse the request body into the given data structure, or
Expand Down
137 changes: 137 additions & 0 deletions internal/api/mail.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company
// SPDX-License-Identifier: Apache-2.0

package api

import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"

. "github.com/majewsky/gg/option"
limesresources "github.com/sapcc/go-api-declarations/limes/resources"
"github.com/sapcc/go-api-declarations/liquid"
"github.com/sapcc/go-bits/httpapi"
"github.com/sapcc/go-bits/logg"
"github.com/sapcc/go-bits/must"
"github.com/sapcc/go-bits/respondwith"
"golang.org/x/net/html"

"github.com/sapcc/limes/internal/core"
"github.com/sapcc/limes/internal/db"
)

// everythingCommitment provides a dummy commitment where all available fields
// are filled with data to cover all potential cases in the mail template rendering process.
var everythingCommitment db.ProjectCommitment = db.ProjectCommitment{
ID: 42,
UUID: "commitment-uuid",
ProjectID: 1,
AZResourceID: 7,
Amount: 500,
Duration: must.Return(limesresources.ParseCommitmentDuration("1 year")),
CreatedAt: time.Now(),
CreatorUUID: "creator-uuid",
CreatorName: "Foo User",
ConfirmBy: Some(time.Now()),
ConfirmedAt: Some(time.Now()),
ExpiresAt: time.Now(),

SupersededAt: Some(time.Now()),
CreationContextJSON: json.RawMessage(`{"reason": "create"}`),
SupersedeContextJSON: Some(json.RawMessage(`{"reason": "merge", "related_uuids": ["other-commitment-uuid"]}`)),
RenewContextJSON: Some(json.RawMessage(`{"reason": "renew"}`)),

TransferStatus: limesresources.CommitmentTransferStatusPublic,
TransferToken: Some("transfer-token"),
TransferStartedAt: Some(time.Now()),

Status: liquid.CommitmentStatusConfirmed,
NotifyOnConfirm: true,
NotifiedForExpiration: true,
}

// RenderMailTemplate handles GET /admin/mail/render?template_type=:type
func (p *v1Provider) RenderMailTemplate(w http.ResponseWriter, r *http.Request) {
httpapi.IdentifyEndpoint(r, "/admin/mail/render")
token := p.CheckToken(r)
if !token.Require(w, "cluster:show") {
return
}

template_type := r.URL.Query().Get("template_type")
if template_type == "" {
http.Error(w, "missing required parameter: template_type", http.StatusBadRequest)
return
}

mailConfig, ok := p.Cluster.Config.MailNotifications.Unpack()
if !ok {
respondwith.ErrorText(w, errors.New("could not get mail configuration"))
return
}

var template core.MailTemplate
switch template_type {
case "confirmed_commitments":
template = mailConfig.Templates.ConfirmedCommitments
case "expiring_commitments":
template = mailConfig.Templates.ExpiringCommitments
case "transferred_commitments":
template = mailConfig.Templates.TransferredCommitments
default:
http.Error(w, "invalid template type", http.StatusBadRequest)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we list available templates here? The user needs admin anyhow, so we don't leak anything, right?

return
}

dummyResource := core.AZResourceLocation{
ServiceType: "foo-service",
ResourceName: "bar-resource",
AvailabilityZone: "eu-de-1a",
}

notification := core.CommitmentGroupNotification{
DomainName: "example-domain",
ProjectName: "test-project",
Commitments: []core.CommitmentNotification{
{
Commitment: everythingCommitment,
DateString: time.Now().Format("2000-01-01"),
Resource: dummyResource,
LeftoverAmount: 100,
},
{
Commitment: everythingCommitment,
DateString: time.Now().Format("2000-01-01"),
Resource: dummyResource,
LeftoverAmount: 200,
},
{
Commitment: everythingCommitment,
DateString: time.Now().Format("2000-01-01"),
Resource: dummyResource,
LeftoverAmount: 300,
},
},
}
projectID := db.ProjectID(42)
mailNotification, err := template.Render(notification, projectID, time.Now())
if respondwith.ErrorText(w, err) {
return
}

_, err = html.Parse(strings.NewReader(mailNotification.Body))
if err != nil {
respondwith.ErrorText(w, fmt.Errorf("mail template rendering returned invalid HTML: %w", err))
return
}

w.WriteHeader(http.StatusOK)
_, err = w.Write([]byte(mailNotification.Body))
if err != nil {
logg.Error("cannot write response for %s %s: %s", r.Method, r.URL.Path, err.Error())
}
}
68 changes: 68 additions & 0 deletions internal/api/mail_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company
// SPDX-License-Identifier: Apache-2.0

package api_test

import (
"net/http"
"testing"

"github.com/sapcc/go-bits/assert"

"github.com/sapcc/limes/internal/test"
)

func TestRenderMailTemplate(t *testing.T) {
s := test.NewSetup(t,
test.WithConfig(`{
"availability_zones": ["az-one", "az-two"],
"discovery": {
"method": "static",
"static_config": {
"domains": [
{"name": "germany", "id": "uuid-for-germany"}
],
"projects": {
"uuid-for-germany": [{"name": "dresden", "id": "uuid-for-dresden", "parent_id": "uuid-for-germany"}]
}
}
},
"liquids": {
"shared": {"area": "shared"}
}
}`),
test.WithMailTemplates,
)

// endpoint requires cluster show permissions
s.TokenValidator.Enforcer.AllowView = false
assert.HTTPRequest{
Method: "GET",
Path: "/admin/mail/render?template_type=confirmed_commitments",
ExpectStatus: http.StatusForbidden,
}.Check(t, s.Handler)
s.TokenValidator.Enforcer.AllowView = true

// expect error when template type is missing
assert.HTTPRequest{
Method: "GET",
Path: "/admin/mail/render",
ExpectStatus: http.StatusBadRequest,
ExpectBody: assert.StringData("missing required parameter: template_type\n"),
}.Check(t, s.Handler)

// expect error for invalid template type
assert.HTTPRequest{
Method: "GET",
Path: "/admin/mail/render?template_type=unknown",
ExpectStatus: http.StatusBadRequest,
ExpectBody: assert.StringData("invalid template type\n"),
}.Check(t, s.Handler)

// happy path
assert.HTTPRequest{
Method: "GET",
Path: "/admin/mail/render?template_type=confirmed_commitments",
ExpectStatus: http.StatusOK,
}.Check(t, s.Handler)
}
23 changes: 23 additions & 0 deletions internal/test/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (

"github.com/go-gorp/gorp/v3"
"github.com/gophercloud/gophercloud/v2"
. "github.com/majewsky/gg/option"
"github.com/prometheus/client_golang/prometheus"
"github.com/sapcc/go-api-declarations/limes"
"github.com/sapcc/go-api-declarations/liquid"
Expand All @@ -42,6 +43,7 @@ type setupParams struct {
WithInitialDiscovery bool
WithEmptyRecordsAsNeeded bool
WithLiquidConnections bool
WithMailTemplates bool
PersistedServiceInfo map[db.ServiceType]liquid.ServiceInfo
LiquidClients map[db.ServiceType]*MockLiquidClient
}
Expand Down Expand Up @@ -128,6 +130,12 @@ func WithInitialDiscovery(params *setupParams) {
params.WithInitialDiscovery = true
}

// WithMailTemplates is a SetupOption that populates the
// mail notification config with dummy mail templates.
func WithMailTemplates(params *setupParams) {
params.WithMailTemplates = true
}

// Setup contains all the pieces that are needed for most tests.
type Setup struct {
// fields that are always set
Expand Down Expand Up @@ -324,6 +332,21 @@ func NewSetup(t *testing.T, opts ...SetupOption) Setup {
`))
}

if params.WithMailTemplates {
testTemplate := core.MailTemplate{
Subject: "subject",
Body: "<html>body</html>",
}
must.Succeed(testTemplate.Compile())
s.Cluster.Config.MailNotifications = Some(&core.MailConfiguration{
Templates: core.MailTemplateConfiguration{
ConfirmedCommitments: testTemplate,
ExpiringCommitments: testTemplate,
TransferredCommitments: testTemplate,
},
})
}

return s
}

Expand Down
27 changes: 27 additions & 0 deletions vendor/golang.org/x/net/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions vendor/golang.org/x/net/PATENTS

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading