Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
1467 lines (1273 loc) · 44.7 KB
/
Copy pathmain.go
File metadata and controls
1467 lines (1273 loc) · 44.7 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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"embed"
"errors"
"flag"
"fmt"
"io/fs"
"log/slog"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"slices"
"strings"
"sync"
"syscall"
"time"
"github.com/docker/docker/api/types/swarm"
oteltrace "go.opentelemetry.io/otel/trace"
"tailscale.com/tsnet"
"github.com/radiergummi/cetacean/internal/acl"
"github.com/radiergummi/cetacean/internal/api"
"github.com/radiergummi/cetacean/internal/api/reqctx"
"github.com/radiergummi/cetacean/internal/api/sse"
"github.com/radiergummi/cetacean/internal/attestations"
"github.com/radiergummi/cetacean/internal/audit"
"github.com/radiergummi/cetacean/internal/auth"
"github.com/radiergummi/cetacean/internal/cache"
"github.com/radiergummi/cetacean/internal/cluster"
"github.com/radiergummi/cetacean/internal/config"
"github.com/radiergummi/cetacean/internal/core"
"github.com/radiergummi/cetacean/internal/docker"
"github.com/radiergummi/cetacean/internal/exec"
"github.com/radiergummi/cetacean/internal/imagecheck"
"github.com/radiergummi/cetacean/internal/mcp"
"github.com/radiergummi/cetacean/internal/mcp/tracing"
"github.com/radiergummi/cetacean/internal/metrics"
"github.com/radiergummi/cetacean/internal/oauth"
promapi "github.com/radiergummi/cetacean/internal/prometheus"
"github.com/radiergummi/cetacean/internal/recommendations"
"github.com/radiergummi/cetacean/internal/timeline"
"github.com/radiergummi/cetacean/internal/version"
)
//go:embed frontend/dist/*
var frontendDist embed.FS
// widgetDist holds the MCP Apps widget bundles, one self-contained HTML
// document per widget, built by `npm run build:widgets`. Like frontend/dist
// above, it must exist before `go build`.
//
//go:embed frontend/dist-widgets/*
var widgetDist embed.FS
//go:embed api/openapi.yaml
var openapiSpec []byte
//go:embed api/asyncapi.yaml
var asyncapiSpec []byte
// scalarJS is the Scalar API reference bundle served at /api/scalar.js, copied
// out of node_modules by the frontend build's postbuild step, so Dependabot,
// the SBOM and THIRD_PARTY_LICENSES govern it. A missing file fails the build.
//
//go:embed frontend/dist/scalar.js
var scalarJS []byte
func main() {
flags, err := config.ParseFlags(os.Args[1:])
if errors.Is(err, flag.ErrHelp) {
os.Exit(0)
}
if err != nil {
fmt.Fprintf(os.Stderr, "flag error: %v\n", err)
os.Exit(2)
}
switch {
case len(flags.Args) == 0:
case len(flags.Args) == 1 && flags.Args[0] == "healthcheck":
os.Exit(runHealthcheck(flags))
default:
fmt.Fprintf(os.Stderr, "unknown command: %s\n", strings.Join(flags.Args, " "))
os.Exit(2)
}
if flags.Version {
fmt.Printf(
"cetacean %s (commit %s, built %s)\n",
version.Version,
version.Commit,
version.Date,
)
os.Exit(0)
}
s, err := loadSettings(flags)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
var logHandler slog.Handler
opts := &slog.HandlerOptions{Level: s.cfg.SlogLevel()}
if s.cfg.LogFormat == "text" {
logHandler = slog.NewTextHandler(os.Stdout, opts)
} else {
logHandler = slog.NewJSONHandler(os.Stdout, opts)
}
slog.SetDefault(slog.New(reqctx.LogHandler(logHandler)))
if s.configPath != "" {
slog.Info("loaded config file", "path", s.configPath, "discovered", flags.Config == "")
}
if err := run(s); err != nil {
slog.Error("cetacean stopped", "error", err)
os.Exit(1)
}
}
// settings is the configuration startup loads and refuses before logging is
// set up, so a misconfiguration reaches the terminal as one plain line.
type settings struct {
cfg *config.Config
authCfg *config.AuthConfig
tlsCfg config.TLSConfig
aclCfg config.ACLConfig
sizing *config.SizingConfig
configPath string
}
func loadSettings(flags *config.Flags) (settings, error) {
if err := config.CheckEnv(os.Environ()); err != nil {
return settings{}, fmt.Errorf("configuration error: %w", err)
}
cfg, fc, configPath, err := config.LoadFlagged(flags)
if err != nil {
return settings{}, fmt.Errorf("configuration error: %w", err)
}
authCfg, err := config.LoadAuth(flags, fc, cfg.PublicURL, cfg.BasePath)
if err != nil {
return settings{}, fmt.Errorf("auth configuration error: %w", err)
}
tlsCfg := config.LoadTLS(flags, fc)
if err := config.Validate(cfg, *authCfg, tlsCfg); err != nil {
return settings{}, err
}
if authCfg.Mode == "headers" {
// realIP reads the one, the provider the other; they must agree.
authCfg.Headers.TrustedProxies = cfg.TrustedProxies
}
aclCfg, err := config.LoadACL(fc)
if err != nil {
return settings{}, err
}
var sizing *config.SizingConfig
if cfg.Recommendations {
if sizing, err = config.LoadSizing(fc); err != nil {
return settings{}, fmt.Errorf("failed to load sizing config: %w", err)
}
}
return settings{
cfg: cfg,
authCfg: authCfg,
tlsCfg: tlsCfg,
aclCfg: aclCfg,
sizing: sizing,
configPath: configPath,
}, nil
}
// run serves until a signal, returning rather than exiting so every deferred
// close, the tracing flush among them, runs on the way out.
func run(s settings) error {
cfg, authCfg, tlsCfg := s.cfg, s.authCfg, s.tlsCfg
tsnetMode := authCfg.Mode == "tailscale" && authCfg.Tailscale.Mode == "tsnet"
// Resolved before either setup so both read the same value. config.Validate
// has already refused an unreachable one for the authorization server; MCP
// alone only wants it for its tool icon URLs.
issuer, reachable := cfg.OAuthIssuer(tlsCfg.Enabled())
if !reachable && cfg.MCP.Enabled {
slog.Warn(
"no reachable issuer could be derived from server.listen_addr; MCP tool icons will point at an unreachable URL. Set server.public_url to the URL clients reach from outside.",
"derived_issuer",
issuer,
"listen_addr",
cfg.ListenAddr,
)
}
var err error
var authProvider auth.Provider
var tsnetServer *tsnet.Server
var tsnetLn net.Listener
switch authCfg.Mode {
case "none":
authProvider = &auth.NoneProvider{}
case "oidc":
authProvider, err = auth.NewOIDCProvider(context.Background(), auth.OIDCProviderConfig{
Issuer: authCfg.OIDC.Issuer,
ClientID: authCfg.OIDC.ClientID,
ClientSecret: authCfg.OIDC.ClientSecret,
RedirectURL: authCfg.OIDC.RedirectURL,
Scopes: authCfg.OIDC.Scopes,
SessionKey: authCfg.OIDC.SessionKey,
BasePath: cfg.BasePath,
})
if err != nil {
return fmt.Errorf("OIDC provider setup failed: %w", err)
}
case "tailscale":
if tsnetMode {
authProvider, tsnetServer, tsnetLn, err = auth.NewTailscaleTsnetProvider(
authCfg.Tailscale.Hostname,
authCfg.Tailscale.AuthKey,
authCfg.Tailscale.StateDir,
authCfg.Tailscale.Capability,
)
if err != nil {
return fmt.Errorf("tsnet setup failed: %w", err)
}
defer tsnetServer.Close()
defer tsnetLn.Close()
} else {
authProvider = auth.NewTailscaleLocalProvider(authCfg.Tailscale.Capability)
}
case "cert":
authProvider = &auth.CertProvider{}
case "headers":
var extraHeaders []string
if s.aclCfg.HeadersACL != "" {
extraHeaders = append(extraHeaders, s.aclCfg.HeadersACL)
}
authProvider = auth.NewHeadersProvider(authCfg.Headers, extraHeaders...)
default:
return fmt.Errorf("unknown auth mode %q", authCfg.Mode)
}
// State cache — created first so its history can be passed to the broadcaster
stateCache := cache.New(nil, cache.WithHistorySize(cfg.HistoryEntries))
// SSE broadcaster — needs history for Last-Event-ID replay
broadcaster := sse.NewBroadcaster(cfg.SSEBatchInterval, stateCache.History())
defer broadcaster.Close()
// The metrics stream, log follows and MCP listens end with it at shutdown,
// as broadcaster.Close ends the event streams.
streams := sse.NewLifetime()
closeStreams := func() {
broadcaster.Close()
streams.End()
}
// Wire cache changes to SSE broadcaster.
// The cancel function is intentionally dropped: the broadcaster and cache
// share the process lifetime, so there is no window in which detaching the
// listener would matter.
stateCache.AddOnChangeListener(func(e cache.Event) {
broadcaster.Broadcast(e)
})
// Docker client + watcher
dockerClient, err := docker.NewClient(cfg.DockerHost, docker.TLS{
CA: cfg.DockerTLS.CA,
Cert: cfg.DockerTLS.Cert,
Key: cfg.DockerTLS.Key,
})
if err != nil {
return fmt.Errorf("docker client failed: %w", err)
}
defer dockerClient.Close() //nolint:errcheck // best-effort shutdown close
dockerClient.AttributeTo(stateCache.Attributions())
// A too-old daemon refuses every request, which otherwise surfaces as
// empty listings and a failing readiness probe.
versionCtx, versionCancel := context.WithTimeout(context.Background(), dockerProbeTimeout)
err = dockerClient.CheckAPIVersion(versionCtx)
versionCancel()
if err != nil {
return fmt.Errorf("unsupported Docker Engine at %s: %w", cfg.DockerHost, err)
}
// Created once, for whichever feature needs it: the cache snapshot, the
// timeline, the authorization server's token store. None is tied to another,
// so any reason alone is enough, and one call means one place that can fail.
dataDirReady := false
if cfg.Snapshot || cfg.Timeline || cfg.OAuth.Enabled {
//nolint:gosec // DataDir is operator-configured, not user input
if err := os.MkdirAll(cfg.DataDir, 0700); err != nil {
slog.Warn(
"could not create data dir; snapshots, history and OAuth state will not persist",
"error", err,
"path", cfg.DataDir,
)
} else {
dataDirReady = true
}
}
snapshotPath := ""
if cfg.Snapshot && dataDirReady {
snapshotPath = filepath.Join(cfg.DataDir, "snapshot.json")
if err := stateCache.LoadFromDisk(snapshotPath); err != nil {
slog.Info("no snapshot loaded", "error", err)
} else {
slog.Info("loaded snapshot from disk", "age", stateCache.SnapshotAge())
}
}
// Before the watcher starts; see History.Restore.
var (
timelineStore timeline.Store
timelineWriter *timeline.Writer
)
if cfg.Timeline && dataDirReady {
timelineStore = restoreTimeline(
filepath.Join(cfg.DataDir, "cetacean.db"),
stateCache,
cfg.HistoryEntries,
)
}
if timelineStore != nil {
// Taken before the first sync, which forgets the services removed in the
// gap, and retaken at each gap for the next.
serviceStacks := stateCache.ServiceStacks()
timelineWriter = timeline.NewWriter(
timelineStore,
stateCache.History(),
cfg.HistoryEntries,
func(ctx context.Context, from, streamSince time.Time) {
var recovered cache.Recovery
if !streamSince.IsZero() {
recovered = docker.RecoverGap(
ctx,
dockerClient,
from,
streamSince,
serviceStacks,
)
}
stateCache.RecordRecoveredGap(from, recovered)
serviceStacks = stateCache.ServiceStacks()
},
)
}
watcher := docker.NewWatcher(dockerClient, stateCache, snapshotPath)
watcher.SetTaskPollInterval(cfg.DockerTaskPollInterval)
// Start watcher in background
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
// Waited for at shutdown, within the same grace as the server, so the
// watcher's last snapshot lands before the Docker client closes.
watcherStopped := make(chan struct{})
// The gap is recorded before the stream records anything, and coverage
// opens only after it; a lost stream, or a shutdown, ends the heartbeats.
watching := make(chan struct{})
var watchingOnce sync.Once
watcher.SetOnWatching(func(streamSince time.Time) {
defer watchingOnce.Do(func() { close(watching) })
if timelineWriter != nil {
timelineWriter.RecordGap(ctx, streamSince)
}
})
if timelineWriter != nil {
timelineWriter.SetLive(func() bool { return ctx.Err() == nil && watcher.Watching() })
}
go func() {
defer close(watcherStopped)
watcher.Run(ctx)
}()
// Stopped only after the watcher and the HTTP server, so the changes and
// annotations they recorded last are written; a nil store stops at once.
timelineCtx, stopTimeline := context.WithCancel(context.Background())
timelineStopped := make(chan struct{})
go func() {
defer close(timelineStopped)
if timelineWriter != nil {
timelineWriter.Run(timelineCtx, watching)
}
}()
watcherDone := make(chan struct{})
go func() {
defer close(watcherDone)
<-ctx.Done()
grace, cancelGrace := context.WithTimeout(context.Background(), shutdownGrace)
defer cancelGrace()
select {
case <-watcherStopped:
case <-grace.Done():
slog.Warn(
"the watcher did not stop within the shutdown grace; its snapshot may be stale",
)
}
}()
// stopRecording runs once the HTTP server has stopped, or never started.
stopRecording := sync.OnceFunc(func() {
stop()
<-watcherDone
// A window of its own: a watcher that used up the grace would otherwise
// leave no time to write what it recorded last.
stopTimeline()
select {
case <-timelineStopped:
if timelineStore != nil {
if err := timelineStore.Close(); err != nil {
slog.Warn("could not close the timeline", "error", err)
}
}
case <-time.After(timelineGrace):
slog.Warn("the change history was not written within its shutdown grace")
}
})
// Every return from here on, an early error included, stops the watcher
// and waits for the history's last write.
defer stopRecording()
// API — pass ready channel so /-/ready reports sync status
var promClient *promapi.Client
var metricsProxy *promapi.Proxy
if cfg.PrometheusURL != "" {
promClient = promapi.NewClient(cfg.PrometheusURL)
metricsProxy = promapi.NewProxy(cfg.PrometheusURL)
slog.Info("prometheus configured", "url", cfg.PrometheusURL)
} else {
slog.Warn("prometheus not configured, metrics disabled")
}
imageChecker := startImageCheck(ctx, cfg, stateCache.ListServices, watcher.Ready())
imageAttestations := startImageAttestations(cfg)
// Recommendations engine
var recEngine *recommendations.Engine
if cfg.Recommendations {
sizingCfg := s.sizing
var checkers []recommendations.Checker
// Always register cache-only checkers. The operational checker derives
// flaky-service detection from the cache and falls back gracefully when
// Prometheus is unavailable (node disk/memory checks are skipped).
var opQuery recommendations.QueryFunc
if promClient != nil {
opQuery = promClient.InstantQuery
}
checkers = append(checkers,
recommendations.NewConfigChecker(stateCache),
recommendations.NewClusterChecker(stateCache),
recommendations.NewOperationalChecker(opQuery, stateCache, sizingCfg.Lookback),
)
if imageChecker != nil {
checkers = append(checkers, recommendations.NewImageChecker(
stateCache,
func(svc swarm.Service) (string, bool) {
update := cluster.ServiceImageUpdate(svc, imageChecker)
if update == nil {
return "", false
}
return update.Image, true
},
))
}
// Register Prometheus-dependent checkers when available.
if promClient != nil {
checkers = append(
checkers,
recommendations.NewSizingChecker(promClient.InstantQuery, stateCache, sizingCfg),
)
}
recEngine = recommendations.NewEngine(checkers...)
if recEngine != nil {
go recEngine.RunAfter(ctx, watcher.Ready())
slog.Info("recommendation engine started", "checkers", len(checkers))
}
} else {
slog.Info("recommendation engine disabled")
}
aclEval, stopPolicyWatch, err := acl.FromConfig(authCfg.Mode, s.aclCfg, stateCache)
if err != nil {
return err
}
defer stopPolicyWatch()
slog.Info("operations level", "level", cfg.OperationsLevel)
if authCfg.Mode == "none" && cfg.OperationsLevel > config.OpsReadOnly {
slog.Warn(
"auth.mode is none with writes enabled: anyone who can reach the server may "+
"change the cluster up to the operations level",
"operations_level", cfg.OperationsLevel,
)
}
if authCfg.Mode == "none" && stateCache.AnnotationsOn() {
slog.Warn("auth.mode is none: anyone who can reach the server may write annotations, " +
"at every operations level including 0")
}
if cfg.Exec.Enabled && cfg.OperationsLevel < cluster.OpOpenExec.Tier() {
slog.Warn("exec.enabled has no effect below server.operations_level 3")
}
shared := core.New(stateCache, streams)
handlers := api.NewHandlers(
shared,
broadcaster,
dockerClient,
dockerClient,
dockerClient,
dockerClient,
watcher.Ready(),
promClient,
cfg.OperationsLevel,
recEngine,
aclEval,
)
handlers.SetTokenOperationsLevel(
cfg.OAuth.EffectiveTokenOperationsLevel(cfg.OperationsLevel),
)
if imageChecker != nil {
handlers.SetImageDigests(imageChecker)
}
if imageAttestations != nil {
handlers.SetAttestations(imageAttestations)
}
if cfg.Exec.Enabled {
closeExec, err := startExec(ctx, cfg, handlers, dockerClient, aclEval)
if err != nil {
return err
}
// Stopped first on an early return too, or the wait would never end.
defer func() { stop(); closeExec() }()
}
// SPA
distFS, err := fs.Sub(frontendDist, "frontend/dist")
if err != nil {
return fmt.Errorf("failed to create sub FS: %w", err)
}
spa := api.NewSPAHandler(distFS, cfg.BasePath)
// The SPA applies the stored theme from an inline script before the first
// paint; the CSP allows it by hashing the document actually being served,
// so the policy cannot drift from an edit to index.html.
inlineScriptHashes, err := api.InlineScriptHashes(distFS)
if err != nil {
return fmt.Errorf("failed to hash the SPA's inline scripts: %w", err)
}
if cfg.Pprof {
slog.Warn("pprof endpoints enabled", "path", "/debug/pprof/")
}
var corsConfig *api.CORSConfig
if len(cfg.CORSOrigins) > 0 {
corsConfig = &api.CORSConfig{AllowedOrigins: cfg.CORSOrigins}
slog.Info("CORS enabled", "origins", cfg.CORSOrigins)
// A wildcard can only answer half of what this setting decides: "*" is
// not an origin, so it cannot be trusted for cross-origin writes.
if corsConfig.Wildcard() {
slog.Warn(
"server.cors.origins is a wildcard: browsers may read the API " +
"from any origin, but cross-origin writes are refused. List " +
"the origins explicitly to allow them.",
)
}
}
// Opt-in: with no collector configured the MCP server keeps mcp-go's noop
// tracer. The MCP server is the only thing emitting spans, so building the
// pipeline without it would leave a batch processor and its goroutine
// alive for the life of the process with nothing able to feed them.
var mcpTracer oteltrace.Tracer
if cfg.OTelEndpoint != "" && !cfg.MCP.Enabled {
slog.Warn(
"tracing is configured but the MCP server is disabled, so no spans will be exported",
"endpoint", cfg.OTelEndpoint,
)
}
if cfg.OTelEndpoint != "" && cfg.MCP.Enabled {
traceProvider, err := tracing.NewProvider(ctx, cfg.OTelEndpoint, version.Version)
if err != nil {
return fmt.Errorf("tracing setup failed: %w", err)
}
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := traceProvider.Shutdown(shutdownCtx); err != nil {
slog.Warn("tracing shutdown failed", "error", err)
}
}()
mcpTracer = traceProvider.Tracer()
slog.Info("distributed tracing enabled", "endpoint", cfg.OTelEndpoint)
}
if mcpInClear(cfg.MCP.Enabled, authCfg.Mode, tlsCfg.Enabled() || tsnetMode, cfg.PublicURL) {
slog.Warn("MCP is enabled without TLS: credentials reach /mcp in clear text. " +
"Set tls.cert and tls.key, or server.public_url to the https URL of a terminating proxy.")
}
var tsnetDomains []string
if tsnetServer != nil {
tsnetDomains = tsnetServer.CertDomains()
}
if warning := hostGuardWarning(
cfg.ListenAddr, cfg.PublicURL, cfg.AllowedHosts, tsnetDomains,
); warning != "" {
slog.Warn(warning)
}
// One set for both guards, so /mcp never answers a Host the API refuses.
hosts := auth.NewHostSet(
cfg.PublicURL,
append(allowedHosts(cfg.ListenAddr, tsnetDomains), cfg.AllowedHosts...)...,
)
deps := mcpDeps{
cfg: cfg,
hosts: hosts,
cors: corsConfig,
authMode: authCfg.Mode,
authProvider: authProvider,
issuer: issuer,
dataDirReady: dataDirReady,
shared: shared,
writeClient: dockerClient,
logs: dockerClient,
acl: aclEval,
rec: recEngine,
prometheus: promClient,
images: imageChecker,
attestations: imageAttestations,
tracer: mcpTracer,
}
oauthSrv := setupOAuth(deps)
// One nil check for both consumers. A nil *oauth.Server is not a nil
// interface and not a nil func value, so assigning it unguarded would arm
// bearerAuth on a nil receiver and mount routes that call through nothing.
var (
tokenVerifier mcp.TokenVerifier
oauthRoutes func(mux *http.ServeMux, basePath string)
apiTokens auth.APITokens
tokenRevoker api.TokenRevoker
mcpResource string
)
if oauthSrv != nil {
tokenVerifier, oauthRoutes, tokenRevoker = oauthSrv, oauthSrv.RegisterRoutes, oauthSrv
mcpResource = oauthSrv.ResourceIdentifier(mcp.MountPath)
// Only when the API is actually offered as a resource: without it there
// is no audience a token could carry, so a verifier here would refuse
// every bearer it was handed instead of leaving it to the provider.
if cfg.OAuth.APITokens {
apiTokens = auth.APITokens{
Verifier: oauthSrv,
Resource: oauthSrv.ResourceIdentifier(""),
}
}
}
mcpHandler, closeMCP, err := setupMCP(deps, tokenVerifier, mcpResource)
if err != nil {
return err
}
defer closeMCP()
router := api.NewRouter(api.RouterConfig{
Handlers: handlers,
Broadcaster: broadcaster,
MetricsProxy: metricsProxy,
SPA: spa,
InlineScriptHashes: inlineScriptHashes,
OpenAPISpec: openapiSpec,
AsyncAPISpec: asyncapiSpec,
ScalarJS: scalarJS,
EnablePprof: cfg.Pprof,
EnableSelfMetrics: cfg.SelfMetrics,
EnableVersionCheck: cfg.VersionCheck,
AuthProvider: authProvider,
BasePath: cfg.BasePath,
PublicURL: cfg.PublicURL,
Hosts: hosts,
CORS: corsConfig,
TLSEnabled: tlsCfg.Enabled() || tsnetMode,
TrustedProxies: cfg.TrustedProxies,
ForwardedHeaders: cfg.ForwardedHeaders,
Resyncer: watcher,
Liveness: watcher,
Refresher: watcher,
MCPHandler: mcpHandler,
OAuthRoutes: oauthRoutes,
APITokens: apiTokens,
TokenRevoker: tokenRevoker,
})
var serverTLSConfig *tls.Config
// Only where we terminate TLS ourselves: behind a TLS-terminating proxy
// the client certificate arrives in a header the proxy already verified,
// and this config would never be consulted.
if authCfg.Mode == "cert" && tlsCfg.Enabled() {
//nolint:gosec // G703: the CA path is operator-configured, not user input
caCert, err := os.ReadFile(filepath.Clean(authCfg.Cert.CA))
if err != nil {
return fmt.Errorf("failed to read CA cert: %w", err)
}
caPool := x509.NewCertPool()
if !caPool.AppendCertsFromPEM(caCert) {
return errors.New("failed to parse CA cert")
}
serverTLSConfig = clientCertTLS(caPool)
}
// tsnet mode: dual listeners (tailnet for app, regular for meta only)
if tsnetLn != nil {
// The watcher stops when ctx does, which a failed listener does not cause:
// waiting on it then would hold the process until a signal.
if err := serveDualListeners(
ctx,
cfg,
router,
handlers,
tsnetLn,
closeStreams,
); err != nil {
return err
}
stopRecording()
slog.Info("shutdown complete")
return nil
}
server := &http.Server{
Addr: cfg.ListenAddr,
Handler: router,
ReadTimeout: serverReadTimeout,
WriteTimeout: 0, // SSE requires no write timeout; per-request timeouts used instead
IdleTimeout: serverIdleTimeout,
TLSConfig: serverTLSConfig,
}
// Shutdown waits for every handler to return, and a stream never does on
// its own: end them first, or each deploy waits out the grace.
server.RegisterOnShutdown(closeStreams)
// Graceful shutdown. ListenAndServe returns ErrServerClosed as soon as
// Shutdown closes the listeners, so main waits on drained rather than
// returning mid-drain.
drained := make(chan struct{})
go func() {
defer close(drained)
<-ctx.Done()
slog.Info("shutting down", "cause", context.Cause(ctx))
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), shutdownGrace)
defer shutdownCancel()
if err := server.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown error", "error", err)
}
}()
slog.Info(
"server started",
"listen_addr",
cfg.ListenAddr,
"base_path",
cfg.BasePath,
"version",
version.Version,
"commit",
version.Commit,
"auth",
authCfg.Mode,
)
if tlsCfg.Enabled() {
slog.Info("TLS enabled", "cert", tlsCfg.Cert, "key", tlsCfg.Key)
if err := server.ListenAndServeTLS(tlsCfg.Cert, tlsCfg.Key); err != http.ErrServerClosed {
return fmt.Errorf("server error: %w", err)
}
} else {
if err := server.ListenAndServe(); err != http.ErrServerClosed {
return fmt.Errorf("server error: %w", err)
}
}
<-drained
stopRecording()
slog.Info("shutdown complete")
return nil
}
// openTimeline opens the timeline, waiting up to timelineHeldWait while
// another process holds it.
func openTimeline(ctx context.Context, path string) (*timeline.SQLite, error) {
deadline := time.Now().Add(timelineHeldWait)
for waited := false; ; waited = true {
store, err := timeline.OpenSQLite(ctx, path)
if !errors.Is(err, timeline.ErrHeld) || time.Now().After(deadline) {
return store, err
}
if !waited {
slog.InfoContext(ctx, "the timeline is held by another process; waiting", "path", path)
}
time.Sleep(time.Second)
}
}
// restoreTimeline opens the timeline and fills the history and the annotations
// from it, or returns nil when it cannot: the history then lives in memory
// only, as it would with storage.timeline off, and startup goes on.
func restoreTimeline(path string, stateCache *cache.Cache, keep int) timeline.Store {
ctx := context.Background()
store, err := openTimeline(ctx, path)
if err != nil {
slog.Warn("could not open the timeline; the change history will not persist",
"error", err, "path", path)
return nil
}
entries, last, err := store.Restore(ctx, keep)
if err != nil {
_ = store.Close()
slog.Warn("could not restore the timeline; the change history will not persist",
"error", err, "path", path)
return nil
}
annotations, err := store.Annotations(ctx)
if err != nil {
_ = store.Close()
slog.Warn("could not restore the annotations; the change history will not persist",
"error", err, "path", path)
return nil
}
stateCache.History().Restore(entries, last, store.Instance())
// IDs past Count reach readers before the first flush stores any of them;
// storing Count now makes the next start skip them even after a crash.
if err := store.Commit(ctx, timeline.Batch{Last: stateCache.History().Count()}); err != nil {
slog.Warn("could not reserve history IDs; a crash before the first write may reissue them",
"error", err, "path", path)
}
stateCache.RestoreAnnotations(store, annotations)
slog.Info("restored the change history",
"entries", len(entries), "annotations", len(annotations))
return store
}
// dockerProbeTimeout bounds the startup version probe, so a socket that
// accepts and then says nothing cannot hold startup open.
const dockerProbeTimeout = 10 * time.Second
// Every listener shares these; none sets a write timeout, since SSE streams
// for as long as the client stays.
const (
serverReadTimeout = 5 * time.Second
serverIdleTimeout = 120 * time.Second
)
// execShutdownGrace bounds the wait for live shells to be signalled and their
// ends recorded; it matches the pump's own bound on closing a shell.
const execShutdownGrace = 10 * time.Second
// shutdownGrace bounds how long a signalled process waits for in-flight
// requests, inside the ten seconds an orchestrator allows before SIGKILL.
const shutdownGrace = 5 * time.Second
// timelineGrace bounds the history's final write, after the watcher stopped.
const timelineGrace = 2 * time.Second
// timelineHeldWait is how long startup waits for a previous process, such as
// the task a start-first update replaces, to let go of the timeline.
const timelineHeldWait = 15 * time.Second
// runHealthcheck probes the server's readiness with the configuration the
// server itself would load, so a listen address, base path or TLS set in any
// source is the one probed.
func runHealthcheck(flags *config.Flags) int {
cfg, fc, _, err := config.LoadFlagged(flags)
if err != nil {
fmt.Fprintf(os.Stderr, "healthcheck failed: %v\n", err)
return 1
}
tlsEnabled := config.LoadTLS(flags, fc).Enabled()
target, err := healthcheckURL(cfg.ListenAddr, cfg.BasePath, tlsEnabled)
if err != nil {
fmt.Fprintf(os.Stderr, "healthcheck failed: %v\n", err)
return 1
}
if err := probeReady(target, tlsEnabled); err != nil {
fmt.Fprintf(os.Stderr, "healthcheck failed: %v\n", err)
return 1
}
return 0
}
// healthcheckURL is where readiness answers from inside the server's own
// container: a wildcard or empty listen host is reached over loopback.
func healthcheckURL(listenAddr, basePath string, tlsEnabled bool) (string, error) {
host, port, err := net.SplitHostPort(listenAddr)
if err != nil {
return "", fmt.Errorf("listen address %q: %w", listenAddr, err)
}
if ip := net.ParseIP(host); host == "" || ip != nil && ip.IsUnspecified() {
host = "localhost"
}
scheme := "http"
if tlsEnabled {
scheme = "https"
}
target := url.URL{
Scheme: scheme,
Host: net.JoinHostPort(host, port),
Path: basePath + "/-/ready",
}
return target.String(), nil
}
// clientCertTLS verifies any certificate a client presents against pool, but
// admits one that presents none: the healthcheck has no certificate, and
// CertProvider refuses every authenticated route to a caller without one.
func clientCertTLS(pool *x509.CertPool) *tls.Config {
return &tls.Config{ClientCAs: pool, ClientAuth: tls.VerifyClientCertIfGiven}
}
func probeReady(target string, tlsEnabled bool) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
if err != nil {
return err
}
// No Proxy: the listen address is the server's own, never one a proxy reaches.
transport := &http.Transport{}