-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathservice.go
More file actions
645 lines (607 loc) · 20 KB
/
Copy pathservice.go
File metadata and controls
645 lines (607 loc) · 20 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
// Package kata exposes Kata as a listener-free application service.
//
// A Service owns its configured storage handle and core background workers.
// Callers mount Handler in their own HTTP server, run background work with Run,
// and release owned resources with Close. The package does not open a network
// listener, install signal handlers, or manage its caller's process lifecycle.
package kata
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
"sync"
"time"
"go.kenn.io/kata/internal/config"
"go.kenn.io/kata/internal/daemon"
"go.kenn.io/kata/internal/db"
"go.kenn.io/kata/internal/db/pgstore"
"go.kenn.io/kata/internal/db/storeopen"
"go.kenn.io/kata/internal/federation"
"go.kenn.io/kata/internal/githubsync"
"go.kenn.io/kata/internal/hooks"
)
// PostgresSchemaMode controls how a PostgreSQL-backed service treats its
// configured schema at startup.
type PostgresSchemaMode string
const (
// PostgresSchemaBootstrap installs missing Kata migrations before serving.
PostgresSchemaBootstrap PostgresSchemaMode = "bootstrap"
// PostgresSchemaValidate requires an already-installed, compatible schema
// and performs no schema installation.
PostgresSchemaValidate PostgresSchemaMode = "validate"
)
// EmbeddingProfile selects which HTTP administration surfaces a mounted
// service exposes. The zero value preserves standalone-compatible operations
// supported by the public embedding configuration. Federation endpoint rebind
// remains daemon-only because mounted services do not expose a daemon catalog
// or exact credential-replacement contract.
type EmbeddingProfile string
// Embedding profiles supported by Config.Profile.
const (
EmbeddingProfileStandalone EmbeddingProfile = ""
// EmbeddingProfileRestricted is for applications that own project,
// credential, federation, and external-integration administration. It keeps
// task and federation transport behavior while failing closed on native
// administration routes.
EmbeddingProfileRestricted EmbeddingProfile = "restricted"
)
// PostgresConfig selects an isolated PostgreSQL schema and startup policy.
// Empty fields use Kata's standalone defaults.
type PostgresConfig struct {
Schema string
SchemaMode PostgresSchemaMode
SchemaOwner string
AllowInsecureTransport bool
}
// AuthConfig defines Kata-owned authentication for a mounted Service. Select
// exactly one of Token, TrustCallerAuthentication, or Config.Access.
type AuthConfig struct {
// Token protects Kata's ordinary HTTP surface. Federation transport and
// claim actions retain their own scoped credential checks.
Token string
// TrustCallerAuthentication disables Kata's bearer check because the
// caller guarantees that Handler is mounted behind its own authentication
// boundary. Never mount that handler directly on an untrusted listener.
TrustCallerAuthentication bool
}
// GitHubSyncConfig supplies credentials used by GitHub issue synchronization.
// TokenEnv names an environment variable containing a token; token values are
// never stored in Config. Empty fields use Kata's standalone defaults.
type GitHubSyncConfig struct {
TokenEnv string
TokenHost string
Apps []GitHubAppConfig
}
// GitHubAppConfig identifies one GitHub App installation credential.
type GitHubAppConfig struct {
Host string
Owner string
AppID int64
InstallationID int64
PrivateKeyPath string
}
// Config contains the process-neutral inputs needed to construct a Service.
type Config struct {
// DSN accepts a SQLite path, sqlite:// URL, or PostgreSQL URL.
DSN string
Postgres PostgresConfig
Auth AuthConfig
GitHubSync GitHubSyncConfig
// DefaultTimezone applies to civil schedules without issue timezone.
// Empty means UTC.
DefaultTimezone string
// Access selects host-supplied in-process authentication and authorization.
// It is mutually exclusive with Auth.
Access AccessController
// FederationAccess optionally adds host-owned authorization after Kata has
// authenticated a project-scoped federation credential. It does not replace
// Kata's credential authentication.
FederationAccess FederationAccessController
// WorkerTransactionFence revalidates host authority from inside every
// background-worker writable storage transaction. It is required when
// Access is set.
WorkerTransactionFence TransactionFence
// Profile optionally removes native administration routes that an embedding
// host owns. The zero value keeps the complete standalone-compatible API.
Profile EmbeddingProfile
// FederationCredentials isolates secret material from other Service
// instances. Nil selects a service-owned in-memory store.
FederationCredentials FederationCredentialStore
StartedAt time.Time
Logger *slog.Logger
}
type serviceDeps struct {
gitHubSyncFetcher githubsync.Fetcher
gitHubSyncFetcherFactory func(config.GitHubSyncConfig) githubsync.Fetcher
}
// Service is a mountable Kata HTTP application and its owned lifecycle.
type Service struct {
store db.Storage
server *daemon.Server
broadcaster *daemon.EventBroadcaster
hookSink hooks.Sink
federationWake chan struct{}
gitHubSyncWake chan struct{}
gitHubSyncFetcher githubsync.Fetcher
federationCredentials config.FederationCredentialStore
logger *slog.Logger
hostAccessEnabled bool
workerTransactionFence TransactionFence
lifetimeCtx context.Context
lifetimeCancel context.CancelFunc
handlerWG sync.WaitGroup
mu sync.Mutex
running bool
runCancel context.CancelFunc
runDone chan struct{}
closed bool
closeDone chan struct{}
closeErr error
}
// New opens the configured backend and constructs a listener-free service.
// The returned Service owns the backend handle and closes it from Close.
func New(ctx context.Context, cfg Config) (*Service, error) {
return newService(ctx, cfg, serviceDeps{})
}
func newService(ctx context.Context, cfg Config, deps serviceDeps) (*Service, error) {
if strings.TrimSpace(cfg.DSN) == "" {
return nil, errors.New("kata: storage DSN is required")
}
if cfg.Profile != EmbeddingProfileStandalone && cfg.Profile != EmbeddingProfileRestricted {
return nil, fmt.Errorf("kata: unknown embedding profile %q", cfg.Profile)
}
cfg.DefaultTimezone = strings.TrimSpace(cfg.DefaultTimezone)
if cfg.DefaultTimezone != "" {
if _, err := time.LoadLocation(cfg.DefaultTimezone); err != nil {
return nil, fmt.Errorf("kata: default timezone %q is not a valid IANA timezone: %w", cfg.DefaultTimezone, err)
}
}
usesAccess := cfg.Access != nil
usesToken := strings.TrimSpace(cfg.Auth.Token) != ""
usesTrustedCaller := cfg.Auth.TrustCallerAuthentication
if !usesAccess && !usesToken && !usesTrustedCaller {
return nil, errors.New("kata: auth token is required unless caller authentication is explicitly trusted")
}
if boolCount(usesAccess, usesToken, usesTrustedCaller) != 1 {
return nil, errors.New("kata: auth token, trusted caller authentication, and host access are mutually exclusive")
}
gitHubSyncConfig, err := resolveGitHubSyncConfig(cfg.GitHubSync)
if err != nil {
return nil, fmt.Errorf("kata: GitHub sync config: %w", err)
}
publicFederationCredentials := cfg.FederationCredentials
if publicFederationCredentials == nil {
publicFederationCredentials = newMemoryFederationCredentialStore()
}
federationCredentials := serviceCredentialStoreAdapter{store: publicFederationCredentials}
openCfg := storeopen.DefaultConfig()
pgCfg := cfg.Postgres
openCfg.Postgres = pgstore.ConfigFromValues(
pgCfg.Schema,
string(pgCfg.SchemaMode),
pgCfg.SchemaOwner,
pgCfg.AllowInsecureTransport,
)
store, err := storeopen.OpenWithConfig(ctx, cfg.DSN, openCfg, db.Serving())
if err != nil {
return nil, fmt.Errorf("kata: open storage: %w", err)
}
startedAt := cfg.StartedAt
if startedAt.IsZero() {
startedAt = time.Now().UTC()
}
logger := cfg.Logger
if logger == nil {
logger = slog.Default()
}
lifetimeCtx, lifetimeCancel := context.WithCancel(context.Background())
broadcaster := daemon.NewEventBroadcaster()
hookSink := hooks.NewNoop()
federationWake := make(chan struct{}, 1)
wakeFederation := func() {
select {
case federationWake <- struct{}{}:
default:
}
}
gitHubSyncWake := make(chan struct{}, 1)
wakeGitHubSync := func() {
select {
case gitHubSyncWake <- struct{}{}:
default:
}
}
gitHubSyncFetcher := deps.gitHubSyncFetcher
if gitHubSyncFetcher == nil {
factory := deps.gitHubSyncFetcherFactory
if factory == nil {
factory = func(cfg config.GitHubSyncConfig) githubsync.Fetcher {
return githubsync.NewHTTPFetcher(githubsync.HTTPFetcherConfig{
CredentialResolver: githubsync.NewCredentialResolver(cfg, nil),
})
}
}
gitHubSyncFetcher = factory(gitHubSyncConfig)
}
var hostAccess daemon.HostAccessController
if cfg.Access != nil {
hostAccess = hostAccessControllerAdapter{controller: cfg.Access}
}
var hostFederationAccess daemon.HostFederationAccessController
if cfg.FederationAccess != nil {
hostFederationAccess = hostFederationAccessControllerAdapter{
controller: cfg.FederationAccess,
}
}
server := daemon.NewServer(daemon.ServerConfig{
DB: store,
DefaultTimezone: cfg.DefaultTimezone,
StartedAt: startedAt,
Broadcaster: broadcaster,
FederationWake: wakeFederation,
FederationCredentials: federationCredentials,
DisableFederationRebind: true,
GitHubSyncFetcher: gitHubSyncFetcher,
GitHubSyncConfig: gitHubSyncConfig,
GitHubSyncWake: wakeGitHubSync,
Hooks: hookSink,
Auth: config.AuthConfig{Token: cfg.Auth.Token},
HostAccess: hostAccess,
HostFederationAccess: hostFederationAccess,
EmbeddingProfile: daemon.EmbeddingProfile(cfg.Profile),
Logger: logger,
})
return &Service{
store: store,
server: server,
broadcaster: broadcaster,
hookSink: hookSink,
federationWake: federationWake,
gitHubSyncWake: gitHubSyncWake,
gitHubSyncFetcher: gitHubSyncFetcher,
federationCredentials: federationCredentials,
logger: logger,
hostAccessEnabled: cfg.Access != nil,
workerTransactionFence: cfg.WorkerTransactionFence,
lifetimeCtx: lifetimeCtx,
lifetimeCancel: lifetimeCancel,
closeDone: make(chan struct{}),
}, nil
}
func resolveGitHubSyncConfig(cfg GitHubSyncConfig) (config.GitHubSyncConfig, error) {
apps := make([]config.GitHubAppConfig, len(cfg.Apps))
for i := range cfg.Apps {
app := cfg.Apps[i]
apps[i] = config.GitHubAppConfig{
Host: app.Host,
Owner: app.Owner,
AppID: app.AppID,
InstallationID: app.InstallationID,
PrivateKeyPath: app.PrivateKeyPath,
}
}
return config.NormalizeGitHubSyncConfig(config.GitHubSyncConfig{
TokenEnv: cfg.TokenEnv, TokenHost: cfg.TokenHost, Apps: apps,
})
}
// Handler returns the HTTP application for mounting in a caller-owned server.
func (s *Service) Handler() http.Handler { return http.HandlerFunc(s.serveHTTP) }
func (s *Service) serveHTTP(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
if s.closed {
s.mu.Unlock()
http.Error(w, "kata service is closed", http.StatusServiceUnavailable)
return
}
s.handlerWG.Add(1)
lifetimeCtx := s.lifetimeCtx
s.mu.Unlock()
defer s.handlerWG.Done()
requestCtx, cancel := context.WithCancel(r.Context())
stopLifetimeCancel := context.AfterFunc(lifetimeCtx, cancel)
defer func() {
stopLifetimeCancel()
cancel()
}()
if principal, ok := principalFromContext(requestCtx); s.hostAccessEnabled && ok {
requestCtx = daemon.WithPrincipal(requestCtx, daemon.Principal{
Kind: daemon.PrincipalHost, Subject: principal.Subject, Actor: principal.Actor,
})
}
s.server.Handler().ServeHTTP(w, r.WithContext(requestCtx))
}
func boolCount(values ...bool) int {
count := 0
for _, value := range values {
if value {
count++
}
}
return count
}
type hostAccessControllerAdapter struct {
controller AccessController
}
type hostFederationAccessControllerAdapter struct {
controller FederationAccessController
}
func (a hostFederationAccessControllerAdapter) AuthorizeFederation(
ctx context.Context,
request daemon.HostFederationAccessRequest,
) (daemon.HostFederationAccessDecision, error) {
if a.controller == nil {
return daemon.HostFederationAccessDecision{}, nil
}
decision, err := a.controller.AuthorizeFederation(ctx, FederationAccessRequest{
Enrollment: publicFederationEnrollment(request.Enrollment, request.Project.UID),
Project: publicProject(request.Project),
Capability: FederationCapability(request.Capability),
Operation: FederationOperation{
ID: request.Operation.ID, Mutation: request.Operation.Mutation,
},
})
if errors.Is(err, ErrAccessDenied) {
return daemon.HostFederationAccessDecision{}, daemon.ErrHostAccessDenied
}
if errors.Is(err, ErrFederationAdmissionLimited) {
return daemon.HostFederationAccessDecision{}, daemon.ErrHostFederationAdmissionLimited
}
if err != nil {
return daemon.HostFederationAccessDecision{}, err
}
var transactionFence db.TransactionFence
if decision.TransactionFence != nil {
transactionFence = func(ctx context.Context, transaction db.Transaction) error {
err := decision.TransactionFence(ctx, transaction)
if errors.Is(err, ErrAccessDenied) {
return daemon.ErrHostAccessDenied
}
return err
}
}
return daemon.HostFederationAccessDecision{TransactionFence: transactionFence}, nil
}
func (a hostAccessControllerAdapter) Authorize(
ctx context.Context,
request daemon.HostAccessRequest,
) (daemon.HostAccessDecision, error) {
if a.controller == nil {
return daemon.HostAccessDecision{}, nil
}
decision, err := a.controller.Authorize(ctx, AccessRequest{
Principal: Principal{Subject: request.Subject, Actor: request.Actor},
Operation: Operation{
ID: request.Operation.ID, Method: request.Operation.Method, Path: request.Operation.Path,
PathParams: request.Operation.PathParams,
Policy: OperationPolicy{
Kind: OperationKind(request.Operation.Policy.Kind),
Capability: Capability(request.Operation.Policy.Capability),
Mutation: request.Operation.Policy.Mutation,
LongLived: request.Operation.Policy.LongLived,
},
ProjectIDs: append([]int64(nil), request.Operation.ProjectIDs...),
ProjectUIDs: append([]string(nil), request.Operation.ProjectUIDs...),
AllProjects: request.Operation.AllProjects,
},
})
if errors.Is(err, ErrAccessDenied) {
return daemon.HostAccessDecision{}, daemon.ErrHostAccessDenied
}
if err != nil {
return daemon.HostAccessDecision{}, err
}
var revalidate func(context.Context) error
if decision.Lease != nil {
revalidate = decision.Lease.Revalidate
}
var transactionFence db.TransactionFence
if decision.TransactionFence != nil {
transactionFence = func(ctx context.Context, transaction db.Transaction) error {
err := decision.TransactionFence(ctx, transaction)
if errors.Is(err, ErrAccessDenied) {
return daemon.ErrHostAccessDenied
}
return err
}
}
return daemon.HostAccessDecision{
Revalidate: revalidate, TransactionFence: transactionFence,
}, nil
}
// Run executes Kata's federation, GitHub synchronization, and timed-claim
// workers until ctx is canceled or Close is called. Run does not start a
// listener and may be called only once at a time.
func (s *Service) Run(ctx context.Context) error {
if ctx == nil {
return errors.New("kata: run context is required")
}
if s.hostAccessEnabled && s.workerTransactionFence == nil {
return errors.New("kata: worker transaction fence is required with host access")
}
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return errors.New("kata: service is closed")
}
if s.running {
s.mu.Unlock()
return errors.New("kata: service is already running")
}
runCtx, cancel := context.WithCancel(ctx)
workerFenceFailures := make(chan error, 1)
var reportWorkerFenceFailure sync.Once
if s.workerTransactionFence != nil {
runCtx = db.WithTransactionFence(runCtx, func(
fenceCtx context.Context,
transaction db.Transaction,
) error {
err := s.workerTransactionFence(fenceCtx, transaction)
if err != nil {
reportWorkerFenceFailure.Do(func() {
workerFenceFailures <- err
cancel()
})
}
return err
})
}
done := make(chan struct{})
s.running = true
s.runCancel = cancel
s.runDone = done
s.mu.Unlock()
defer func() {
cancel()
s.mu.Lock()
s.running = false
s.runCancel = nil
close(done)
s.mu.Unlock()
}()
federationSub := s.broadcaster.Subscribe(daemon.SubFilter{})
federationWakeDone := make(chan struct{})
go func() {
defer close(federationWakeDone)
for {
select {
case <-runCtx.Done():
return
case msg, ok := <-federationSub.Ch:
if !ok {
return
}
if msg.Kind == "event" {
signalWake(s.federationWake)
}
}
}
}()
defer func() {
cancel()
<-federationWakeDone
federationSub.Unsub()
}()
workerErrs := make(chan error, 3)
runner := &federation.Runner{
DB: s.store,
Credentials: s.federationCredentials,
Interval: 30 * time.Second,
Wake: s.federationWake,
OnError: func(err error) {
s.logger.Error("kata federation worker", "err", err)
},
OnPulledEvents: func(projectID int64, events []db.Event) {
for i := range events {
event := events[i]
s.broadcaster.Broadcast(daemon.StreamMsg{
Kind: "event", Event: &event, ProjectID: projectID,
})
}
},
}
gitHubSyncRunner := githubsync.NewRunner(githubsync.RunnerConfig{
Store: s.store,
Fetcher: s.gitHubSyncFetcher,
Logger: s.logger,
Interval: 5 * time.Minute,
Wake: s.gitHubSyncWake,
EventSink: func(_ context.Context, projectID int64, events []db.Event) error {
for i := range events {
event := events[i]
s.broadcaster.Broadcast(daemon.StreamMsg{
Kind: "event", Event: &event, ProjectID: projectID,
})
s.hookSink.Enqueue(event)
}
return nil
},
})
sweeper := daemon.NewTimedClaimSweeper(s.store, s.broadcaster, s.hookSink)
sweeper.OnError = func(err error) {
s.logger.Error("kata timed-claim worker", "err", err)
}
go func() { workerErrs <- runner.Run(runCtx) }()
go func() { workerErrs <- gitHubSyncRunner.Run(runCtx) }()
go func() { workerErrs <- sweeper.Run(runCtx) }()
workerResults := make([]error, 0, 3)
var workerFenceFailure error
select {
case <-runCtx.Done():
case workerFenceFailure = <-workerFenceFailures:
case err := <-workerErrs:
workerResults = append(workerResults, err)
}
cancel()
for len(workerResults) < 3 {
workerResults = append(workerResults, <-workerErrs)
}
if workerFenceFailure == nil {
select {
case workerFenceFailure = <-workerFenceFailures:
default:
}
}
shuttingDown := ctx.Err() != nil || s.isClosed()
if shuttingDown && errors.Is(workerFenceFailure, context.Canceled) {
return nil
}
if workerFenceFailure != nil {
return fmt.Errorf("kata: worker transaction fence: %w", workerFenceFailure)
}
if runCtx.Err() != nil && shuttingDown {
return nil
}
for i := range workerResults {
workerResults[i] = normalizeWorkerError(workerResults[i])
}
return errors.Join(workerResults...)
}
func signalWake(ch chan<- struct{}) {
select {
case ch <- struct{}{}:
default:
}
}
func normalizeWorkerError(err error) error {
if errors.Is(err, context.Canceled) {
return nil
}
return err
}
func (s *Service) isClosed() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.closed
}
// Close stops active background work and releases every resource owned by the
// service. It is safe to call Close more than once.
func (s *Service) Close() error {
s.mu.Lock()
if s.closed {
done := s.closeDone
s.mu.Unlock()
<-done
s.mu.Lock()
defer s.mu.Unlock()
return s.closeErr
}
s.closed = true
s.lifetimeCancel()
cancel := s.runCancel
runDone := s.runDone
s.mu.Unlock()
if cancel != nil {
cancel()
<-runDone
}
s.handlerWG.Wait()
err := errors.Join(s.server.Close(), s.store.Close())
s.mu.Lock()
s.closeErr = err
close(s.closeDone)
s.mu.Unlock()
return err
}