-
Notifications
You must be signed in to change notification settings - Fork 30
/
enrich.go
286 lines (269 loc) · 9.96 KB
/
enrich.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package interceptors
import (
"context"
"reflect"
"strings"
"github.com/raystack/frontier/billing/customer"
"github.com/raystack/frontier/pkg/server/consts"
frontierv1beta1 "github.com/raystack/frontier/proto/v1beta1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/raystack/frontier/internal/api/v1beta1"
"google.golang.org/grpc"
)
var (
ErrStatusOrgProjectMismatch = status.Error(codes.InvalidArgument, "both project_id and org_id cannot be provided")
)
// UnaryAPIRequestEnrich is a unary server interceptor that enriches the request context with additional information
func UnaryAPIRequestEnrich() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
serverHandler, ok := info.Server.(*v1beta1.Handler)
if !ok {
// no need to capture the request
return handler(ctx, req)
}
req, err = APIRequestEnrich(ctx, serverHandler, info.FullMethod, req)
if err != nil {
return nil, err
}
// populate stripe key if applicable
ctx = UnaryCtxWithStripeTestClock(ctx, serverHandler, info.FullMethod)
resp, err = handler(ctx, req)
if err != nil {
return nil, err
}
resp = APIResponseEnrich(ctx, serverHandler, info.FullMethod, req, resp)
return resp, nil
}
}
func APIRequestEnrich(ctx context.Context, handler *v1beta1.Handler, methodName string, req any) (any, error) {
// convert project ids to org ids for billing endpoints:
// - CheckFeatureEntitlement
// - CreateBillingUsage
// - RevertBillingUsage
switch methodName {
case "/raystack.frontier.v1beta1.FrontierService/CheckFeatureEntitlement":
req := req.(*frontierv1beta1.CheckFeatureEntitlementRequest)
if req.GetProjectId() != "" && req.GetOrgId() != "" {
return req, ErrStatusOrgProjectMismatch
}
if req.GetProjectId() != "" {
proj, err := handler.GetProject(ctx, &frontierv1beta1.GetProjectRequest{
Id: req.GetProjectId(),
})
if err != nil {
return req, err
}
req.OrgId = proj.GetProject().GetOrgId()
}
case "/raystack.frontier.v1beta1.FrontierService/CreateBillingUsage":
req := req.(*frontierv1beta1.CreateBillingUsageRequest)
if req.GetProjectId() != "" && req.GetOrgId() != "" {
return req, ErrStatusOrgProjectMismatch
}
if req.GetProjectId() != "" {
proj, err := handler.GetProject(ctx, &frontierv1beta1.GetProjectRequest{
Id: req.GetProjectId(),
})
if err != nil {
return req, err
}
req.OrgId = proj.GetProject().GetOrgId()
}
case "/raystack.frontier.v1beta1.AdminService/RevertBillingUsage":
req := req.(*frontierv1beta1.RevertBillingUsageRequest)
if req.GetProjectId() != "" && req.GetOrgId() != "" {
return req, ErrStatusOrgProjectMismatch
}
if req.GetProjectId() != "" {
proj, err := handler.GetProject(ctx, &frontierv1beta1.GetProjectRequest{
Id: req.GetProjectId(),
})
if err != nil {
return req, err
}
req.OrgId = proj.GetProject().GetOrgId()
}
}
// find default billing account for the customer if needed
// - CheckFeatureEntitlement
// - CreateBillingUsage
// - ListInvoices
// - GetUpcomingInvoice
// - RevertBillingUsage
switch methodName {
case "/raystack.frontier.v1beta1.FrontierService/CheckFeatureEntitlement":
req := req.(*frontierv1beta1.CheckFeatureEntitlementRequest)
if req.GetBillingId() == "" {
customerID, err := handler.GetRequestCustomerID(ctx, req)
if err != nil {
return req, status.Error(codes.InvalidArgument, err.Error())
}
req.BillingId = customerID
}
case "/raystack.frontier.v1beta1.FrontierService/CreateBillingUsage":
req := req.(*frontierv1beta1.CreateBillingUsageRequest)
if req.GetBillingId() == "" {
customerID, err := handler.GetRequestCustomerID(ctx, req)
if err != nil {
return req, status.Error(codes.InvalidArgument, err.Error())
}
req.BillingId = customerID
}
case "/raystack.frontier.v1beta1.FrontierService/ListInvoices":
req := req.(*frontierv1beta1.ListInvoicesRequest)
if req.GetBillingId() == "" {
customerID, err := handler.GetRequestCustomerID(ctx, req)
if err != nil {
return req, status.Error(codes.InvalidArgument, err.Error())
}
req.BillingId = customerID
}
case "/raystack.frontier.v1beta1.FrontierService/GetUpcomingInvoice":
req := req.(*frontierv1beta1.GetUpcomingInvoiceRequest)
if req.GetBillingId() == "" {
customerID, err := handler.GetRequestCustomerID(ctx, req)
if err != nil {
return req, status.Error(codes.InvalidArgument, err.Error())
}
req.BillingId = customerID
}
case "/raystack.frontier.v1beta1.AdminService/RevertBillingUsage":
req := req.(*frontierv1beta1.RevertBillingUsageRequest)
if req.GetBillingId() == "" {
customerID, err := handler.GetRequestCustomerID(ctx, req)
if err != nil {
return req, status.Error(codes.InvalidArgument, err.Error())
}
req.BillingId = customerID
}
}
return req, nil
}
// APIResponseEnrich is a unary server interceptor that enriches the response context with additional information
// based on the request expand field
func APIResponseEnrich(ctx context.Context, handler *v1beta1.Handler, methodName string, req, resp any) any {
// find the strings mentioned in the request under Expand field
// we will only enrich the response if the Expand field is set for the specific model
expandModels := map[string]bool{}
expandReflect := reflect.ValueOf(req).Elem().FieldByName("Expand")
if expandReflect.IsValid() && expandReflect.Len() > 0 {
for i := 0; i < expandReflect.Len(); i++ {
expandModels[strings.ToLower(expandReflect.Index(i).String())] = true
}
}
if len(expandModels) == 0 {
// no need to enrich the response
return resp
}
switch methodName {
case "/raystack.frontier.v1beta1.FrontierService/ListBillingTransactions":
resp := resp.(*frontierv1beta1.ListBillingTransactionsResponse)
if len(resp.GetTransactions()) > 0 {
for tIdx, t := range resp.GetTransactions() {
if expandModels["customer"] && len(t.GetCustomerId()) > 0 {
ba, _ := handler.GetBillingAccount(ctx, &frontierv1beta1.GetBillingAccountRequest{
Id: t.GetCustomerId(),
})
resp.Transactions[tIdx].Customer = ba.GetBillingAccount()
}
if expandModels["user"] && len(t.GetUserId()) > 0 {
// if we allowed anyone to report usage with a user id, a bad actor can pass any user id
// and retrieve user information.
user, _ := handler.GetUser(ctx, &frontierv1beta1.GetUserRequest{
Id: t.GetUserId(),
})
resp.Transactions[tIdx].User = user.GetUser()
}
}
}
case "/raystack.frontier.v1beta1.FrontierService/GetBillingAccount":
resp := resp.(*frontierv1beta1.GetBillingAccountResponse)
if (expandModels["organization"] || expandModels["org"]) && resp.GetBillingAccount() != nil {
org, _ := handler.GetOrganization(ctx, &frontierv1beta1.GetOrganizationRequest{
Id: resp.GetBillingAccount().GetOrgId(),
})
resp.BillingAccount.Organization = org.GetOrganization()
}
case "/raystack.frontier.v1beta1.FrontierService/ListBillingAccounts":
resp := resp.(*frontierv1beta1.ListBillingAccountsResponse)
if len(resp.GetBillingAccounts()) > 0 {
for baIdx, ba := range resp.GetBillingAccounts() {
if expandModels["organization"] || expandModels["org"] {
org, _ := handler.GetOrganization(ctx, &frontierv1beta1.GetOrganizationRequest{
Id: ba.GetOrgId(),
})
resp.BillingAccounts[baIdx].Organization = org.GetOrganization()
}
}
}
case "/raystack.frontier.v1beta1.FrontierService/GetSubscription":
resp := resp.(*frontierv1beta1.GetSubscriptionResponse)
if resp.GetSubscription() == nil {
if expandModels["customer"] {
ba, _ := handler.GetBillingAccount(ctx, &frontierv1beta1.GetBillingAccountRequest{
Id: resp.GetSubscription().GetCustomerId(),
})
resp.Subscription.Customer = ba.GetBillingAccount()
}
if expandModels["plan"] {
plan, _ := handler.GetPlan(ctx, &frontierv1beta1.GetPlanRequest{
Id: resp.GetSubscription().GetPlanId(),
})
resp.Subscription.Plan = plan.GetPlan()
}
}
case "/raystack.frontier.v1beta1.FrontierService/ListSubscriptions":
resp := resp.(*frontierv1beta1.ListSubscriptionsResponse)
if len(resp.GetSubscriptions()) > 0 {
for sIdx, s := range resp.GetSubscriptions() {
if expandModels["customer"] {
ba, _ := handler.GetBillingAccount(ctx, &frontierv1beta1.GetBillingAccountRequest{
Id: s.GetCustomerId(),
})
resp.Subscriptions[sIdx].Customer = ba.GetBillingAccount()
}
if expandModels["plan"] {
plan, _ := handler.GetPlan(ctx, &frontierv1beta1.GetPlanRequest{
Id: s.GetPlanId(),
})
resp.Subscriptions[sIdx].Plan = plan.GetPlan()
}
}
}
case "/raystack.frontier.v1beta1.FrontierService/ListInvoices":
resp := resp.(*frontierv1beta1.ListInvoicesResponse)
if len(resp.GetInvoices()) > 0 {
for iIdx, i := range resp.GetInvoices() {
if expandModels["customer"] {
ba, _ := handler.GetBillingAccount(ctx, &frontierv1beta1.GetBillingAccountRequest{
Id: i.GetCustomerId(),
})
resp.Invoices[iIdx].Customer = ba.GetBillingAccount()
}
}
}
}
return resp
}
// UnaryCtxWithStripeTestClock adds stripe test clock id to context
func UnaryCtxWithStripeTestClock(ctx context.Context, handler *v1beta1.Handler, methodName string) context.Context {
switch methodName {
// stripeTestClockEnabledEndpoints is a map of endpoints that are allowed to use stripe test clock
case "/raystack.frontier.v1beta1.FrontierService/CreateBillingAccount":
if handler.IsSuperUser(ctx) == nil {
// superuser can simulate stripe test clock if needed
values := metadata.ValueFromIncomingContext(ctx, consts.StripeTestClockRequestKey)
if len(values) > 0 {
ctx = customer.SetStripeTestClockInContext(ctx, values[0])
}
}
case "/raystack.frontier.v1beta1.FrontierService/BillingWebhookCallback":
values := metadata.ValueFromIncomingContext(ctx, consts.StripeWebhookSignature)
if len(values) > 0 {
ctx = customer.SetStripeWebhookSignatureInContext(ctx, values[0])
}
}
return ctx
}