v0.23.0 333c710

sessions.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6	"context"
7	"crypto/rand"
8	"crypto/sha256"
9	"encoding/base64"
10	"errors"
11	"fmt"
12	"sync"
13	"time"
14
15	"github.com/bnema/zerowrap"
16	"github.com/golang-jwt/jwt/v5"
17
18	"bnema.dev/ermite/internal/domain"
19	"bnema.dev/ermite/internal/ports"
20)
21
22// Web login (ADR 0018). The owner asks for a one-time link with the API, opens
23// it in a browser and confirms; the confirmation trades the link for a signed
24// session token that the web keeps in an HttpOnly cookie.
25const (
26	// LoginLinkTTL is how long a login link works.
27	LoginLinkTTL = 60 * time.Second
28	// MaxPendingLoginLinks bounds the links that wait to be used, so that a
29	// loop of CreateLoginLink cannot grow the memory.
30	MaxPendingLoginLinks = 16
31	// SessionTTL is the lifetime of a session.
32	SessionTTL = 12 * time.Hour
33
34	// loginNonceBytes is the size of the secret in a link: 256 bits.
35	loginNonceBytes = 32
36	// sessionSubject is the "sub" claim of every session: there is one owner.
37	sessionSubject = "owner"
38	// LoginPath is the path prefix of login links on the public URL.
39	LoginPath = "/-/login/"
40)
41
42// Sessions are the use cases of the owner's browser sessions: login links,
43// session tokens and signing out everywhere. Login links live in memory only,
44// so a restart voids them; the signing key and the epoch are in the store.
45type Sessions struct {
46	store     ports.SessionStore
47	clock     ports.Clock
48	publicURL string
49	key       []byte
50
51	mu    sync.Mutex
52	links map[[sha256.Size]byte]pendingLink // by hash of the nonce
53}
54
55var _ ports.SessionService = (*Sessions)(nil)
56
57// pendingLink is a login link that waits to be used.
58type pendingLink struct {
59	expires time.Time
60	// sessionCap is the latest moment the session it opens may last until: the
61	// expiry of the token that created the link. Zero means no cap.
62	sessionCap time.Time
63}
64
65// NewSessions builds the session use cases and loads the signing key, which
66// the store generates on first start. publicURL is the base URL the login
67// links are built on.
68func NewSessions(ctx context.Context, store ports.SessionStore, clock ports.Clock, publicURL string) (*Sessions, error) {
69	key, err := store.Key(ctx)
70	if err != nil {
71		return nil, fmt.Errorf("load session key: %w", err)
72	}
73	return &Sessions{store: store, clock: clock, publicURL: publicURL, key: key, links: map[[sha256.Size]byte]pendingLink{}}, nil
74}
75
76// requireOwner is the access rule of the session API: root, or a stored token
77// with every scope, no repository list and no branch prefixes.
78func requireOwner(p domain.Principal) error {
79	switch {
80	case p.IsAnonymous():
81		return domain.ErrUnauthenticated
82	case !p.HasOwnerRights():
83		return fmt.Errorf("%w: managing web sessions needs the admin token or a token with every scope, no repository list and no branch prefixes", domain.ErrForbidden)
84	}
85	return nil
86}
87
88// CreateLoginLink makes a link valid for LoginLinkTTL and usable once. Only
89// the owner may. The session the link opens never outlives the token that
90// created it: it is capped at that token's expiry (no cap for root, or a token
91// that never expires). It gives domain.ErrResourceExhausted when MaxPendingLoginLinks
92// links wait. The nonce is never logged.
93func (s *Sessions) CreateLoginLink(ctx context.Context, p domain.Principal) (ports.LoginLink, error) {
94	if err := requireOwner(p); err != nil {
95		return ports.LoginLink{}, err
96	}
97	var raw [loginNonceBytes]byte
98	if _, err := rand.Read(raw[:]); err != nil {
99		return ports.LoginLink{}, fmt.Errorf("generate login link: %w", err)
100	}
101	nonce := base64.RawURLEncoding.EncodeToString(raw[:])
102	now := s.clock.Now()
103	exp := now.Add(LoginLinkTTL)
104
105	s.mu.Lock()
106	for h, l := range s.links {
107		if !now.Before(l.expires) {
108			delete(s.links, h)
109		}
110	}
111	if len(s.links) >= MaxPendingLoginLinks {
112		s.mu.Unlock()
113		return ports.LoginLink{}, fmt.Errorf("%w: %d login links are already pending, use one or wait a minute", domain.ErrResourceExhausted, MaxPendingLoginLinks)
114	}
115	s.links[sha256.Sum256([]byte(nonce))] = pendingLink{expires: exp, sessionCap: p.ExpiresAt()}
116	s.mu.Unlock()
117
118	log := zerowrap.FromCtx(ctx)
119	log.Info().Str("created_by", p.Label()).Str("created_by_token", p.TokenID()).Time("expires_at", exp).Msg("login link created")
120	return ports.LoginLink{URL: s.publicURL + LoginPath + nonce, ExpiresAt: exp.UTC()}, nil
121}
122
123// LoginLinkValid reports whether the nonce is a pending link, without using
124// it: opening a link shows a confirmation, only confirming consumes it.
125func (s *Sessions) LoginLinkValid(nonce string) bool {
126	h := sha256.Sum256([]byte(nonce))
127	s.mu.Lock()
128	defer s.mu.Unlock()
129	l, ok := s.links[h]
130	return ok && s.clock.Now().Before(l.expires)
131}
132
133// Login consumes the link and opens a session: it returns the signed session
134// token, for the cookie, and when it expires. A link that is unknown, expired
135// or already used gives domain.ErrUnauthenticated, whatever the reason. The
136// nonce and the token are never logged. The session lasts SessionTTL, or until
137// the expiry of the token that created the link when that comes first; a link
138// whose token has expired since gives domain.ErrUnauthenticated.
139func (s *Sessions) Login(ctx context.Context, nonce string) (token string, expiresAt time.Time, err error) {
140	h := sha256.Sum256([]byte(nonce))
141	s.mu.Lock()
142	l, ok := s.links[h]
143	delete(s.links, h) // single use, also when expired
144	s.mu.Unlock()
145	if !ok || !s.clock.Now().Before(l.expires) {
146		return "", time.Time{}, domain.ErrUnauthenticated
147	}
148	token, expiresAt, err = s.issue(ctx, l.sessionCap)
149	if err != nil {
150		return "", time.Time{}, err
151	}
152	log := zerowrap.FromCtx(ctx)
153	log.Info().Time("expires_at", expiresAt).Msg("owner signed in on the web")
154	return token, expiresAt, nil
155}
156
157// sessionClaims are the claims of a session token. The epoch is a pointer so
158// that a token without one is not taken for epoch 0.
159type sessionClaims struct {
160	Epoch *uint64 `json:"epoch"`
161	jwt.RegisteredClaims
162}
163
164// issue signs a session for SessionTTL, cut at capAt unless that is zero.
165func (s *Sessions) issue(ctx context.Context, capAt time.Time) (string, time.Time, error) {
166	epoch, err := s.store.Epoch(ctx)
167	if err != nil {
168		return "", time.Time{}, fmt.Errorf("read session epoch: %w", err)
169	}
170	now := s.clock.Now().UTC()
171	exp := now.Add(SessionTTL)
172	if !capAt.IsZero() && capAt.Before(exp) {
173		exp = capAt.UTC()
174	}
175	if !exp.Truncate(time.Second).After(now) {
176		return "", time.Time{}, domain.ErrUnauthenticated
177	}
178	tok, err := jwt.NewWithClaims(jwt.SigningMethodHS256, sessionClaims{
179		Epoch: &epoch,
180		RegisteredClaims: jwt.RegisteredClaims{
181			Subject:   sessionSubject,
182			IssuedAt:  jwt.NewNumericDate(now),
183			ExpiresAt: jwt.NewNumericDate(exp),
184		},
185	}).SignedString(s.key)
186	if err != nil {
187		return "", time.Time{}, fmt.Errorf("sign session: %w", err)
188	}
189	return tok, exp.Truncate(time.Second), nil
190}
191
192// issueOwner opens an uncapped session for the owner (a passkey login): the
193// same token a login link gives, for SessionTTL.
194func (s *Sessions) issueOwner(ctx context.Context) (string, time.Time, error) {
195	return s.issue(ctx, time.Time{})
196}
197
198// bumpEpoch ends every session and returns the new epoch.
199func (s *Sessions) bumpEpoch(ctx context.Context) (uint64, error) {
200	return s.store.BumpEpoch(ctx)
201}
202
203// Verify checks a session token and returns the owner. The signature must be
204// HS256 with the session key (the algorithm is pinned, so "none" and any other
205// are refused), the token must not be expired or issued in the future, and its
206// epoch must be the current one. Any such failure gives
207// domain.ErrUnauthenticated; a store failure is returned as it is, so that the
208// caller fails closed.
209func (s *Sessions) Verify(ctx context.Context, token string) (domain.Principal, error) {
210	var c sessionClaims
211	_, err := jwt.ParseWithClaims(token, &c, func(*jwt.Token) (any, error) { return s.key, nil },
212		jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
213		jwt.WithExpirationRequired(),
214		jwt.WithIssuedAt(),
215		jwt.WithSubject(sessionSubject),
216		jwt.WithTimeFunc(s.clock.Now),
217	)
218	if err != nil || c.Epoch == nil {
219		return domain.Principal{}, domain.ErrUnauthenticated
220	}
221	epoch, err := s.store.Epoch(ctx)
222	if err != nil {
223		return domain.Principal{}, fmt.Errorf("read session epoch: %w", err)
224	}
225	if *c.Epoch != epoch {
226		return domain.Principal{}, domain.ErrUnauthenticated
227	}
228	return domain.Owner(), nil
229}
230
231// SignOutEverywhere ends every session by incrementing the epoch. Only the
232// owner may. Pending login links stay valid.
233func (s *Sessions) SignOutEverywhere(ctx context.Context, p domain.Principal) error {
234	if err := requireOwner(p); err != nil {
235		return err
236	}
237	epoch, err := s.store.BumpEpoch(ctx)
238	if err != nil {
239		if errors.Is(err, domain.ErrConflict) {
240			return err
241		}
242		return fmt.Errorf("sign out everywhere: %w", err)
243	}
244	log := zerowrap.FromCtx(ctx)
245	log.Info().Str("by", p.Label()).Str("by_token", p.TokenID()).Uint64("epoch", epoch).Msg("every web session signed out")
246	return nil
247}

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 44

↑↓ moveenter openesc close