oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1// agents.go is the non-human half of §6.2's actors: the token a person
2// mints so a program can drive their decks, the middleware that turns
3// one back into a principal, and the screen that does both.
4//
5// The rule the whole file exists to hold, spec §7.1 and suite ruling 9:
6// an agent is its OWN principal, never a borrowed session. Three
7// consequences, each implemented here rather than only stated:
8//
9// - The token is a bearer credential and only a bearer credential.
10// The API never reads a session cookie and the HTML screens never
11// read a bearer, so neither surface can be reached with the other's
12// credential — and a page in a signed-in person's browser has
13// nothing that would drive the API.
14// - Every write it makes is recorded "agent:<id>", so a deck's
15// history names the agent and, through its operator, the person
16// who is answerable for it.
17// - It can see exactly what its operator can see, and not one deck
18// more: every API read and write runs through visibleDecks
19// evaluated for the operator (api.go).
20//
21// Only the SHA-256 of the token is stored — share.go's bargain, and
22// share.go's reason. So the token is shown once, at the moment of
23// minting, and the screen says so there rather than letting somebody
24// find out by coming back for it.
25package slides
26
27import (
28 "context"
29 "crypto/rand"
30 "crypto/sha256"
31 "crypto/subtle"
32 "encoding/hex"
33 "errors"
34 "fmt"
35 "net/http"
36 "strconv"
37 "strings"
38 "time"
39
40 "github.com/go-chi/chi/v5"
41 "gorm.io/gorm"
42
43 "amadan.net/rastrillo/rastrillo"
44 "amadan.net/rastrillo/rastrillo/form"
45)
46
47// --- the token ---
48
49// agentTokenPrefix marks a Slides agent token on sight. A secret that
50// leaks into a log or a paste is found by whoever is scanning for it,
51// and a prefix is what makes that scan possible; it is also what tells
52// a person which of the six tokens in their password manager this is.
53const agentTokenPrefix = "sl_"
54
55// agentTokenAlphabet is base62: what survives being copied out of a
56// terminal, pasted into a YAML file and typed into an environment
57// variable, with nothing to escape and nothing to trim.
58const agentTokenAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
59
60// agentTokenLength is how many of those characters follow the prefix.
61// Forty over sixty-two symbols is about 238 bits, which is not
62// guessable by anything, and short enough to fit on one line.
63const agentTokenLength = 40
64
65// newAgentToken mints one. len(agentTokenAlphabet) is 62, not a power
66// of two, so a plain `b % 62` would be very slightly biased — this
67// rejects the tail of the byte range instead, because a credential is
68// the one place in this app where "astronomically unlikely to matter"
69// is not the standard to hold a random number to.
70func newAgentToken() (string, error) {
71 // 248 is the largest multiple of 62 at or below 256; a byte at or
72 // above it is drawn again.
73 const limit = 248
74 out := make([]byte, 0, agentTokenLength)
75 buf := make([]byte, agentTokenLength)
76 for len(out) < agentTokenLength {
77 if _, err := rand.Read(buf); err != nil {
78 return "", fmt.Errorf("slides: generate agent token: %w", err)
79 }
80 for _, b := range buf {
81 if b >= limit {
82 continue
83 }
84 out = append(out, agentTokenAlphabet[int(b)%len(agentTokenAlphabet)])
85 if len(out) == agentTokenLength {
86 break
87 }
88 }
89 }
90 return agentTokenPrefix + string(out), nil
91}
92
93// hashAgentToken is the stored form: SHA-256 hex, unsalted. The token
94// is 238 bits of randomness, so there is no dictionary to defend
95// against and no salt to add; what an unsalted hash buys is that
96// resolving a bearer is one indexed read.
97//
98// Written out again rather than shared with hashShareToken and
99// hashRemoteToken for presentation.go's reason: the three are separate
100// protocol decisions that happen to agree today, and a change to how
101// share links are stored must not silently change what every live
102// agent token means.
103func hashAgentToken(token string) string {
104 sum := sha256.Sum256([]byte(token))
105 return hex.EncodeToString(sum[:])
106}
107
108// --- the principal ---
109
110// agentPrincipal is spec §7.1's `<name>~<operator email>`: what a
111// person reads in an activity list to know which program made a change
112// and on whose authority.
113//
114// The tilde is the separator because neither half can contain one — an
115// agent name is [a-z0-9-] (validAgentName) and an email address's
116// local part cannot hold a bare tilde in any address this app admits —
117// so the string parses back apart unambiguously.
118func agentPrincipal(name, operatorEmail string) string {
119 return name + "~" + operatorEmail
120}
121
122// agentActor is spec §6.2's actor string for an agent, the counterpart
123// of decks.go's actorFor. Every write over the API records one.
124func agentActor(id int64) string { return fmt.Sprintf("agent:%d", id) }
125
126// agentMark is the robot prefix an agent's principal is shown with,
127// amadan's own convention. It is a mark and not a colour: an agent's
128// write is a different kind of fact from a person's, and a tint alone
129// would say so only to people who can see it.
130const agentMark = "🤖 "
131
132// --- the request principal ---
133
134// principal is the resolved bearer: which agent is calling, and the
135// person whose visibility it borrows. Held together because every API
136// handler needs both — the actor to record, and the operator to scope.
137type principal struct {
138 agent Agent
139 operator User
140}
141
142// actor is what this principal's writes are recorded as.
143func (p principal) actor() string { return agentActor(p.agent.ID) }
144
145// principalKey is the context key the bearer middleware stashes a
146// resolved principal under. An unexported type, so nothing outside
147// this package can put one there.
148type principalKey struct{}
149
150// principalFrom answers the principal this request carries, if the
151// bearer gate resolved one. Only /api/v1 is behind that gate, so on
152// every HTML screen this answers false — which is what makes "the HTML
153// routes never read a bearer" a fact about the router rather than a
154// promise each handler has to keep.
155func principalFrom(r *http.Request) (principal, bool) {
156 p, ok := r.Context().Value(principalKey{}).(principal)
157 return p, ok
158}
159
160// bearerActor is the API's whole gate: an `Authorization: Bearer`
161// header, resolved to a live agent and its operator, or a JSON 401.
162//
163// It reads the header and nothing else. No cookie, no fallback to a
164// session, no "signed in OR bearer" — an API that accepted a cookie
165// would be an API every page in the person's browser could drive.
166//
167// The lookup is by hash, so it is one indexed read; the compare that
168// follows is constant-time over two hex strings of fixed length, which
169// the index alone would not be. Belt and braces: SQLite's comparison
170// is not constant-time, so the index narrows and this decides.
171func (a *app) bearerActor(next http.Handler) http.Handler {
172 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
173 // presentation.go's reader, which the phone remote already
174 // uses: one place decides what `Authorization: Bearer` means
175 // in this app.
176 token := bearerToken(r)
177 if token == "" {
178 apiFail(w, http.StatusUnauthorized, errUnauthorized)
179 return
180 }
181 hash := hashAgentToken(token)
182
183 var agent Agent
184 err := a.db.G.WithContext(r.Context()).
185 Where("token_hash = ? AND revoked_at IS NULL", hash).Take(&agent).Error
186 switch {
187 case err == nil:
188 case errors.Is(err, gorm.ErrRecordNotFound):
189 // A token that was never real and one that was revoked get
190 // the same answer, share.go's rule: anything else would let
191 // a holder of a guess learn that it had once worked.
192 apiFail(w, http.StatusUnauthorized, errUnauthorized)
193 return
194 default:
195 a.logger.Error("slides: resolve a bearer", "err", err)
196 apiFail(w, http.StatusInternalServerError, errInternal)
197 return
198 }
199 if subtle.ConstantTimeCompare([]byte(agent.TokenHash), []byte(hash)) != 1 {
200 apiFail(w, http.StatusUnauthorized, errUnauthorized)
201 return
202 }
203
204 var operator User
205 if err := a.db.G.WithContext(r.Context()).Take(&operator, agent.OperatorID).Error; err != nil {
206 // An agent whose operator is gone is an agent with nobody
207 // answerable for it, and it can see nothing: 401 rather
208 // than a principal with no visibility, so the answer says
209 // what is wrong.
210 a.logger.Error("slides: an agent's operator is missing",
211 "agent", agent.ID, "operator", agent.OperatorID, "err", err)
212 apiFail(w, http.StatusUnauthorized, errUnauthorized)
213 return
214 }
215 // And an agent whose operator is no longer admitted here is an
216 // agent with nobody answerable for it either — spec §6.1's
217 // offboarding rule (codex 6). An agent sees exactly what its
218 // operator sees; when the operator sees nothing, so does it.
219 //
220 // This is the recheck that makes taking an address off
221 // SLIDES_ALLOWED_ADDRESSES mean something. Without it, a token
222 // nobody revoked plus an operator row nobody deleted was
223 // enough to keep writing team decks indefinitely, which is the
224 // one path out of this instance that survives a browser being
225 // signed out. Fail closed, and the same 401 a revoked token
226 // gets: an agent learns nothing about why.
227 //
228 // In team mode the roster replaces that recheck, as it does for
229 // the operator's own sessions (team_access.go): the operator
230 // carries the roster's standing, asked on this request, and the
231 // agent reaches exactly what that standing reaches — the team
232 // rung while Member, grants alone otherwise.
233 if a.team != nil {
234 operator = a.withStanding(r.Context(), operator)
235 } else if !a.allowed.allows(operator.Email) {
236 a.logger.Warn("slides: an agent's operator is no longer admitted; refusing the token",
237 "agent", agent.ID, "operator", operator.ID)
238 apiFail(w, http.StatusUnauthorized, errUnauthorized)
239 return
240 }
241
242 ctx := context.WithValue(r.Context(), principalKey{}, principal{agent: agent, operator: operator})
243 next.ServeHTTP(w, r.WithContext(ctx))
244 })
245}
246
247// --- names ---
248
249// agentNameMin and agentNameMax bound the short half of a principal.
250// Two characters because one is not a name; thirty-two because the
251// principal has to stay readable in a list row beside an address.
252const (
253 agentNameMin = 2
254 agentNameMax = 32
255)
256
257// validAgentName holds the name to what a principal can carry:
258// lowercase letters, digits and hyphens. No dot, no at sign and no
259// tilde, so `<name>~<email>` splits at exactly one place and no name
260// can be made to look like an address.
261func validAgentName(name string) bool {
262 if len(name) < agentNameMin || len(name) > agentNameMax {
263 return false
264 }
265 for _, c := range name {
266 switch {
267 case c >= 'a' && c <= 'z', c >= '0' && c <= '9', c == '-':
268 default:
269 return false
270 }
271 }
272 return true
273}
274
275// --- actor labels ---
276
277// actorLabels resolves a set of actor strings to what a person reads:
278// an address for a person, the robot mark plus the principal for an
279// agent.
280//
281// Two queries for any number of actors, because the deck list calls it
282// once with every row's actor rather than once per row.
283//
284// An actor that resolves to nothing — a deleted person, an agent row
285// that is gone — is left out of the map rather than rendered as a raw
286// id. A list row simply says nothing about who last touched it, which
287// is true, where "person:7" would be noise.
288func (a *app) actorLabels(ctx context.Context, actors []string) map[string]string {
289 var personIDs, agentIDs []int64
290 for _, actor := range actors {
291 kind, raw, found := strings.Cut(actor, ":")
292 if !found {
293 continue
294 }
295 id, err := strconv.ParseInt(raw, 10, 64)
296 if err != nil {
297 continue
298 }
299 switch kind {
300 case "person":
301 personIDs = append(personIDs, id)
302 case "agent":
303 agentIDs = append(agentIDs, id)
304 }
305 }
306
307 out := a.connectionLabels(ctx, actors)
308 if len(personIDs) > 0 {
309 var people []User
310 if err := a.db.G.WithContext(ctx).Where("id IN ?", personIDs).Find(&people).Error; err != nil {
311 a.logger.Error("slides: resolve person actors", "err", err)
312 }
313 homeOnly := a.homeOnlySubjects(ctx)
314 for _, u := range people {
315 out[actorFor(u)] = u.label(homeOnly[u.ID])
316 }
317 }
318 if len(agentIDs) > 0 {
319 var agents []Agent
320 if err := a.db.G.WithContext(ctx).Where("id IN ?", agentIDs).Find(&agents).Error; err != nil {
321 a.logger.Error("slides: resolve agent actors", "err", err)
322 }
323 // One query for the operators the agents name, so this stays
324 // two queries however many agents there are.
325 ids := make([]int64, 0, len(agents))
326 for _, ag := range agents {
327 ids = append(ids, ag.OperatorID)
328 }
329 emails := map[int64]string{}
330 var operators []User
331 if err := a.db.G.WithContext(ctx).Where("id IN ?", ids).Find(&operators).Error; err != nil {
332 a.logger.Error("slides: resolve agent operators", "err", err)
333 }
334 homeOnly := a.homeOnlySubjects(ctx)
335 for _, u := range operators {
336 emails[u.ID] = u.Email
337 if u.Email == "" && homeOnly[u.ID] != "" {
338 emails[u.ID] = homeOnlyLabel(homeOnly[u.ID])
339 }
340 }
341 for _, ag := range agents {
342 out[agentActor(ag.ID)] = agentMark + agentPrincipal(ag.Name, emails[ag.OperatorID])
343 }
344 }
345 return out
346}
347
348// --- GET /agents ---
349
350type agentRow struct {
351 Principal string
352 Created string
353 StatusLabel string
354 StatusTone string
355 Revoked bool
356 RevokeLabel string
357 RevokeAria string
358 RevokeHref string
359}
360
361type agentsPage struct {
362 shell
363 Title string
364 Lead string
365 WarningTitle string
366 Warning string
367 Action string
368 NameLabel string
369 NameHint string
370 NameValue string
371 CreateLabel string
372 Errors map[string]string
373
374 // NewToken is the token this request minted, shown once and never
375 // again. Empty on every visit that did not just create one.
376 NewToken string
377 NewPrincipal string
378 NewTitle string
379 NewHint string
380 NewLabel string
381 NewUse string
382 CopyHint string
383
384 Agents []agentRow
385 EmptyTitle string
386 EmptyBody string
387}
388
389// agents serves GET /agents: this person's agents, what a token can
390// do, and the one form that mints another.
391func (a *app) agents(w http.ResponseWriter, r *http.Request) {
392 u, ok := a.viewer(w, r)
393 if !ok {
394 return
395 }
396 // No token from the query string, deliberately: the one that was
397 // just minted is written straight into the POST's own answer
398 // (createAgent), and a GET is a URL — history, Referer, every log
399 // that records a path — so there is nowhere here for a credential
400 // to arrive from that it should be honoured out of.
401 a.renderAgentsPage(w, r, u, "", "", nil)
402}
403
404func (a *app) renderAgentsPage(w http.ResponseWriter, r *http.Request, u User, newToken, name string, errs map[string]string) {
405 var rows []Agent
406 if err := a.db.G.WithContext(r.Context()).
407 Where("operator_id = ?", u.ID).
408 Order("created_at DESC, id DESC").Find(&rows).Error; err != nil {
409 a.fail(w, r, "list agents", err)
410 return
411 }
412
413 page := agentsPage{
414 // Appearance returns to the bare path: this page's query can be
415 // the one-time token (?new=), and reflecting a query into the
416 // page would print it again (TestAgentTokenShownOnceAndHashed).
417 shell: a.shellFor(r, u, frame{parts: []string{rastrillo.T(r, "slides.agents.title")}, ret: "/agents"}),
418 Title: rastrillo.T(r, "slides.agents.title"),
419 Lead: rastrillo.T(r, "slides.agents.lead"),
420 WarningTitle: rastrillo.T(r, "slides.agents.warning.title"),
421 Warning: rastrillo.T(r, "slides.agents.warning"),
422 Action: "/agents",
423 NameLabel: rastrillo.T(r, "slides.agents.name.label"),
424 NameHint: rastrillo.T(r, "slides.agents.name.hint"),
425 NameValue: name,
426 CreateLabel: rastrillo.T(r, "slides.agents.create"),
427 Errors: errs,
428 EmptyTitle: rastrillo.T(r, "slides.agents.empty.title"),
429 EmptyBody: rastrillo.T(r, "slides.agents.empty.body"),
430 Agents: make([]agentRow, 0, len(rows)),
431 }
432 if newToken != "" {
433 page.NewToken = newToken
434 page.NewTitle = rastrillo.T(r, "slides.agents.new.title")
435 page.NewHint = rastrillo.T(r, "slides.agents.new.body")
436 page.NewLabel = rastrillo.T(r, "slides.agents.new.label")
437 page.NewUse = rastrillo.Tf(r, "slides.agents.new.use", "origin", a.cfg.Origin)
438 page.CopyHint = rastrillo.T(r, "slides.agents.new.copy")
439 // Which agent the token belongs to: the row that carries this
440 // hash, so the page cannot name one agent and show another's
441 // credential.
442 var minted Agent
443 if err := a.db.G.WithContext(r.Context()).
444 Where("token_hash = ?", hashAgentToken(newToken)).Take(&minted).Error; err == nil {
445 page.NewPrincipal = agentPrincipal(minted.Name, u.address())
446 }
447 }
448 for _, ag := range rows {
449 principal := agentPrincipal(ag.Name, u.address())
450 row := agentRow{
451 Principal: principal,
452 Created: rastrillo.Tf(r, "slides.agents.row.created", "when", whenWords(r, ag.CreatedAt)),
453 Revoked: ag.RevokedAt != nil,
454 RevokeLabel: rastrillo.T(r, "slides.agents.revoke"),
455 RevokeAria: rastrillo.Tf(r, "slides.agents.revoke.aria", "principal", principal),
456 RevokeHref: fmt.Sprintf("/agents/%d/revoke", ag.ID),
457 }
458 if row.Revoked {
459 row.StatusLabel = rastrillo.T(r, "slides.agents.revoked")
460 row.StatusTone = "neutral"
461 } else {
462 row.StatusLabel = rastrillo.T(r, "slides.agents.active")
463 row.StatusTone = "positive"
464 }
465 page.Agents = append(page.Agents, row)
466 }
467 render(w, "agents", page)
468}
469
470// --- POST /agents ---
471
472// createAgent mints one agent and its token, and answers with the
473// agents page itself carrying the token, so it is shown once.
474//
475// The answer is rendered from the POST rather than redirected to,
476// which is the one place this app breaks POST-redirect-GET on purpose:
477// a redirect would have to carry the token in its URL, and a URL with
478// a live credential in it lands in the browser's history, in the
479// Referer of everything the page then loads, and in any log that
480// records paths. The body is the only place it can be shown that is
481// not one of those, so the token goes there and the response is marked
482// no-store. The cost is a re-POST prompt on refresh, which mints
483// another agent — visible, named and revocable, which a leaked token
484// is not.
485func (a *app) createAgent(w http.ResponseWriter, r *http.Request) {
486 u, ok := a.viewer(w, r)
487 if !ok {
488 return
489 }
490
491 p := form.Parse(r, form.Field{Name: "name", Required: true})
492 name := strings.TrimSpace(p.String("name"))
493 errs := map[string]string{}
494 switch {
495 case !p.OK() || !validAgentName(name):
496 // The framework's own message is English built from the field
497 // name; every visible string in this app is a catalog key, so
498 // the failure is kept and the sentence replaced.
499 errs["Name"] = rastrillo.T(r, "slides.agents.name.invalid")
500 default:
501 var taken int64
502 if err := a.db.G.WithContext(r.Context()).Model(&Agent{}).
503 Where("operator_id = ? AND name = ? AND revoked_at IS NULL", u.ID, name).
504 Count(&taken).Error; err != nil {
505 a.fail(w, r, "check an agent name", err)
506 return
507 }
508 if taken > 0 {
509 errs["Name"] = rastrillo.T(r, "slides.agents.name.taken")
510 }
511 }
512 if len(errs) > 0 {
513 w.WriteHeader(http.StatusUnprocessableEntity)
514 a.renderAgentsPage(w, r, u, "", p.Echo()["name"], errs)
515 return
516 }
517
518 token, err := newAgentToken()
519 if err != nil {
520 a.fail(w, r, "mint an agent token", err)
521 return
522 }
523 agent := Agent{
524 Name: name,
525 OperatorID: u.ID,
526 TokenHash: hashAgentToken(token),
527 CreatedAt: time.Now().UTC(),
528 }
529 if err := a.db.G.WithContext(r.Context()).Create(&agent).Error; err != nil {
530 a.fail(w, r, "create agent", err)
531 return
532 }
533 a.logger.Info("slides: agent minted",
534 "agent", agent.ID, "principal", agentPrincipal(agent.Name, u.address()))
535 // The one response that carries a credential, so no cache — shared
536 // or the browser's own back/forward store — may keep it.
537 w.Header().Set("Cache-Control", "no-store")
538 a.renderAgentsPage(w, r, u, token, "", nil)
539}
540
541// --- POST /agents/{id}/revoke ---
542
543// revokeAgent turns one agent off. Scoped by operator, so another
544// person's agent id is a 404 rather than a revocation nobody was
545// entitled to make; revoking twice is not an error, because the token
546// is dead either way and a double-clicked button should not look like
547// a failure.
548func (a *app) revokeAgent(w http.ResponseWriter, r *http.Request) {
549 u, ok := a.viewer(w, r)
550 if !ok {
551 return
552 }
553 id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
554 if err != nil {
555 a.notFound(w, r)
556 return
557 }
558
559 // revoked_at IS NULL in the WHERE, so a second POST cannot move the
560 // timestamp: when an agent was turned off is a fact about it.
561 res := a.db.G.WithContext(r.Context()).Model(&Agent{}).
562 Where("id = ? AND operator_id = ? AND revoked_at IS NULL", id, u.ID).
563 Update("revoked_at", time.Now().UTC())
564 if res.Error != nil {
565 a.fail(w, r, "revoke agent", res.Error)
566 return
567 }
568 if res.RowsAffected == 0 {
569 var n int64
570 if err := a.db.G.WithContext(r.Context()).Model(&Agent{}).
571 Where("id = ? AND operator_id = ?", id, u.ID).Count(&n).Error; err != nil {
572 a.fail(w, r, "check an agent", err)
573 return
574 }
575 if n == 0 {
576 a.notFound(w, r)
577 return
578 }
579 } else {
580 a.logger.Info("slides: agent revoked", "agent", id, "actor", actorFor(u))
581 }
582 http.Redirect(w, r, "/agents", http.StatusSeeOther)
583}
584