1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3// Package rpc serves the ermite API contract (bnema.dev/ermite-api) with
4// ConnectRPC: handlers that map the messages of the contract to the use cases
5// of usecase and back, the interceptor that authenticates callers, and the error
6// mapping.
7package rpc
8
9import (
10 "context"
11 "net/http"
12 "net/netip"
13 "slices"
14
15 "connectrpc.com/connect"
16 "github.com/bnema/zerowrap"
17
18 "bnema.dev/ermite-api/gen/ermite/ermiteconnect"
19 "bnema.dev/ermite/internal/clientlimit"
20 "bnema.dev/ermite/internal/domain"
21 "bnema.dev/ermite/internal/ports"
22)
23
24// MaxRequestBytes bounds the size of a request message. Responses are not
25// bounded: a diff has its own limits and blobs are streamed.
26const MaxRequestBytes = 1 << 20
27
28// RunnerMaxRequestBytes bounds the size of a request message of RunnerService:
29// a job summary of exactly 1 MiB (UploadSummary) must be accepted, so the limit
30// leaves room for the envelope (job id, step number, framing).
31const RunnerMaxRequestBytes = MaxRequestBytes + 64<<10
32
33// Features are the optional capabilities of the contract that this server
34// always implements, as GetVersion lists them. FeaturePasskeys comes on top
35// when Config.Passkeys is set.
36var Features = []string{"repo.update", "events.resume", "merge_requests", "merge_requests.delete_branch", "signing_key", "session", "git.list_paths", "token.branch_prefixes", "ci.runs", "ci.runs.filters", "ci.runners", "ci.actions", "ci.annotations", "ci.summaries"}
37
38// FeaturePasskeys is listed by GetVersion when passkeys are available.
39const FeaturePasskeys = "passkeys"
40
41// Config configures the API.
42type Config struct {
43 Auth ports.AuthService
44 Repos ports.RepoService
45 Tokens ports.TokenService
46 Browse ports.BrowseService
47 Events ports.EventService
48 // MergeRequests serves MergeRequestService, SigningKey GetSigningKey.
49 MergeRequests ports.MergeRequestService
50 SigningKey ports.SigningKeyService
51 Version string
52 // TrustedProxies are the networks allowed to set X-Forwarded-For.
53 TrustedProxies []netip.Prefix
54 // Limiter counts failed authentications; nil builds a default one. Share
55 // it with the other adapters that authenticate, so that a client has one
56 // budget of failures. Leave it unset rather than assigning a typed nil
57 // pointer (a nil *T in the interface is not nil, and would be called).
58 Limiter ports.FailureLimiter
59 // Runner serves RunnerService and Runs serves RunService; without them the
60 // CI services are not served. Leave them unset rather than assigning a
61 // typed nil pointer.
62 Runner ports.RunnerService
63 Runs ports.RunService
64 // Sessions are the owner's web sessions; nil serves no SessionService.
65 // Leave it unset rather than assigning a typed nil pointer (a nil *T in
66 // the interface is not nil, and the service would be served and called).
67 Sessions ports.SessionService
68 // Passkeys serves ListPasskeys and RemovePasskey; nil means passkeys are
69 // not available (the RPCs answer failed_precondition and GetVersion does
70 // not list "passkeys"). Same rule as Sessions about typed nil pointers.
71 Passkeys ports.PasskeyService
72}
73
74// API is the set of Connect handlers of the contract.
75type API struct {
76 handler http.Handler
77}
78
79// New builds the API.
80func New(cfg Config) *API {
81 if cfg.Limiter == nil {
82 cfg.Limiter = clientlimit.NewLimiter(nil)
83 }
84 opts := []connect.HandlerOption{
85 connect.WithInterceptors(newInterceptor(cfg)),
86 connect.WithReadMaxBytes(MaxRequestBytes),
87 connect.WithRecover(func(ctx context.Context, spec connect.Spec, _ http.Header, panicValue any) error {
88 log := zerowrap.FromCtx(ctx)
89 log.Error().Interface("panic", panicValue).Str("procedure", spec.Procedure).Msg("api handler panicked")
90 return connect.NewError(connect.CodeInternal, errInternal)
91 }),
92 }
93 mux := http.NewServeMux()
94 mux.Handle(ermiteconnect.NewRepoServiceHandler(&repoService{cfg.Repos}, opts...))
95 mux.Handle(ermiteconnect.NewGitServiceHandler(&gitService{cfg.Browse}, opts...))
96 mux.Handle(ermiteconnect.NewTokenServiceHandler(&tokenService{cfg.Tokens}, opts...))
97 mux.Handle(ermiteconnect.NewEventServiceHandler(&eventService{cfg.Events}, opts...))
98 features := slices.Clone(Features)
99 if cfg.Passkeys != nil {
100 features = append(features, FeaturePasskeys)
101 }
102 mux.Handle(ermiteconnect.NewServerServiceHandler(&serverService{version: cfg.Version, features: features, key: cfg.SigningKey}, opts...))
103 mux.Handle(ermiteconnect.NewMergeRequestServiceHandler(&mergeRequestService{cfg.MergeRequests}, opts...))
104 if cfg.Sessions != nil {
105 mux.Handle(ermiteconnect.NewSessionServiceHandler(&sessionService{sessions: cfg.Sessions, passkeys: cfg.Passkeys}, opts...))
106 }
107 if cfg.Runner != nil {
108 runnerOpts := append(slices.Clone(opts), connect.WithReadMaxBytes(RunnerMaxRequestBytes))
109 mux.Handle(ermiteconnect.NewRunnerServiceHandler(&runnerService{runners: cfg.Runner, limiter: cfg.Limiter}, runnerOpts...))
110 }
111 if cfg.Runs != nil {
112 mux.Handle(ermiteconnect.NewRunServiceHandler(&runService{cfg.Runs}, opts...))
113 }
114 return &API{handler: mux}
115}
116
117// Handler returns the handler of all services. Its paths are the procedure
118// paths of the contract ("/ermite.RepoService/ListRepos"); httpserver mounts
119// it under /-/api/ and strips the prefix.
120func (a *API) Handler() http.Handler { return a.handler }
121
122// caller returns the principal the interceptor put in ctx; anonymous when
123// there is none.
124func caller(ctx context.Context) domain.Principal {
125 p, _ := domain.PrincipalFromContext(ctx)
126 return p
127}