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// and JobArtifactService: a job summary of exactly 1 MiB (UploadSummary) and a
30// block message with 1 MiB of data must be accepted, so the limit leaves room
31// for the envelope (job id, step number, block id, framing).
32const RunnerMaxRequestBytes = MaxRequestBytes + 64<<10
33
34// Features are the optional capabilities of the contract that this server
35// always implements, as GetVersion lists them. FeaturePasskeys comes on top
36// when Config.Passkeys is set, and FeatureCISecrets when the settings services
37// are, and FeatureCommitSignatures when Config.TrustedKeys is set.
38var Features = []string{"repo.update", "events.resume", "merge_requests", "merge_requests.delete_branch", "issues", "issues.links", "merge_requests.mergeability", "signing_key", "session", "git.list_paths", "token.branch_prefixes", "ci.runs", "ci.runs.filters", "ci.runners", "ci.actions", "ci.annotations", "ci.summaries", "ci.concurrency", "ci.dispatch", "ci.cache", "ci.workflows", "merge_requests.auto_merge"}
39
40// FeaturePasskeys is listed by GetVersion when passkeys are available.
41// FeatureCIArtifacts (artifact.go) when the artifact services are served.
42const FeaturePasskeys = "passkeys"
43
44// FeatureCIOIDC is listed by GetVersion when the server issues OIDC ID tokens
45// to CI jobs (Job.id_token_url, ServerService.RotateOIDCKey).
46const FeatureCIOIDC = "ci.oidc"
47
48// Config configures the API.
49type Config struct {
50 // Mirrors serves MirrorService when set; leave unset rather than a typed nil.
51 Mirrors ports.MirrorService
52 Auth ports.AuthService
53 Repos ports.RepoService
54 Tokens ports.TokenService
55 Browse ports.BrowseService
56 Events ports.EventService
57 // MergeRequests serves MergeRequestService, SigningKey GetSigningKey.
58 MergeRequests ports.MergeRequestService
59 SigningKey ports.SigningKeyService
60 // Issues serves IssueService.
61 Issues ports.IssueService
62 // IssueModeration serves the moderation calls of IssueService.
63 IssueModeration ports.IssueModerationService
64 Version string
65 // TrustedProxies are the networks allowed to set X-Forwarded-For.
66 TrustedProxies []netip.Prefix
67 // Limiter counts failed authentications; nil builds a default one. Share
68 // it with the other adapters that authenticate, so that a client has one
69 // budget of failures. Leave it unset rather than assigning a typed nil
70 // pointer (a nil *T in the interface is not nil, and would be called).
71 Limiter ports.FailureLimiter
72 // Runner serves RunnerService and Runs serves RunService; without them the
73 // CI services are not served. Leave them unset rather than assigning a
74 // typed nil pointer.
75 Runner ports.RunnerService
76 Runs ports.RunService
77 // Sessions are the owner's web sessions; nil serves no SessionService.
78 // Leave it unset rather than assigning a typed nil pointer (a nil *T in
79 // the interface is not nil, and the service would be served and called).
80 Sessions ports.SessionService
81 // Passkeys serves ListPasskeys and RemovePasskey; nil means passkeys are
82 // not available (the RPCs answer failed_precondition and GetVersion does
83 // not list "passkeys"). Same rule as Sessions about typed nil pointers.
84 Passkeys ports.PasskeyService
85 // Secrets, Variables and Environments serve SecretService, VariableService
86 // and EnvironmentService, and GetVersion lists "ci.secrets", when all three
87 // are set (they are one use case). Same rule as Sessions about typed nil
88 // pointers.
89 Secrets ports.SecretService
90 Variables ports.VariableService
91 Environments ports.EnvironmentService
92 // OIDCKeys manages ID-token signing keys, including when OIDC is disabled.
93 OIDCKeys ports.OIDCKeyService
94 // JobArtifacts and Artifacts serve JobArtifactService and ArtifactService,
95 // and GetVersion lists "ci.artifacts", when both are set and Runner is.
96 // Same rule as Sessions about typed nil pointers.
97 JobArtifacts ports.JobArtifactService
98 Artifacts ports.ArtifactService
99 // TrustedKeys serves TrustedKeyService, and GetVersion lists
100 // "commit_signatures", when set (ADR 0030). Same rule as Sessions about
101 // typed nil pointers.
102 TrustedKeys ports.TrustedKeyService
103}
104
105// API is the set of Connect handlers of the contract.
106type API struct {
107 handler http.Handler
108}
109
110// New builds the API.
111func New(cfg Config) *API {
112 if cfg.Limiter == nil {
113 cfg.Limiter = clientlimit.NewLimiter(nil)
114 }
115 opts := []connect.HandlerOption{
116 connect.WithInterceptors(newInterceptor(cfg)),
117 connect.WithReadMaxBytes(MaxRequestBytes),
118 connect.WithRecover(func(ctx context.Context, spec connect.Spec, _ http.Header, panicValue any) error {
119 log := zerowrap.FromCtx(ctx)
120 log.Error().Interface("panic", panicValue).Str("procedure", spec.Procedure).Msg("api handler panicked")
121 return connect.NewError(connect.CodeInternal, errInternal)
122 }),
123 }
124 mux := http.NewServeMux()
125 mux.Handle(ermiteconnect.NewRepoServiceHandler(&repoService{cfg.Repos}, opts...))
126 mux.Handle(ermiteconnect.NewGitServiceHandler(&gitService{cfg.Browse}, opts...))
127 mux.Handle(ermiteconnect.NewTokenServiceHandler(&tokenService{cfg.Tokens}, opts...))
128 mux.Handle(ermiteconnect.NewEventServiceHandler(&eventService{cfg.Events}, opts...))
129 features := slices.Clone(Features)
130 if cfg.Mirrors != nil {
131 mux.Handle(ermiteconnect.NewMirrorServiceHandler(&mirrorService{cfg.Mirrors}, opts...))
132 features = append(features, FeatureMirror)
133 }
134 if cfg.Passkeys != nil {
135 features = append(features, FeaturePasskeys)
136 }
137 settings := cfg.Secrets != nil && cfg.Variables != nil && cfg.Environments != nil
138 if settings {
139 features = append(features, FeatureCISecrets)
140 }
141 artifacts := cfg.JobArtifacts != nil && cfg.Artifacts != nil && cfg.Runner != nil
142 if artifacts {
143 features = append(features, FeatureCIArtifacts)
144 }
145 if cfg.OIDCKeys != nil && cfg.OIDCKeys.Enabled() {
146 features = append(features, FeatureCIOIDC)
147 }
148 if cfg.TrustedKeys != nil {
149 features = append(features, FeatureCommitSignatures)
150 }
151 mux.Handle(ermiteconnect.NewServerServiceHandler(&serverService{version: cfg.Version, features: features, key: cfg.SigningKey, oidc: cfg.OIDCKeys}, opts...))
152 mux.Handle(ermiteconnect.NewMergeRequestServiceHandler(&mergeRequestService{mrs: cfg.MergeRequests}, opts...))
153 mux.Handle(ermiteconnect.NewIssueServiceHandler(&issueService{issues: cfg.Issues, moderation: cfg.IssueModeration}, opts...))
154 if cfg.Sessions != nil {
155 mux.Handle(ermiteconnect.NewSessionServiceHandler(&sessionService{sessions: cfg.Sessions, passkeys: cfg.Passkeys}, opts...))
156 }
157 if cfg.TrustedKeys != nil {
158 mux.Handle(ermiteconnect.NewTrustedKeyServiceHandler(&trustedKeyService{cfg.TrustedKeys}, opts...))
159 }
160 if settings {
161 mux.Handle(ermiteconnect.NewSecretServiceHandler(&secretService{cfg.Secrets}, opts...))
162 mux.Handle(ermiteconnect.NewVariableServiceHandler(&variableService{cfg.Variables}, opts...))
163 mux.Handle(ermiteconnect.NewEnvironmentServiceHandler(&environmentService{cfg.Environments}, opts...))
164 }
165 if cfg.Runner != nil {
166 runnerOpts := append(slices.Clone(opts), connect.WithReadMaxBytes(RunnerMaxRequestBytes))
167 runners := &runnerService{runners: cfg.Runner, limiter: cfg.Limiter}
168 mux.Handle(ermiteconnect.NewRunnerServiceHandler(runners, runnerOpts...))
169 if artifacts {
170 // A block message carries up to 1 MiB of data, like a summary.
171 mux.Handle(ermiteconnect.NewJobArtifactServiceHandler(&jobArtifactService{artifacts: cfg.JobArtifacts, runner: runners}, runnerOpts...))
172 mux.Handle(ermiteconnect.NewArtifactServiceHandler(&artifactService{artifacts: cfg.Artifacts}, opts...))
173 }
174 }
175 if cfg.Runs != nil {
176 mux.Handle(ermiteconnect.NewRunServiceHandler(&runService{runs: cfg.Runs}, opts...))
177 }
178 return &API{handler: mux}
179}
180
181// Handler returns the handler of all services. Its paths are the procedure
182// paths of the contract ("/ermite.RepoService/ListRepos"); httpserver mounts
183// it under /-/api/ and strips the prefix.
184func (a *API) Handler() http.Handler { return a.handler }
185
186// caller returns the principal the interceptor put in ctx; anonymous when
187// there is none.
188func caller(ctx context.Context) domain.Principal {
189 p, _ := domain.PrincipalFromContext(ctx)
190 return p
191}