detached 973e682

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", "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"}
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 manages ID-token signing keys, including when OIDC is disabled.
91	OIDCKeys ports.OIDCKeyService
92	// JobArtifacts and Artifacts serve JobArtifactService and ArtifactService,
93	// and GetVersion lists "ci.artifacts", when both are set and Runner is.
94	// Same rule as Sessions about typed nil pointers.
95	JobArtifacts ports.JobArtifactService
96	Artifacts    ports.ArtifactService
97	// TrustedKeys serves TrustedKeyService, and GetVersion lists
98	// "commit_signatures", when set (ADR 0030). Same rule as Sessions about
99	// typed nil pointers.
100	TrustedKeys ports.TrustedKeyService
101}
102
103// API is the set of Connect handlers of the contract.
104type API struct {
105	handler http.Handler
106}
107
108// New builds the API.
109func New(cfg Config) *API {
110	if cfg.Limiter == nil {
111		cfg.Limiter = clientlimit.NewLimiter(nil)
112	}
113	opts := []connect.HandlerOption{
114		connect.WithInterceptors(newInterceptor(cfg)),
115		connect.WithReadMaxBytes(MaxRequestBytes),
116		connect.WithRecover(func(ctx context.Context, spec connect.Spec, _ http.Header, panicValue any) error {
117			log := zerowrap.FromCtx(ctx)
118			log.Error().Interface("panic", panicValue).Str("procedure", spec.Procedure).Msg("api handler panicked")
119			return connect.NewError(connect.CodeInternal, errInternal)
120		}),
121	}
122	mux := http.NewServeMux()
123	mux.Handle(ermiteconnect.NewRepoServiceHandler(&repoService{cfg.Repos}, opts...))
124	mux.Handle(ermiteconnect.NewGitServiceHandler(&gitService{cfg.Browse}, opts...))
125	mux.Handle(ermiteconnect.NewTokenServiceHandler(&tokenService{cfg.Tokens}, opts...))
126	mux.Handle(ermiteconnect.NewEventServiceHandler(&eventService{cfg.Events}, opts...))
127	features := slices.Clone(Features)
128	if cfg.Passkeys != nil {
129		features = append(features, FeaturePasskeys)
130	}
131	settings := cfg.Secrets != nil && cfg.Variables != nil && cfg.Environments != nil
132	if settings {
133		features = append(features, FeatureCISecrets)
134	}
135	artifacts := cfg.JobArtifacts != nil && cfg.Artifacts != nil && cfg.Runner != nil
136	if artifacts {
137		features = append(features, FeatureCIArtifacts)
138	}
139	if cfg.OIDCKeys != nil && cfg.OIDCKeys.Enabled() {
140		features = append(features, FeatureCIOIDC)
141	}
142	if cfg.TrustedKeys != nil {
143		features = append(features, FeatureCommitSignatures)
144	}
145	mux.Handle(ermiteconnect.NewServerServiceHandler(&serverService{version: cfg.Version, features: features, key: cfg.SigningKey, oidc: cfg.OIDCKeys}, opts...))
146	mux.Handle(ermiteconnect.NewMergeRequestServiceHandler(&mergeRequestService{mrs: cfg.MergeRequests}, opts...))
147	mux.Handle(ermiteconnect.NewIssueServiceHandler(&issueService{issues: cfg.Issues, moderation: cfg.IssueModeration}, opts...))
148	if cfg.Sessions != nil {
149		mux.Handle(ermiteconnect.NewSessionServiceHandler(&sessionService{sessions: cfg.Sessions, passkeys: cfg.Passkeys}, opts...))
150	}
151	if cfg.TrustedKeys != nil {
152		mux.Handle(ermiteconnect.NewTrustedKeyServiceHandler(&trustedKeyService{cfg.TrustedKeys}, opts...))
153	}
154	if settings {
155		mux.Handle(ermiteconnect.NewSecretServiceHandler(&secretService{cfg.Secrets}, opts...))
156		mux.Handle(ermiteconnect.NewVariableServiceHandler(&variableService{cfg.Variables}, opts...))
157		mux.Handle(ermiteconnect.NewEnvironmentServiceHandler(&environmentService{cfg.Environments}, opts...))
158	}
159	if cfg.Runner != nil {
160		runnerOpts := append(slices.Clone(opts), connect.WithReadMaxBytes(RunnerMaxRequestBytes))
161		runners := &runnerService{runners: cfg.Runner, limiter: cfg.Limiter}
162		mux.Handle(ermiteconnect.NewRunnerServiceHandler(runners, runnerOpts...))
163		if artifacts {
164			// A block message carries up to 1 MiB of data, like a summary.
165			mux.Handle(ermiteconnect.NewJobArtifactServiceHandler(&jobArtifactService{artifacts: cfg.JobArtifacts, runner: runners}, runnerOpts...))
166			mux.Handle(ermiteconnect.NewArtifactServiceHandler(&artifactService{artifacts: cfg.Artifacts}, opts...))
167		}
168	}
169	if cfg.Runs != nil {
170		mux.Handle(ermiteconnect.NewRunServiceHandler(&runService{runs: cfg.Runs}, opts...))
171	}
172	return &API{handler: mux}
173}
174
175// Handler returns the handler of all services. Its paths are the procedure
176// paths of the contract ("/ermite.RepoService/ListRepos"); httpserver mounts
177// it under /-/api/ and strips the prefix.
178func (a *API) Handler() http.Handler { return a.handler }
179
180// caller returns the principal the interceptor put in ctx; anonymous when
181// there is none.
182func caller(ctx context.Context) domain.Principal {
183	p, _ := domain.PrincipalFromContext(ctx)
184	return p
185}

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