detached 388d3be

api.go RawHistoryFolder

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", "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"}
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	Auth   ports.AuthService
51	Repos  ports.RepoService
52	Tokens ports.TokenService
53	Browse ports.BrowseService
54	Events ports.EventService
55	// MergeRequests serves MergeRequestService, SigningKey GetSigningKey.
56	MergeRequests ports.MergeRequestService
57	SigningKey    ports.SigningKeyService
58	// Issues serves IssueService.
59	Issues ports.IssueService
60	// IssueModeration serves the moderation calls of IssueService.
61	IssueModeration ports.IssueModerationService
62	Version         string
63	// TrustedProxies are the networks allowed to set X-Forwarded-For.
64	TrustedProxies []netip.Prefix
65	// Limiter counts failed authentications; nil builds a default one. Share
66	// it with the other adapters that authenticate, so that a client has one
67	// budget of failures. Leave it unset rather than assigning a typed nil
68	// pointer (a nil *T in the interface is not nil, and would be called).
69	Limiter ports.FailureLimiter
70	// Runner serves RunnerService and Runs serves RunService; without them the
71	// CI services are not served. Leave them unset rather than assigning a
72	// typed nil pointer.
73	Runner ports.RunnerService
74	Runs   ports.RunService
75	// Sessions are the owner's web sessions; nil serves no SessionService.
76	// Leave it unset rather than assigning a typed nil pointer (a nil *T in
77	// the interface is not nil, and the service would be served and called).
78	Sessions ports.SessionService
79	// Passkeys serves ListPasskeys and RemovePasskey; nil means passkeys are
80	// not available (the RPCs answer failed_precondition and GetVersion does
81	// not list "passkeys"). Same rule as Sessions about typed nil pointers.
82	Passkeys ports.PasskeyService
83	// Secrets, Variables and Environments serve SecretService, VariableService
84	// and EnvironmentService, and GetVersion lists "ci.secrets", when all three
85	// are set (they are one use case). Same rule as Sessions about typed nil
86	// pointers.
87	Secrets      ports.SecretService
88	Variables    ports.VariableService
89	Environments ports.EnvironmentService
90	// OIDCKeys rotates the key of the ID tokens of CI jobs; nil when the server
91	// issues none (GetVersion then does not list "ci.oidc"). Same rule as
92	// Sessions about typed nil pointers.
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.Passkeys != nil {
131		features = append(features, FeaturePasskeys)
132	}
133	settings := cfg.Secrets != nil && cfg.Variables != nil && cfg.Environments != nil
134	if settings {
135		features = append(features, FeatureCISecrets)
136	}
137	artifacts := cfg.JobArtifacts != nil && cfg.Artifacts != nil && cfg.Runner != nil
138	if artifacts {
139		features = append(features, FeatureCIArtifacts)
140	}
141	if cfg.OIDCKeys != nil {
142		features = append(features, FeatureCIOIDC)
143	}
144	if cfg.TrustedKeys != nil {
145		features = append(features, FeatureCommitSignatures)
146	}
147	mux.Handle(ermiteconnect.NewServerServiceHandler(&serverService{version: cfg.Version, features: features, key: cfg.SigningKey, oidc: cfg.OIDCKeys}, opts...))
148	mux.Handle(ermiteconnect.NewMergeRequestServiceHandler(&mergeRequestService{mrs: cfg.MergeRequests}, opts...))
149	mux.Handle(ermiteconnect.NewIssueServiceHandler(&issueService{issues: cfg.Issues, moderation: cfg.IssueModeration}, opts...))
150	if cfg.Sessions != nil {
151		mux.Handle(ermiteconnect.NewSessionServiceHandler(&sessionService{sessions: cfg.Sessions, passkeys: cfg.Passkeys}, opts...))
152	}
153	if cfg.TrustedKeys != nil {
154		mux.Handle(ermiteconnect.NewTrustedKeyServiceHandler(&trustedKeyService{cfg.TrustedKeys}, opts...))
155	}
156	if settings {
157		mux.Handle(ermiteconnect.NewSecretServiceHandler(&secretService{cfg.Secrets}, opts...))
158		mux.Handle(ermiteconnect.NewVariableServiceHandler(&variableService{cfg.Variables}, opts...))
159		mux.Handle(ermiteconnect.NewEnvironmentServiceHandler(&environmentService{cfg.Environments}, opts...))
160	}
161	if cfg.Runner != nil {
162		runnerOpts := append(slices.Clone(opts), connect.WithReadMaxBytes(RunnerMaxRequestBytes))
163		runners := &runnerService{runners: cfg.Runner, limiter: cfg.Limiter}
164		mux.Handle(ermiteconnect.NewRunnerServiceHandler(runners, runnerOpts...))
165		if artifacts {
166			// A block message carries up to 1 MiB of data, like a summary.
167			mux.Handle(ermiteconnect.NewJobArtifactServiceHandler(&jobArtifactService{artifacts: cfg.JobArtifacts, runner: runners}, runnerOpts...))
168			mux.Handle(ermiteconnect.NewArtifactServiceHandler(&artifactService{artifacts: cfg.Artifacts}, opts...))
169		}
170	}
171	if cfg.Runs != nil {
172		mux.Handle(ermiteconnect.NewRunServiceHandler(&runService{runs: cfg.Runs}, opts...))
173	}
174	return &API{handler: mux}
175}
176
177// Handler returns the handler of all services. Its paths are the procedure
178// paths of the contract ("/ermite.RepoService/ListRepos"); httpserver mounts
179// it under /-/api/ and strips the prefix.
180func (a *API) Handler() http.Handler { return a.handler }
181
182// caller returns the principal the interceptor put in ctx; anonymous when
183// there is none.
184func caller(ctx context.Context) domain.Principal {
185	p, _ := domain.PrincipalFromContext(ctx)
186	return p
187}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 4

Tags 45

↑↓ moveenter openesc close