-
Notifications
You must be signed in to change notification settings - Fork 440
Expand file tree
/
Copy pathsandbox_create.go
More file actions
737 lines (596 loc) · 23.4 KB
/
Copy pathsandbox_create.go
File metadata and controls
737 lines (596 loc) · 23.4 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
package handlers
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"path/filepath"
"slices"
"strings"
"time"
"github.com/asaskevich/govalidator"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/launchdarkly/go-sdk-common/v3/ldcontext"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"golang.org/x/net/idna"
"github.com/e2b-dev/infra/packages/api/internal/api"
templatecache "github.com/e2b-dev/infra/packages/api/internal/cache/templates"
apiorch "github.com/e2b-dev/infra/packages/api/internal/orchestrator"
"github.com/e2b-dev/infra/packages/api/internal/sandbox"
"github.com/e2b-dev/infra/packages/auth/pkg/auth"
sqlcdb "github.com/e2b-dev/infra/packages/db/client"
"github.com/e2b-dev/infra/packages/db/pkg/types"
"github.com/e2b-dev/infra/packages/db/queries"
"github.com/e2b-dev/infra/packages/shared/pkg/clusters"
"github.com/e2b-dev/infra/packages/shared/pkg/featureflags"
"github.com/e2b-dev/infra/packages/shared/pkg/ginutils"
"github.com/e2b-dev/infra/packages/shared/pkg/grpc/orchestrator"
"github.com/e2b-dev/infra/packages/shared/pkg/id"
"github.com/e2b-dev/infra/packages/shared/pkg/logger"
sbxlogger "github.com/e2b-dev/infra/packages/shared/pkg/logger/sandbox"
"github.com/e2b-dev/infra/packages/shared/pkg/middleware/otel/metrics"
sandbox_network "github.com/e2b-dev/infra/packages/shared/pkg/sandbox-network"
"github.com/e2b-dev/infra/packages/shared/pkg/telemetry"
sharedUtils "github.com/e2b-dev/infra/packages/shared/pkg/utils"
)
const (
InstanceIDPrefix = "i"
metricTemplateAlias = metrics.MetricPrefix + "template.alias"
minEnvdVersionForSecureFlag = "0.2.0" // Minimum version of envd that supports secure flag
// Network validation error messages
ErrMsgDomainsRequireBlockAll = "When specifying allowed domains in allow out, you must include 'ALL_TRAFFIC' in deny out to block all other traffic."
maxNetworkRuleDomains = 10
maxNetworkRuleTransformsPerDomain = 1
maxNetworkRuleDomainLen = 128
maxNetworkRuleHeaderNameLen = 64
maxNetworkRuleHeaderValueLen = 256
)
func (a *APIStore) PostSandboxes(c *gin.Context) {
ctx := c.Request.Context()
// Get team from context, use TeamContextKey
teamInfo := auth.MustGetTeamInfo(c)
c.Set("teamID", teamInfo.Team.ID.String())
span := trace.SpanFromContext(ctx)
traceID := span.SpanContext().TraceID().String()
c.Set("traceID", traceID)
body, err := ginutils.ParseBody[api.PostSandboxesJSONRequestBody](ctx, c)
if err != nil {
a.sendAPIStoreError(c, http.StatusBadRequest, fmt.Sprintf("Error when parsing request: %s", err))
telemetry.ReportCriticalError(ctx, "error when parsing request", err)
return
}
telemetry.ReportEvent(ctx, "Parsed body")
identifier, tag, err := id.ParseName(body.TemplateID)
if err != nil {
a.sendAPIStoreError(c, http.StatusBadRequest, fmt.Sprintf("Invalid template reference: %s", err))
telemetry.ReportError(ctx, "invalid template reference", err)
return
}
clusterID := clusters.WithClusterFallback(teamInfo.Team.ClusterID)
aliasInfo, err := a.templateCache.ResolveAlias(ctx, identifier, teamInfo.Team.Slug)
if err != nil {
apiErr := templatecache.ErrorToAPIError(err, identifier)
telemetry.ReportErrorByCode(ctx, apiErr.Code, "error when resolving template alias", apiErr.Err, attribute.String("identifier", identifier))
a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg)
return
}
env, build, err := a.templateCache.Get(ctx, aliasInfo.TemplateID, tag, teamInfo.Team.ID, clusterID)
if err != nil {
visible := aliasInfo.TeamID == teamInfo.Team.ID
if metadata, mErr := a.templateCache.GetMetadata(ctx, aliasInfo.TemplateID); mErr == nil {
visible = visible || metadata.Public
}
ref := templatecache.TemplateRef{
Identifier: aliasInfo.MatchedIdentifier,
Visible: visible,
}
apiErr := ref.APIError(err)
telemetry.ReportErrorByCode(ctx, apiErr.Code, "error when getting template", apiErr.Err, telemetry.WithTemplateID(aliasInfo.TemplateID))
a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg)
return
}
telemetry.ReportEvent(ctx, "Checked team access")
c.Set("envID", env.TemplateID)
setTemplateNameMetric(ctx, c, a.featureFlags, env.TemplateID, env.Names)
sandboxID := InstanceIDPrefix + id.Generate()
c.Set("instanceID", sandboxID)
sbxlogger.E(&sbxlogger.SandboxMetadata{
SandboxID: sandboxID,
TemplateID: env.TemplateID,
TeamID: teamInfo.Team.ID.String(),
}).Debug(ctx, "Started creating sandbox")
alias := firstAlias(env.Aliases)
telemetry.SetAttributes(ctx,
telemetry.WithSandboxID(sandboxID),
telemetry.WithTemplateID(env.TemplateID),
telemetry.WithBuildID(build.ID.String()),
attribute.String("env.alias", alias),
telemetry.WithKernelVersion(build.KernelVersion),
telemetry.WithFirecrackerVersion(build.FirecrackerVersion),
)
autoPause := sharedUtils.DerefOrDefault(body.AutoPause, sandbox.AutoPauseDefault)
envVars := sharedUtils.DerefOrDefault(body.EnvVars, nil)
mcp := sharedUtils.DerefOrDefault(body.Mcp, nil)
metadata := sharedUtils.DerefOrDefault(body.Metadata, nil)
apiVolumeMounts := sharedUtils.DerefOrDefault(body.VolumeMounts, nil)
timeout := sandbox.SandboxTimeoutDefault
if body.Timeout != nil {
timeout = time.Duration(*body.Timeout) * time.Second
if timeout > time.Duration(teamInfo.Limits.MaxLengthHours)*time.Hour {
a.sendAPIStoreError(c, http.StatusBadRequest, fmt.Sprintf("Timeout cannot be greater than %d hours", teamInfo.Limits.MaxLengthHours))
return
}
}
autoResume := buildAutoResumeConfig(body.AutoResume)
if autoResume != nil {
minAutoResumeTimeout := time.Duration(a.featureFlags.IntFlag(ctx, featureflags.MinAutoResumeTimeoutSeconds)) * time.Second
autoResume.Timeout = calculateTimeoutSeconds(timeout, minAutoResumeTimeout, teamInfo)
}
var envdAccessToken *string = nil
if body.Secure != nil && *body.Secure == true {
accessToken, tokenErr := a.getEnvdAccessToken(build.EnvdVersion, sandboxID)
if tokenErr != nil {
telemetry.ReportError(ctx, "secure envd access token error", tokenErr.Err, telemetry.WithSandboxID(sandboxID), telemetry.WithBuildID(build.ID.String()))
a.sendAPIStoreError(c, tokenErr.Code, tokenErr.ClientMsg)
return
}
envdAccessToken = &accessToken
}
allowInternetAccess := body.AllowInternetAccess
var network *types.SandboxNetworkConfig
if n := body.Network; n != nil {
if err := validateNetworkConfig(ctx, a.featureFlags, teamInfo.Team.ID, n); err != nil {
telemetry.ReportError(ctx, "invalid network config", err.Err, telemetry.WithSandboxID(sandboxID))
a.sendAPIStoreError(c, err.Code, err.ClientMsg)
return
}
network = &types.SandboxNetworkConfig{
Ingress: &types.SandboxNetworkIngressConfig{
AllowPublicAccess: n.AllowPublicTraffic,
MaskRequestHost: n.MaskRequestHost,
},
Egress: &types.SandboxNetworkEgressConfig{
AllowedAddresses: sharedUtils.DerefOrDefault(n.AllowOut, nil),
DeniedAddresses: sharedUtils.DerefOrDefault(n.DenyOut, nil),
Rules: apiRulesToDBRules(n.Rules),
},
}
// Make sure envd seucre access is enforced when public access is disabled,
// This requirement forces users using newer features to secure sandboxes properly.
if !sharedUtils.DerefOrDefault(network.Ingress.AllowPublicAccess, types.AllowPublicAccessDefault) && envdAccessToken == nil {
a.sendAPIStoreError(c, http.StatusBadRequest, "You cannot create a sandbox without public access unless you enable secure envd access via 'secure' flag.")
return
}
}
sbxVolumeMounts, err := convertAPIVolumesToOrchestratorVolumes(
ctx, a.sqlcDB, a.featureFlags, teamInfo.ID, apiVolumeMounts, build,
)
if err != nil {
if errors.Is(err, errVolumesNotSupported) {
a.sendAPIStoreError(c, http.StatusBadRequest, err.Error())
return
}
if errors.Is(err, ErrVolumeMountsDisabled) {
a.sendAPIStoreError(c, http.StatusBadRequest, "Volume mounts are not enabled.")
return
}
var vne InvalidVolumeMountsError
if errors.As(err, &vne) {
a.sendAPIStoreError(c, http.StatusBadRequest, vne.Error())
return
}
telemetry.ReportError(ctx, "failed to convert volume mounts", err, telemetry.WithSandboxID(sandboxID))
a.sendAPIStoreError(c, http.StatusInternalServerError, "failed to convert volume mounts")
return
}
getSandboxData := func(_ context.Context) (apiorch.SandboxMetadata, *api.APIError) {
// The data can't be influenced by action on the same sandbox as other operations,
// so it's safe to reuse the data
return apiorch.SandboxMetadata{
Metadata: metadata,
EnvVars: envVars,
Build: *build,
AllowInternetAccess: allowInternetAccess,
Network: network,
Alias: alias,
TemplateID: env.TemplateID,
BaseTemplateID: env.TemplateID,
AutoPause: autoPause,
AutoResume: autoResume,
VolumeMounts: sbxVolumeMounts,
EnvdAccessToken: envdAccessToken,
}, nil
}
sbx, createErr := a.startSandbox(
ctx,
sandboxID,
timeout,
teamInfo,
getSandboxData,
&c.Request.Header,
false,
mcp,
)
if createErr != nil {
a.sendAPIStoreError(c, createErr.Code, createErr.ClientMsg)
return
}
if n := body.Network; n != nil && n.Rules != nil && len(*n.Rules) > 0 {
domains := make([]string, 0, len(*n.Rules))
for domain := range *n.Rules {
domains = append(domains, domain)
}
a.posthog.CreateAnalyticsTeamEvent(ctx, teamInfo.Team.ID.String(), "sandbox with network transform rules created",
a.posthog.GetPackageToPosthogProperties(&c.Request.Header).
Set("sandbox_id", sandboxID).
Set("domains", domains),
)
}
c.JSON(http.StatusCreated, &sbx)
}
func buildAutoResumeConfig(autoResume *api.SandboxAutoResumeConfig) *types.SandboxAutoResumeConfig {
if autoResume == nil {
return nil
}
policy := types.SandboxAutoResumeOff
if autoResume.Enabled {
policy = types.SandboxAutoResumeAny
}
return &types.SandboxAutoResumeConfig{
Policy: policy,
}
}
func dedupeVolumeNames(items []api.SandboxVolumeMount) []string {
itemsSet := make(map[string]struct{}, len(items))
for _, item := range items {
itemsSet[item.Name] = struct{}{}
}
results := make([]string, 0, len(itemsSet))
for name := range itemsSet {
results = append(results, name)
}
return results
}
var ErrVolumeMountsDisabled = errors.New("volume mounts are not enabled")
type featureFlagsClient interface {
BoolFlag(ctx context.Context, flagName featureflags.BoolFlag, contexts ...ldcontext.Context) bool
}
type InvalidMount struct {
Index int
Reason string
}
type InvalidVolumeMountsError struct {
InvalidMounts []InvalidMount
}
func (im InvalidVolumeMountsError) Error() string {
var errs []string
for _, mount := range im.InvalidMounts {
errs = append(errs, fmt.Sprintf("\t- volume mount #%d: %s", mount.Index, mount.Reason))
}
return fmt.Sprintf("invalid mounts:\n%s", strings.Join(errs, "\n"))
}
var errVolumesNotSupported = errors.New("volumes are not supported")
var errNoEnvdVersion = errors.New("no envd version provided")
const minEnvdVersionForVolumes = "0.5.14"
func convertAPIVolumesToOrchestratorVolumes(ctx context.Context, sqlClient *sqlcdb.Client, featureFlags featureFlagsClient, teamID uuid.UUID, volumeMounts []api.SandboxVolumeMount, env *queries.EnvBuild) ([]*orchestrator.SandboxVolumeMount, error) {
// are any volumes configured?
if len(volumeMounts) == 0 {
return []*orchestrator.SandboxVolumeMount{}, nil // only b/c you should never return (nil, nil)
}
// are volumes enabled?
if !featureFlags.BoolFlag(ctx, featureflags.PersistentVolumesFlag) {
return nil, ErrVolumeMountsDisabled
}
// does your envd version support volumes?
if envdVersion := sharedUtils.DerefOrDefault(env.EnvdVersion, ""); envdVersion == "" {
logger.L().Warn(ctx, "envd version is unset")
return nil, errNoEnvdVersion
} else if ok, err := sharedUtils.IsGTEVersion(envdVersion, minEnvdVersionForVolumes); err != nil {
logger.L().Warn(ctx, "failed to check envd version", zap.Error(err), zap.String("envd_version", envdVersion))
return nil, fmt.Errorf("invalid envd version %q: %w", envdVersion, err)
} else if !ok {
return nil, fmt.Errorf("%w; template must be rebuilt. Template envd version is %s, must be at least %s to support volumes", errVolumesNotSupported, envdVersion, minEnvdVersionForVolumes)
}
// get volumes from the database
dbVolumesMap, err := getDBVolumesMap(ctx, sqlClient, teamID, volumeMounts)
if err != nil {
return nil, fmt.Errorf("failed to get db volumes map: %w", err)
}
invalidVolumeMounts := make([]InvalidMount, 0)
results := make([]*orchestrator.SandboxVolumeMount, 0, len(volumeMounts))
usedPaths := make(map[string]struct{})
for index, v := range volumeMounts {
actualVolume, ok := dbVolumesMap[v.Name]
if !ok {
invalidVolumeMounts = append(invalidVolumeMounts, InvalidMount{Index: index, Reason: fmt.Sprintf("volume '%s' not found", v.Name)})
continue
}
if reason, ok := isValidMountPath(v.Path); !ok {
invalidVolumeMounts = append(invalidVolumeMounts, InvalidMount{Index: index, Reason: reason})
continue
}
if _, ok := usedPaths[v.Path]; ok {
invalidVolumeMounts = append(invalidVolumeMounts, InvalidMount{Index: index, Reason: fmt.Sprintf("path '%s' is already used", v.Path)})
continue
}
usedPaths[v.Path] = struct{}{}
results = append(results, &orchestrator.SandboxVolumeMount{
Id: actualVolume.ID.String(),
Path: v.Path,
Type: actualVolume.VolumeType,
Name: actualVolume.Name,
})
}
if len(invalidVolumeMounts) > 0 {
return nil, InvalidVolumeMountsError{InvalidMounts: invalidVolumeMounts}
}
return results, nil
}
func isValidMountPath(path string) (string, bool) {
if path == "" {
return "path cannot be empty", false
}
if !filepath.IsAbs(path) {
return "path must be absolute", false
}
if filepath.Clean(path) != path {
return "path must not contain any '.' or '..' components", false
}
return "", true
}
func getDBVolumesMap(ctx context.Context, sqlcDB *sqlcdb.Client, teamID uuid.UUID, volumeMounts []api.SandboxVolumeMount) (map[string]queries.Volume, error) {
dbVolumes, err := sqlcDB.GetVolumesByName(ctx, queries.GetVolumesByNameParams{
TeamID: teamID,
VolumeNames: dedupeVolumeNames(volumeMounts),
})
if err != nil {
return nil, fmt.Errorf("failed to get volumes from db: %w", err)
}
dbVolumesMap := make(map[string]queries.Volume, len(dbVolumes))
for _, v := range dbVolumes {
dbVolumesMap[v.Name] = v
}
return dbVolumesMap, nil
}
func (a *APIStore) getEnvdAccessToken(envdVersion *string, sandboxID string) (string, *api.APIError) {
if envdVersion == nil {
return "", &api.APIError{
Code: http.StatusBadRequest,
ClientMsg: "You need to re-build template to allow using secured access. Please visit https://e2b.dev/docs/sandbox/secured-access for more information.",
Err: errors.New("envd version is required during envd access token creation"),
}
}
// check if the envd version is at least 0.2.0
ok, err := sharedUtils.IsGTEVersion(*envdVersion, minEnvdVersionForSecureFlag)
if err != nil {
return "", &api.APIError{
Code: http.StatusInternalServerError,
ClientMsg: "error during envd version check",
Err: err,
}
}
if !ok {
return "", &api.APIError{
Code: http.StatusBadRequest,
ClientMsg: "Template is not compatible with secured access. Please visit https://e2b.dev/docs/sandbox/secured-access for more information.",
Err: errors.New("envd version is not supported for secure flag"),
}
}
key, err := a.accessTokenGenerator.GenerateEnvdAccessToken(sandboxID)
if err != nil {
return "", &api.APIError{
Code: http.StatusInternalServerError,
ClientMsg: "error during sandbox access token generation",
Err: err,
}
}
return key, nil
}
func setTemplateNameMetric(ctx context.Context, c *gin.Context, ff *featureflags.Client, templateID string, names []string) {
trackedTemplates := featureflags.GetTrackedTemplatesSet(ctx, ff)
// Check template ID first
if _, exists := trackedTemplates[templateID]; exists {
c.Set(metricTemplateAlias, templateID)
return
}
// Then check names (namespace/alias format when namespaced)
for _, name := range names {
if _, exists := trackedTemplates[name]; exists {
c.Set(metricTemplateAlias, name)
return
}
}
// Fallback to 'other' if no match of tracked templates found
c.Set(metricTemplateAlias, "other")
}
func firstAlias(aliases []string) string {
if len(aliases) == 0 {
return ""
}
return aliases[0]
}
func splitHostPortOptional(hostport string) (host string, port string, err error) {
host, port, err = net.SplitHostPort(hostport)
if err != nil {
if strings.Contains(err.Error(), "missing port") {
return hostport, "", nil
}
return "", "", err
}
return host, port, nil
}
func apiRulesToDBRules(apiRules *map[string][]api.SandboxNetworkRule) map[string][]types.SandboxNetworkRule {
if apiRules == nil {
return nil
}
dbRules := make(map[string][]types.SandboxNetworkRule, len(*apiRules))
for domain, rules := range *apiRules {
dbDomainRules := make([]types.SandboxNetworkRule, 0, len(rules))
for _, r := range rules {
dbRule := types.SandboxNetworkRule{}
if r.Transform != nil {
dbRule.Transform = &types.SandboxNetworkTransform{
Headers: sharedUtils.DerefOrDefault(r.Transform.Headers, nil),
}
}
dbDomainRules = append(dbDomainRules, dbRule)
}
dbRules[domain] = dbDomainRules
}
return dbRules
}
func validateNetworkConfig(ctx context.Context, featureFlags featureFlagsClient, teamID uuid.UUID, network *api.SandboxNetworkConfig) *api.APIError {
if network == nil {
return nil
}
if maskRequestHost := network.MaskRequestHost; maskRequestHost != nil {
hostname, _, err := splitHostPortOptional(*maskRequestHost)
if err != nil {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("invalid mask request host (%s): %w", *maskRequestHost, err),
ClientMsg: fmt.Sprintf("mask request host is not valid: %s", *maskRequestHost),
}
}
host, err := idna.Display.ToASCII(hostname)
if err != nil {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("invalid mask request host (%s): %w", *maskRequestHost, err),
ClientMsg: fmt.Sprintf("mask request host is not valid: %s", *maskRequestHost),
}
}
if !strings.EqualFold(host, hostname) {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("mask request host is not ASCII (%s)!=(%s)", host, hostname),
ClientMsg: fmt.Sprintf("mask request host '%s' is not ASCII. Please use ASCII characters only.", hostname),
}
}
}
denyOut := sharedUtils.DerefOrDefault(network.DenyOut, nil)
allowOut := sharedUtils.DerefOrDefault(network.AllowOut, nil)
if err := validateEgressRules(allowOut, denyOut); err != nil {
return err
}
return validateNetworkRules(ctx, featureFlags, teamID, network.Rules)
}
// validateEgressRules validates egress allow/deny rules:
// - denyOut entries must be valid IPs or CIDRs (not domains)
// - allowOut entries must be valid IPs, CIDRs, or domain names
// - when allowOut contains domains, denyOut must include 0.0.0.0/0
func validateEgressRules(allowOut, denyOut []string) *api.APIError {
for _, cidr := range denyOut {
if !sandbox_network.IsSpecifiedIPOrCIDR(cidr) {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("invalid denied CIDR %s", cidr),
ClientMsg: fmt.Sprintf("invalid denied CIDR %s", cidr),
}
}
}
if len(allowOut) > 0 {
allowedAddresses, allowedDomains := sandbox_network.ParseAddressesAndDomains(allowOut)
for _, addr := range allowedAddresses {
if !sandbox_network.IsSpecifiedIPOrCIDR(addr) {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("invalid allowed address %s", addr),
ClientMsg: fmt.Sprintf("invalid allowed address %s", addr),
}
}
}
hasBlockAll := slices.Contains(denyOut, sandbox_network.AllInternetTrafficCIDR)
if len(allowedDomains) > 0 && !hasBlockAll {
return &api.APIError{
Code: http.StatusBadRequest,
Err: errors.New("allow out contains domains but deny out is missing 0.0.0.0/0 (ALL_TRAFFIC)"),
ClientMsg: ErrMsgDomainsRequireBlockAll,
}
}
}
return nil
}
func validateNetworkRules(ctx context.Context, featureFlags featureFlagsClient, teamID uuid.UUID, rules *map[string][]api.SandboxNetworkRule) *api.APIError {
if rules == nil {
return nil
}
if !featureFlags.BoolFlag(ctx, featureflags.NetworkTransformRulesFlag, featureflags.TeamContext(teamID.String())) {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("team %s is not allowed to use network transform rules", teamID),
ClientMsg: "Network transform rules are not available for your team.",
}
}
if len(*rules) > maxNetworkRuleDomains {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("too many rule domains: %d (max %d)", len(*rules), maxNetworkRuleDomains),
ClientMsg: fmt.Sprintf("Network rules can have at most %d domains.", maxNetworkRuleDomains),
}
}
for domain, domainRules := range *rules {
if len(domain) == 0 {
return &api.APIError{
Code: http.StatusBadRequest,
Err: errors.New("rule domain must not be empty"),
ClientMsg: "Rule domain must not be empty.",
}
}
if len(domain) > maxNetworkRuleDomainLen {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("rule domain %q exceeds max length %d", domain, maxNetworkRuleDomainLen),
ClientMsg: fmt.Sprintf("Rule domain %q exceeds maximum length of %d characters.", domain, maxNetworkRuleDomainLen),
}
}
if !govalidator.IsDNSName(domain) {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("rule domain %q is not a valid domain", domain),
ClientMsg: fmt.Sprintf("Rule domain %q is not a valid domain name.", domain),
}
}
if len(domainRules) > maxNetworkRuleTransformsPerDomain {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("domain %q has %d transforms (max %d)", domain, len(domainRules), maxNetworkRuleTransformsPerDomain),
ClientMsg: fmt.Sprintf("Domain %q can have at most %d transform rule.", domain, maxNetworkRuleTransformsPerDomain),
}
}
for _, rule := range domainRules {
if rule.Transform == nil {
continue
}
headers := sharedUtils.DerefOrDefault(rule.Transform.Headers, nil)
for name, value := range headers {
if len(name) == 0 {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("header name in rule for domain %q must not be empty", domain),
ClientMsg: fmt.Sprintf("Header name in rule for domain %q must not be empty.", domain),
}
}
if len(name) > maxNetworkRuleHeaderNameLen {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("header name %q in rule for domain %q exceeds max length %d", name, domain, maxNetworkRuleHeaderNameLen),
ClientMsg: fmt.Sprintf("Header name %q in rule for domain %q exceeds maximum length of %d characters.", name, domain, maxNetworkRuleHeaderNameLen),
}
}
if len(value) > maxNetworkRuleHeaderValueLen {
return &api.APIError{
Code: http.StatusBadRequest,
Err: fmt.Errorf("value for header %q in rule for domain %q exceeds max length %d", name, domain, maxNetworkRuleHeaderValueLen),
ClientMsg: fmt.Sprintf("Value for header %q in rule for domain %q exceeds maximum length of %d characters.", name, domain, maxNetworkRuleHeaderValueLen),
}
}
}
}
}
return nil
}