detached aa7340c

forge.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package app
4
5import (
6	"context"
7	"crypto/ed25519"
8	"crypto/rand"
9	"crypto/rsa"
10	"errors"
11	"fmt"
12	"net"
13	"os"
14	"path/filepath"
15	"strings"
16	"time"
17
18	"github.com/bnema/zerowrap"
19
20	"bnema.dev/ermite/internal/adapters/ciartifacts"
21	"bnema.dev/ermite/internal/adapters/cilogs"
22	"bnema.dev/ermite/internal/adapters/cisummaries"
23	"bnema.dev/ermite/internal/adapters/ermitegit"
24	"bnema.dev/ermite/internal/adapters/eventbus"
25	"bnema.dev/ermite/internal/adapters/gitcli"
26	"bnema.dev/ermite/internal/adapters/githttp"
27	"bnema.dev/ermite/internal/adapters/githubapi"
28	"bnema.dev/ermite/internal/adapters/githubraw"
29	"bnema.dev/ermite/internal/adapters/gitremote"
30	"bnema.dev/ermite/internal/adapters/httpserver"
31	"bnema.dev/ermite/internal/adapters/kvstore"
32	"bnema.dev/ermite/internal/adapters/oidchttp"
33	"bnema.dev/ermite/internal/adapters/rpc"
34	"bnema.dev/ermite/internal/adapters/secretbox"
35	"bnema.dev/ermite/internal/adapters/sigverify"
36	"bnema.dev/ermite/internal/adapters/sshsig"
37	"bnema.dev/ermite/internal/adapters/web"
38	"bnema.dev/ermite/internal/adapters/webauthn"
39	"bnema.dev/ermite/internal/clientlimit"
40	"bnema.dev/ermite/internal/config"
41	"bnema.dev/ermite/internal/domain"
42	"bnema.dev/ermite/internal/ports"
43	"bnema.dev/ermite/internal/usecase"
44)
45
46// maxReceiveBytes bounds the body of a push, both at the HTTP handler and in
47// Git (receive.maxInputSize).
48const maxReceiveBytes = githttp.DefaultMaxBodyBytes
49
50// options are the parts of the wiring that tests replace.
51type options struct {
52	// hookExe is the executable the hook scripts exec; empty means this
53	// process's own executable.
54	hookExe string
55	// maintenanceDelay overrides usecase.MaintenanceDelay when positive.
56	maintenanceDelay time.Duration
57	// maxBodyBytes overrides the limit of a push body when positive.
58	maxBodyBytes int64
59	// eventBuffer overrides usecase.DefaultEventBuffer when positive.
60	eventBuffer int
61	// revalidateEvery overrides usecase.DefaultRevalidateEvery when not zero.
62	revalidateEvery time.Duration
63	// archivesPerClient overrides the archives one client downloads at once
64	// when positive.
65	archivesPerClient int
66	// receivePacks overrides the git-receive-pack backends running at once
67	// when positive (the default follows GOMAXPROCS).
68	receivePacks int
69	// remote replaces the lister of github.com refs (tests never reach the
70	// network).
71	remoteLister ports.GitRemote
72	// workflowFetcher replaces the downloader of github.com reusable workflows
73	// (tests never reach the network).
74	workflowFetcher ports.WorkflowFetcher
75	// ci overrides the settings of the CI engine (tests shorten its
76	// durations).
77	ci func(*usecase.CIConfig)
78	// oidcKey generates the signing keys of the ID tokens; nil generates RSA
79	// keys (tests give prepared ones: a 3072-bit key takes a while).
80	oidcKey func() (*rsa.PrivateKey, error)
81	// issuePoW lowers the proof of work of the public issue form (the base
82	// and the highest difficulty, in bits) when positive, and shortens the
83	// minimum fill time to a nanosecond; tests only.
84	issuePoW int
85}
86
87// remote returns the lister of github.com refs: the test's, else def.
88func (o options) remote(def ports.GitRemote) ports.GitRemote {
89	if o.remoteLister != nil {
90		return o.remoteLister
91	}
92	return def
93}
94
95// workflows returns the downloader of github.com reusable workflows: the
96// test's, else def.
97func (o options) workflows(def ports.WorkflowFetcher) ports.WorkflowFetcher {
98	if o.workflowFetcher != nil {
99		return o.workflowFetcher
100	}
101	return def
102}
103
104// forge is the wired server: every adapter and use case, ready to serve.
105type forge struct {
106	cfg    config.Config
107	store  *kvstore.Store
108	server *httpserver.Server
109	hooks  *githttp.HookServer
110	maint  *usecase.Maintainer
111	git    *gitcli.Git
112	// reader is the ermite-git reader when ERMITE_GIT_READER selects it.
113	reader *ermitegit.Adapter
114
115	// The use cases and the API are exposed for tests and for the phases
116	// that add the web.
117	Repos  *usecase.Repos
118	Tokens *usecase.Tokens
119	Auth   *usecase.Auth
120	Pushes *usecase.Pushes
121	Browse *usecase.Browse
122	// MergeRequests and SigningKey serve MergeRequestService and
123	// ServerService.GetSigningKey.
124	MergeRequests *usecase.MergeRequests
125	// Issues serves IssueService, and tells what a number names.
126	Issues *usecase.Issues
127	// IssueModeration serves the moderation calls of IssueService.
128	IssueModeration *usecase.IssueModeration
129	// IssueKeys are the subkeys of the public issue form, and the stores and
130	// the limiter its submissions use (the form itself comes later).
131	IssueKeys *usecase.IssueKeys
132	// IssueSubmissions serves the anonymous submission of issues.
133	IssueSubmissions  *usecase.IssueSubmissions
134	SubmissionLimiter *clientlimit.SubmissionLimiter
135	PendingIssues     ports.PendingIssueStore
136	IssueBans         ports.IssueBanStore
137	// Inbox serves the owner's inbox of the web.
138	Inbox      *usecase.Inbox
139	SigningKey *usecase.SigningKey
140	// Mergeability keeps the mergeability of the open merge requests up to date.
141	Mergeability *usecase.Mergeability
142	// Signatures are the trusted keys and the commit signature checks
143	// (ADR 0030).
144	Signatures *usecase.Signatures
145	Sessions   *usecase.Sessions
146	// Passkeys is nil when passkeys are not available (passkeysAvailable).
147	Passkeys *usecase.Passkeys
148	EventLog *usecase.Events
149	// CI is the CI engine: workflow trigger, planner, runner protocol and the
150	// owner side. It starts with the server and stops with it.
151	CI *usecase.CI
152	// Settings are the secrets, variables and environments of CI.
153	Settings *usecase.CISettings
154	// OIDC is the provider of the ID tokens of CI jobs; nil without a secrets
155	// key.
156	OIDC *usecase.OIDC
157	API  *rpc.API
158	Bus  ports.EventBus
159}
160
161// newSigningSeed makes the seed of a new ed25519 signing key.
162func newSigningSeed() ([]byte, error) {
163	seed := make([]byte, ed25519.SeedSize)
164	if _, err := rand.Read(seed); err != nil {
165		return nil, err
166	}
167	return seed, nil
168}
169
170// serverVersion is the version GetVersion reports: the module version of the
171// build, or "devel" for an untagged one.
172func serverVersion() string {
173	if v := buildVersion(); v != "(devel)" {
174		return v
175	}
176	return "devel"
177}
178
179// newForge opens the metadata store, resets run/, checks git, reconciles the repositories,
180// writes the hook scripts, opens the hook socket and builds the HTTP server.
181// The data directory must be prepared (prepareDataDir). Close it after the
182// server stopped.
183func newForge(ctx context.Context, cfg config.Config, opts options) (_ *forge, err error) {
184	log := zerowrap.FromCtx(ctx)
185	store, err := kvstore.Open(ctx, filepath.Join(cfg.DataDir, "kv"))
186	if err != nil {
187		return nil, err
188	}
189	f := &forge{cfg: cfg, store: store}
190	defer func() {
191		if err != nil {
192			f.Close(context.WithoutCancel(ctx))
193		}
194	}()
195	// The kv store holds the directory lock: only now is run/ ours to reset.
196	// The hook scripts and the socket are written into it afterwards.
197	if err := resetRunDir(cfg.DataDir); err != nil {
198		return nil, err
199	}
200
201	path := os.Getenv("PATH")
202	if path == "" {
203		path = "/usr/local/bin:/usr/bin:/bin"
204	}
205	maxBody := maxReceiveBytes
206	if opts.maxBodyBytes > 0 {
207		maxBody = opts.maxBodyBytes
208	}
209	git := gitcli.New(gitcli.Config{Bin: cfg.Git, DataDir: cfg.DataDir, Path: path, MaxReceiveBytes: maxBody})
210	f.git = git
211	gitVersion, err := git.CheckVersion(ctx)
212	if err != nil {
213		return nil, fmt.Errorf("%s=%q: %w", config.EnvGit, cfg.Git, err)
214	}
215	log.Info().Str("git", gitVersion.String()).Msg("git checked")
216	if _, err := git.HTTPBackend(ctx, false); err != nil {
217		return nil, fmt.Errorf("%s=%q: %w", config.EnvGit, cfg.Git, err)
218	}
219
220	clock := systemClock{}
221	f.Bus = eventbus.New()
222	f.Repos = usecase.NewRepos(store, git, f.Bus, clock)
223	report, err := f.Repos.Reconcile(ctx)
224	if err != nil {
225		return nil, fmt.Errorf("reconcile repositories: %w", err)
226	}
227	log.Info().
228		Int("registered", len(report.Registered)).
229		Int("missing_dirs", len(report.MissingDirs)).
230		Int("invalid_dirs", len(report.InvalidDirs)).
231		Msg("repositories reconciled")
232
233	f.Tokens = usecase.NewTokens(store.Tokens(), clock, store.Sessions())
234	f.Auth = usecase.NewAuth(cfg.AdminTokenHash, store.Tokens(), clock).WithRepoTokens(store.CI())
235	f.maint = usecase.NewMaintainer(ctx, git, opts.maintenanceDelay)
236	f.Pushes = usecase.NewPushes(store, f.Repos, git, f.Bus, clock, f.maint, f.Auth)
237
238	exe := opts.hookExe
239	if exe == "" {
240		if exe, err = os.Executable(); err != nil {
241			return nil, fmt.Errorf("find the ermite executable for the hooks: %w", err)
242		}
243	}
244	if err := githttp.WriteHookScripts(gitcli.HooksDir(cfg.DataDir), exe); err != nil {
245		return nil, err
246	}
247	f.hooks = githttp.NewHookServer(filepath.Join(cfg.DataDir, "run", "hook.sock"), f.Pushes)
248	if err := f.hooks.Listen(ctx); err != nil {
249		return nil, err
250	}
251
252	var reader ports.RepoReader = git
253	if cfg.GitReader == config.GitReaderErmiteGit {
254		f.reader = ermitegit.New(ermitegit.Config{
255			Fallback: git,
256			RepoDir:  func(name domain.RepoName) string { return gitcli.RepoDir(cfg.DataDir, name) },
257		})
258		git.OnTrash(f.reader.Forget)
259		f.maint.WithFreshener(f.reader)
260		f.Pushes.WithFreshener(f.reader)
261		reader = f.reader
262	}
263	log.Info().Str("reader", cfg.GitReader).Msg("git reader selected")
264	f.Browse = usecase.NewBrowse(store, reader)
265
266	// Secrets, variables and environments (ADR 0019, CI-3). With a key the
267	// secrets are sealed under it, and the server refuses to start when the
268	// key is not the one they were sealed with; without one they cannot be set
269	// and jobs receive none.
270	var sealer ports.SecretSealer // a nil *secretbox.Box must not become a non-nil interface
271	if cfg.SecretsKey != nil {
272		box, err := secretbox.New(cfg.SecretsKey)
273		if err != nil {
274			return nil, fmt.Errorf("%s: %w", config.EnvSecretsKey, err)
275		}
276		sealer = box
277	}
278	f.Settings, err = usecase.NewCISettings(ctx, store, store.Settings(), sealer, clock)
279	if err != nil {
280		return nil, fmt.Errorf("%s: %w", config.EnvSecretsKey, err)
281	}
282	// The OIDC provider of CI jobs (CI-4): its signing key is sealed with the
283	// secrets key, so there is none without one.
284	f.OIDC, err = usecase.NewOIDC(ctx, usecase.OIDCConfig{
285		Store: store, Sealer: sealer, Tokens: store.CI(), Clock: clock, PublicURL: cfg.PublicURL, NewKey: opts.oidcKey,
286	})
287	if err != nil {
288		return nil, fmt.Errorf("oidc: %w", err)
289	}
290
291	// CI (ADR 0025): the engine reads workflows through the reader, and plans
292	// them in the background; a push only queues its refs.
293	committer := domain.Identity{Name: cfg.CommitterName, Email: cfg.CommitterEmail}
294	ciCfg := usecase.CIConfig{
295		Store: store.CI(), Logs: cilogs.New(cilogs.Dir(cfg.DataDir)), Summaries: cisummaries.New(cisummaries.Dir(cfg.DataDir)), Meta: store, Repos: git, Reader: reader,
296		Git: git, Diff: git, Bus: f.Bus, Clock: clock, Auth: f.Auth,
297		Owner: cfg.Owner, PublicURL: cfg.PublicURL, Retention: cfg.CIRetention,
298		PollTimeout: cfg.CIPollTimeout, Archive: git,
299		Remote: opts.remote(gitremote.New(gitremote.Config{
300			Bin: cfg.Git, Path: path, Home: filepath.Join(cfg.DataDir, "run", "git-home"),
301			Proxy: gitremote.ProxyEnv(os.Getenv),
302		})),
303		Tokens:        store.Tokens(),
304		RefTips:       store.CI(),
305		WorkflowState: store.CI(),
306		Settings:      f.Settings,
307		Workflows:     opts.workflows(githubraw.New(githubraw.Config{})),
308		OIDC:          f.OIDC,
309	}
310	artifacts(&ciCfg, cfg, store)
311	f.pullRequests(&ciCfg, store, git, committer)
312	if opts.ci != nil {
313		opts.ci(&ciCfg)
314	}
315	f.CI = usecase.NewCI(ctx, ciCfg)
316	f.Pushes.WithWorkflowTrigger(f.CI).WithWorkflowGuard(git).WithRefTips(store.CI())
317	f.Repos.WithCIRunCleaner(f.CI)
318	f.CI.Start()
319	f.EventLog = usecase.NewEvents(ctx, f.Repos, f.Bus, clock, usecase.EventsConfig{
320		Size: opts.eventBuffer, Auth: f.Auth, RevalidateEvery: opts.revalidateEvery,
321	})
322
323	// The instance signing key (ADR 0022): generated on the first start.
324	seed, err := store.SigningSeed(ctx, newSigningSeed, clock.Now().UTC())
325	if err != nil {
326		return nil, err
327	}
328	signer, err := sshsig.New(seed)
329	if err != nil {
330		return nil, err
331	}
332	f.SigningKey = usecase.NewSigningKey(signer, committer)
333	if err := f.signatures(store, reader, signer.PublicKey(), committer, clock); err != nil {
334		return nil, err
335	}
336	f.Mergeability = usecase.NewMergeability(ctx, usecase.MergeabilityConfig{
337		Store: store.MergeRequests(), Meta: store, Git: git, Bus: f.Bus, Clock: clock,
338	})
339	f.Pushes.WithMergeability(f.Mergeability)
340	f.MergeRequests = usecase.NewMergeRequests(usecase.MergeRequestsConfig{
341		Meta: store, Store: store.MergeRequests(), Repos: git, Git: git, Signer: signer,
342		Committer: committer, Bus: f.Bus, Clock: clock, Maint: f.maint,
343		CI: f.CI, Checks: f.CI, PullRequests: f.CI, RefTips: store.CI(), Mergeability: f.Mergeability,
344	})
345	f.Mergeability.Start()
346	f.MergeRequests.WithVerifier(f.Signatures)
347	f.Issues = usecase.NewIssues(usecase.IssuesConfig{
348		Meta: store, Store: store.Issues(), MergeRequests: store.MergeRequests(), Bus: f.Bus, Clock: clock,
349	})
350	f.IssueModeration = usecase.NewIssueModeration(usecase.IssueModerationConfig{
351		Meta: store, Pending: store.PendingIssues(), Bans: store.IssueBans(), Bus: f.Bus, Clock: clock,
352	})
353	f.SubmissionLimiter = clientlimit.NewSubmissionLimiter(nil)
354	f.PendingIssues, f.IssueBans = store.PendingIssues(), store.IssueBans()
355	f.IssueKeys, err = usecase.NewIssueKeys(ctx, store.IssueKeys())
356	if err != nil {
357		return nil, err
358	}
359	f.IssueSubmissions = usecase.NewIssueSubmissions(usecase.IssueSubmissionsConfig{
360		Meta: store, Pending: f.PendingIssues, Bans: f.IssueBans, Limiter: f.SubmissionLimiter,
361		Keys: f.IssueKeys, Bus: f.Bus, Clock: clock,
362		BaseDifficulty: opts.issuePoW, MaxDifficulty: opts.issuePoW, MinFillTime: fastFill(opts.issuePoW),
363	})
364	f.Inbox = usecase.NewInbox(usecase.InboxConfig{
365		Meta: store, MergeRequests: store.MergeRequests(), Issues: store.Issues(), Pending: store.PendingIssues(),
366	})
367	f.CI.SetPullGate(f.MergeRequests)
368	log.Info().Str("fingerprint", signer.PublicKey().Fingerprint).Msg("commit signing key ready")
369
370	f.Sessions, err = usecase.NewSessions(ctx, store.Sessions(), clock, cfg.PublicURL)
371	if err != nil {
372		return nil, err
373	}
374
375	// Owner passkeys (ADR 0026): built only when the public URL allows them.
376	// When it does, a verifier that cannot be built is fatal.
377	if ok, reason := passkeysAvailable(cfg.PublicURL); ok {
378		verifier, err := webauthn.New(cfg.PublicURL, cfg.Owner)
379		if err != nil {
380			return nil, fmt.Errorf("passkeys: %w", err)
381		}
382		f.Passkeys = usecase.NewPasskeys(store.Passkeys(), verifier, f.Sessions, clock)
383		log.Info().Str("public_url", cfg.PublicURL).Msg("passkeys enabled")
384	} else {
385		log.Info().Str("reason", reason).Msg("passkeys disabled")
386	}
387
388	// One budget of failed authentications per client, for Git, the API and
389	// the web login.
390	limiter := clientlimit.NewLimiter(nil)
391	// A nil *usecase.Passkeys must not become a non-nil interface: the API
392	// tests for nil to answer failed_precondition and to leave the feature out.
393	var apiPasskeys ports.PasskeyService
394	if f.Passkeys != nil {
395		apiPasskeys = f.Passkeys
396	}
397	var apiOIDC ports.OIDCKeyService // same rule as apiPasskeys
398	if f.OIDC != nil {
399		apiOIDC = f.OIDC
400	}
401	var jobArtifacts ports.JobArtifactService
402	var artifacts ports.ArtifactService
403	if cfg.CIArtifacts {
404		jobArtifacts, artifacts = f.CI, f.CI
405	}
406	f.API = rpc.New(rpc.Config{
407		Auth:            f.Auth,
408		Repos:           f.Repos,
409		Tokens:          f.Tokens,
410		Browse:          f.Browse,
411		Events:          f.EventLog,
412		MergeRequests:   f.MergeRequests,
413		Issues:          f.Issues,
414		IssueModeration: f.IssueModeration,
415		SigningKey:      f.SigningKey,
416		TrustedKeys:     f.Signatures,
417		Sessions:        f.Sessions,
418		Passkeys:        apiPasskeys,
419		Runner:          f.CI,
420		Runs:            f.CI,
421		Secrets:         f.Settings,
422		Variables:       f.Settings,
423		Environments:    f.Settings,
424		OIDCKeys:        apiOIDC,
425		JobArtifacts:    jobArtifacts,
426		Artifacts:       artifacts,
427		Version:         serverVersion(),
428		TrustedProxies:  cfg.TrustedProxies,
429		Limiter:         limiter,
430	})
431
432	gh := githttp.New(githttp.Config{
433		Auth:            f.Auth,
434		Repos:           f.Repos,
435		Pushes:          f.Pushes,
436		Backend:         git,
437		Owner:           cfg.Owner,
438		Hooks:           f.hooks,
439		TrustedProxies:  cfg.TrustedProxies,
440		Limiter:         limiter,
441		MaxBodyBytes:    maxBody,
442		MaxReceivePacks: opts.receivePacks,
443	})
444	routes := make([]httpserver.Route, 0, 2*len(githttp.Patterns)+len(githubapi.Patterns)+len(oidchttp.Patterns)+len(web.Patterns))
445	for _, p := range githttp.Patterns {
446		routes = append(routes, httpserver.Route{Pattern: p, Handler: gh})
447	}
448	// The owner form of the clone URL (github.repository), which GitHub's
449	// actions use. config.Owner follows the rules of repository names, so it is
450	// a literal segment that never overlaps /-/.
451	for _, p := range githttp.OwnerPatterns(cfg.Owner) {
452		routes = append(routes, httpserver.Route{Pattern: p, Handler: gh})
453	}
454	// The REST subset the actions call on github.api_url.
455	api := githubapi.New(githubapi.Config{Auth: f.Auth, API: f.CI, TrustedProxies: cfg.TrustedProxies, Limiter: limiter, MaxArchivesPerClient: opts.archivesPerClient})
456	for _, p := range githubapi.Patterns {
457		routes = append(routes, httpserver.Route{Pattern: p, Handler: api})
458	}
459	// The OIDC provider of CI jobs (issuer <public URL>/-/oidc).
460	idp := oidchttp.New(oidchttp.Config{OIDC: f.CI, TrustedProxies: cfg.TrustedProxies, Limiter: limiter})
461	for _, p := range oidchttp.Patterns {
462		routes = append(routes, httpserver.Route{Pattern: p, Handler: idp})
463	}
464	warnSessionsNeedHTTPS(ctx, cfg.PublicURL)
465	warnSharedClientKey(ctx, cfg.TrustedProxies, githttp.DefaultMaxPerClient)
466	site, err := newWeb(cfg, f, limiter)
467	if err != nil {
468		return nil, fmt.Errorf("web: %w", err)
469	}
470	routes = append(routes, webRoutes(site)...)
471	f.server = httpserver.New(httpserver.Config{
472		Addr:         cfg.Addr,
473		PublicURL:    cfg.PublicURL,
474		HealthChecks: []httpserver.Check{store.Check, httpserver.DirWritable(cfg.DataDir)},
475		Routes:       routes,
476		API:          f.API.Handler(),
477		// Event streams never end by themselves: close them when the
478		// shutdown begins, or it would wait for them until its timeout.
479		OnShutdown: []func(){func() { f.EventLog.Close(context.WithoutCancel(ctx)) }},
480	})
481	return f, nil
482}
483
484// Run listens on the configured address and serves until ctx ends.
485func (f *forge) Run(ctx context.Context) error {
486	ln, err := net.Listen("tcp", f.cfg.Addr)
487	if err != nil {
488		return fmt.Errorf("listen on %s: %w", f.cfg.Addr, err)
489	}
490	return f.Serve(ctx, ln)
491}
492
493// Serve serves HTTP on ln and the hook socket until ctx ends. The hook socket
494// outlives the HTTP server: requests still in flight while it drains are
495// pushes whose hooks need it. A failure of either stops both.
496func (f *forge) Serve(ctx context.Context, ln net.Listener) error {
497	ctx, cancel := context.WithCancel(ctx)
498	defer cancel()
499	hookCtx, stopHooks := context.WithCancel(context.WithoutCancel(ctx))
500	defer stopHooks()
501
502	hookErr := make(chan error, 1)
503	go func() {
504		err := f.hooks.Serve(hookCtx)
505		cancel() // a dead hook socket would reject every push: stop serving
506		hookErr <- err
507	}()
508
509	httpErr := f.server.Serve(ctx, ln)
510	stopHooks()
511	return errors.Join(httpErr, <-hookErr)
512}
513
514// Close releases what newForge opened. It is safe to call twice. Call it after
515// the HTTP server stopped: it stops the event log and the long-lived Git
516// processes of the read side, which requests in flight may still use.
517func (f *forge) Close(ctx context.Context) {
518	log := zerowrap.FromCtx(ctx)
519	if f.hooks != nil {
520		f.hooks.Close(ctx)
521	}
522	if f.MergeRequests != nil {
523		f.MergeRequests.Wait(ctx) // its side effects use CI and Mergeability
524	}
525	if f.CI != nil {
526		f.CI.Close(ctx)
527	}
528	if f.Mergeability != nil {
529		f.Mergeability.Close(ctx)
530	}
531	if f.EventLog != nil {
532		f.EventLog.Close(ctx)
533	}
534	if f.reader != nil {
535		f.reader.Close()
536	}
537	if f.git != nil {
538		if err := f.git.Close(ctx); err != nil {
539			log.Error().Err(err).Msg("close git reader")
540		}
541	}
542	if f.maint != nil {
543		f.maint.Close(ctx)
544	}
545	if f.store != nil {
546		if err := f.store.Close(ctx); err != nil {
547			log.Error().Err(err).Msg("close metadata store")
548		}
549		f.store = nil
550	}
551}
552
553// artifacts gives the CI the stores and limits of the artifacts (CI-4 D3):
554// records in the kv store, contents under ci/artifacts. ERMITE_CI_ARTIFACTS=0
555// gives none, and the API then serves no artifact service.
556func artifacts(ci *usecase.CIConfig, cfg config.Config, store *kvstore.Store) {
557	if !cfg.CIArtifacts {
558		return
559	}
560	ci.Artifacts, ci.ArtifactFiles = store.Artifacts(), ciartifacts.New(ciartifacts.Dir(cfg.DataDir))
561	ci.ArtifactLimits = ports.ArtifactLimits{Retention: cfg.CIArtifactRetention, Quota: cfg.CIArtifactQuota, MaxSize: cfg.CIArtifactMax}
562}
563
564// pullRequests gives the CI the merge requests, the refs/pull refs and the
565// identity of the test merge commits (CI-3, D5).
566func (f *forge) pullRequests(cfg *usecase.CIConfig, store *kvstore.Store, git *gitcli.Git, committer domain.Identity) {
567	cfg.MRs, cfg.Pull, cfg.Committer = store.MergeRequests(), git, committer
568	if f.reader != nil {
569		cfg.Fresh = f.reader // a nil *ermitegit.Adapter must not become a non-nil interface
570	}
571}
572
573// signatures wires the commit signature checks (ADR 0030): the stored trusted
574// keys, the instance key as a builtin one for the committer email, the SSH and
575// OpenPGP verifiers, and the raw commit objects of the selected reader.
576func (f *forge) signatures(store *kvstore.Store, reader ports.RepoReader, key domain.SigningPublicKey, committer domain.Identity, clock ports.Clock) error {
577	objects, ok := reader.(ports.CommitObjectReader)
578	if !ok {
579		return errors.New("the git reader cannot read raw commit objects")
580	}
581	builtin := domain.TrustedKey{
582		ID: key.Fingerprint, Format: domain.FormatSSH, Title: "ermite instance key",
583		PublicKey: key.AuthorizedKey, Emails: []string{strings.ToLower(committer.Email)}, Builtin: true,
584	}
585	verifiers := map[domain.SignatureFormat]ports.SignatureVerifier{
586		domain.FormatSSH: sigverify.SSH{}, domain.FormatGPG: sigverify.GPG{},
587	}
588	sigs, err := usecase.NewSignatures(store.TrustedKeys(), sigverify.Inspector{}, verifiers, objects, builtin, clock)
589	if err != nil {
590		return err
591	}
592	f.Signatures = sigs
593	f.Browse.WithVerifier(sigs)
594	return nil
595}
596
597// fastFill is the minimum fill time of the public issue form for a test that
598// lowers the proof of work: next to none. Zero keeps the production value.
599func fastFill(issuePoW int) time.Duration {
600	if issuePoW > 0 {
601		return time.Nanosecond
602	}
603	return 0
604}

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 2

Tags 46

↑↓ moveenter openesc close