detached 388d3be

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

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