A guest login: temporary, look-only, revocable

Users -> Guest logins makes a throwaway user name and password, good for half
an hour by default, to hand to somebody who wants to see the console. It is a
normal account with `guest: true` and an expiry, so login, sessions and the
saved look need no special case, and it is left out of the account list, out of
"the last account can't be removed", and out of the one account an empty user
name means.

What a guest may do is one allow-list, checked in the auth middleware, rather
than a flag ~190 handlers have to remember. The list is matched by asking the
router which handler a request would reach, so it cannot drift from the routes
it names, and it is checked against the scoped path — /api/nodes/grid/procs is
/api/procs on grid — because the hub proxies to a node with a token that is
full control of that node. The node cannot tell a guest from its owner, so the
only place it can be stopped is here, before the request leaves.

A guest gets the dashboard, containers, stacks, disks, hardware, ZFS and usage,
on this machine and on any managed one, and nothing else: no terminal (attaching
is a GET, and it is a root shell), no files, no container logs or environments,
no stack files, no alert channels, no cron, no tokens, no settings, no power.

Expiry is enforced on every request and swept once a minute, so a console left
open on a visitor's phone stops within the minute rather than at their next
click; revoking signs them out at once. The console hides what a guest cannot
use and says how long is left where the power button would be.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Mitchell-Johnson
2026-09-27 17:23:16 -07:00
co-authored by Claude Opus 5
parent 4450f1285d
commit 8a7167bf03
16 changed files with 860 additions and 48 deletions
+280
View File
@@ -0,0 +1,280 @@
package api
// Guest logins: a temporary account for showing somebody the console. It expires by itself
// (half an hour by default), it can be revoked in one tap, and it may only look — it cannot
// change a thing, on this machine or on any machine this hub manages.
//
// The gate is a list of what a guest may reach, and nothing else, so a route added later is
// shut to guests until somebody decides otherwise. It is applied to the *scoped* path, which
// is what makes it hold for managed machines too: the hub proxies to a node as itself, with a
// token that is full control of that node, so the node cannot tell a guest from its owner —
// the decision has to be made here, before the request leaves.
import (
"encoding/json"
"io"
"log"
"net/http"
"net/url"
"strings"
"time"
"hamlab/internal/auth"
"hamlab/internal/config"
"hamlab/internal/store"
)
const (
guestPrefix = "guest-"
guestTTLDefault = 30 * time.Minute
guestTTLMax = 24 * time.Hour
guestReapEvery = time.Minute
)
// guestRoutes is every route a guest login may reach, by the pattern it is registered under
// in New. Reading only, with three exceptions that are the guest's own: signing out, and the
// theme and page order that follow the login.
//
// Deliberately not here, though they only read:
// - terminals — attaching is a root-capable shell, and attaching is a GET
// - files — reading a file is reading every file, including keys and this config
// - a container's logs, inspect, events and health — env vars and logs are where secrets are
// - stack files and .env — same
// - cron/jobs, alerts — the jobs are commands; a channel URL is a key to his phone
// - KVM — a screen and a keyboard on a machine, and its assets load with a GET
// - updates — what is unpatched on his box is not a thing to show a visitor
var guestRoutes = map[string]bool{
"GET /api/me": true,
"POST /api/logout": true,
"GET /api/nodes": true, // the machine switcher: a guest may look at any of them
"GET /api/prefs/ui": true,
"PUT /api/prefs/ui": true, // the look is the login's own
"GET /api/prefs/history": true,
"GET /api/prefs/sampler": true,
"GET /api/procs": true,
"GET /api/hardware": true,
"GET /api/storage": true,
"GET /api/storage/smart/{dev}": true,
"GET /api/storage/zfs/snapshots": true,
"GET /api/zfs": true,
"GET /api/docker": true, // containers, images, volumes, networks — the lists only
"GET /api/docker/stacks": true,
"GET /api/services": true,
"GET /api/services/{unit}": true,
"GET /api/space": true,
"GET /api/space/{disk}": true,
"GET /api/space/{disk}/tree": true,
"GET /api/space/{disk}/largest": true,
"GET /api/tasks": true,
"GET /api/tasks/{id}": true,
// sensors: the read-only interface the dashboard and every graph are built on. A query
// is a POST when the list of ids is too long for a URL, and still only a read.
"GET /api/sensors": true,
"GET /api/sensors/query": true,
"POST /api/sensors/query": true,
"GET /api/sensors/stream": true,
"GET /api/sensors/history": true,
"GET /api/sensors/{id}": true,
"GET /api/sensors/{id}/history": true,
"GET /api/fleet/sensors/query": true,
"POST /api/fleet/sensors/query": true,
}
// guestScope is the path whose permission decides this request. A hub route for a managed
// machine is the same route on that machine — /api/nodes/grid/procs is /api/procs — so it is
// judged by the same line of guestRoutes. A path with nothing after the machine name is the
// machine record itself (adding or removing one), which is no guest's business.
func guestScope(p string) string {
rest, ok := strings.CutPrefix(p, "/api/nodes/")
if !ok {
return p
}
i := strings.IndexByte(rest, '/')
if i < 0 {
return ""
}
return "/api" + rest[i:]
}
// guestMay decides a request by asking the router which handler it would reach, so the
// answer can never drift from the route it is about. An unrouted path lands on the catch-all,
// which is not in the list, so it is refused.
func (s *Server) guestMay(r *http.Request) bool {
probe := r
if p := guestScope(r.URL.Path); p != r.URL.Path {
if p == "" {
return false
}
probe = &http.Request{Method: r.Method, URL: &url.URL{Path: p}, Host: r.Host}
}
_, pattern := s.mux.Handler(probe)
return guestRoutes[pattern]
}
// ---- the accounts themselves ----
func (s *Server) listGuests(w http.ResponseWriter, r *http.Request) {
now := time.Now()
counts := s.sessions.Count()
out := []map[string]any{}
s.cfg.View(func(c *config.Config) {
for _, u := range c.Users {
if !u.Guest || u.Expired(now) {
continue
}
out = append(out, map[string]any{
"name": u.Name, "created": u.Created, "expires": u.Expires,
"issued_by": u.IssuedBy, "sessions": counts[u.Name], "used": !u.LastSeen.IsZero(),
})
}
})
jsonOK(w, 200, out)
}
// addGuest makes a guest login and hands back its password — the only time it is ever
// readable, here as everywhere else a password is generated.
func (s *Server) addGuest(w http.ResponseWriter, r *http.Request) {
me := actorOf(r)
if me.Guest {
jsonErr(w, 403, "a guest login can only look around")
return
}
var body struct {
Minutes int `json:"minutes"`
}
_ = json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&body)
ttl := guestTTLDefault
if body.Minutes > 0 {
ttl = time.Duration(body.Minutes) * time.Minute
}
if ttl > guestTTLMax {
jsonErr(w, 400, "a guest login lasts at most 24 hours")
return
}
pw, err := auth.GuestPassword()
if err != nil {
jsonErr(w, 500, err.Error())
return
}
hash, err := auth.HashPassword(pw)
if err != nil {
jsonErr(w, 500, err.Error())
return
}
var name string
for try := 0; try < 8 && name == ""; try++ {
suffix, err := auth.GuestSuffix()
if err != nil {
jsonErr(w, 500, err.Error())
return
}
candidate := guestPrefix + suffix
s.cfg.View(func(c *config.Config) {
if _, taken := c.User(candidate); !taken {
name = candidate
}
})
}
if name == "" {
jsonErr(w, 500, "could not find a free guest name")
return
}
now := time.Now()
expires := now.Add(ttl)
if err := s.cfg.Update(func(c *config.Config) {
c.Users = append(c.Users, config.User{Name: name, Hash: hash, Created: now, Guest: true, Expires: expires, IssuedBy: me.User})
}); err != nil {
jsonErr(w, 500, err.Error())
return
}
log.Printf("guest login %q issued until %s (by %s)", name, expires.Format(time.RFC3339), clientIP(r))
jsonOK(w, 200, map[string]any{"name": name, "password": pw, "expires": expires, "minutes": int(ttl.Minutes())})
}
// revokeGuest ends a guest login now. No password: it only ever takes access away, and the
// whole point of the thing is that ending it is one tap.
func (s *Server) revokeGuest(w http.ResponseWriter, r *http.Request) {
if actorOf(r).Guest {
jsonErr(w, 403, "a guest login can only look around")
return
}
name := r.PathValue("name")
found := false
if err := s.cfg.Update(func(c *config.Config) {
kept := c.Users[:0]
for _, u := range c.Users {
if u.Name == name && u.Guest {
found = true
continue
}
kept = append(kept, u)
}
c.Users = kept
}); err != nil {
jsonErr(w, 500, err.Error())
return
}
if !found {
jsonErr(w, 404, "no such guest login")
return
}
s.forgetGuest(name)
log.Printf("guest login %q revoked (by %s)", name, clientIP(r))
w.WriteHeader(204)
}
// forgetGuest signs a guest out everywhere and drops the look they left behind.
func (s *Server) forgetGuest(name string) {
s.sessions.RevokeUser(name)
_ = s.store.Update(func(st *store.State) { delete(st.Users, name) })
}
// watchGuests clears out guest logins whose time is up. Expiry is enforced on every request
// as well — this is what keeps the config file from collecting them, and what signs a guest
// out of a console they left open rather than waiting for their next click.
func (s *Server) watchGuests() {
for {
s.reapGuests()
time.Sleep(guestReapEvery)
}
}
func (s *Server) reapGuests() {
now := time.Now()
var gone []string
var have bool
s.cfg.View(func(c *config.Config) {
for _, u := range c.Users {
if u.Guest {
have = true
if u.Expired(now) {
gone = append(gone, u.Name)
}
}
}
})
if !have || len(gone) == 0 {
return
}
expired := map[string]bool{}
for _, n := range gone {
expired[n] = true
}
if err := s.cfg.Update(func(c *config.Config) {
kept := c.Users[:0]
for _, u := range c.Users {
if expired[u.Name] {
continue
}
kept = append(kept, u)
}
c.Users = kept
}); err != nil {
log.Printf("guests: %v", err)
return
}
for _, n := range gone {
s.forgetGuest(n)
}
log.Printf("guest login(s) expired: %s", strings.Join(gone, ", "))
}
+205
View File
@@ -0,0 +1,205 @@
package api
import (
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"testing"
"time"
"hamlab/internal/auth"
"hamlab/internal/config"
"hamlab/internal/store"
)
// The router built without any of the machinery behind it: registering a route never calls
// its handler, so this is the real table, and what guestMay is asked about.
func gateServer(t *testing.T) *Server {
t.Helper()
s := &Server{}
s.mux = s.routes()
return s
}
func may(t *testing.T, s *Server, method, path string) bool {
t.Helper()
return s.guestMay(&http.Request{Method: method, URL: &url.URL{Path: path}})
}
// Every line of guestRoutes has to name a route that exists. A pattern with a typo in it
// would quietly match nothing — safe, but the page that needs it would break with no clue
// why, so the mistake is caught here instead.
func TestGuestRoutesAreReal(t *testing.T) {
s := gateServer(t)
for pattern := range guestRoutes {
method, path, ok := strings.Cut(pattern, " ")
if !ok {
t.Errorf("%q is not \"METHOD /path\"", pattern)
continue
}
probe := strings.NewReplacer("{dev}", "sda", "{unit}", "ssh.service", "{disk}", "sda", "{id}", "x", "{name}", "grid").Replace(path)
_, got := s.mux.Handler(&http.Request{Method: method, URL: &url.URL{Path: probe}})
if got != pattern {
t.Errorf("guestRoutes has %q; %s %s routes to %q", pattern, method, probe, got)
}
}
}
func TestGuestMayOnlyLookAround(t *testing.T) {
s := gateServer(t)
for _, tc := range []struct {
method, path string
want bool
why string
}{
// what a guest is for
{"GET", "/api/me", true, "who am I"},
{"POST", "/api/logout", true, "signing out"},
{"GET", "/api/procs", true, "the Processes page"},
{"GET", "/api/docker", true, "the container list"},
{"GET", "/api/docker/stacks", true, "the stack list"},
{"GET", "/api/zfs", true, "the ZFS page"},
{"GET", "/api/storage/smart/sda", true, "drive health"},
{"GET", "/api/space/sda/tree", true, "the Usage page"},
{"GET", "/api/sensors/stream", true, "live graphs"},
{"POST", "/api/sensors/query", true, "a query too long for a URL is still a read"},
{"GET", "/api/nodes", true, "the machine switcher"},
{"PUT", "/api/prefs/ui", true, "the look is the login's own"},
// the shell, and every road to it
{"GET", "/api/terminals", false, "terminals"},
{"POST", "/api/terminals", false, "opening a shell"},
{"GET", "/api/terminals/abc/attach", false, "attaching is a GET, and it is a root shell"},
{"POST", "/api/docker/containers/gitea/exec", false, "a shell in a container"},
// reads that give away too much
{"GET", "/api/files", false, "the file tree"},
{"GET", "/api/files/read", false, "reading any file, including this config and his keys"},
{"GET", "/api/docker/containers/gitea/inspect", false, "a container's environment is where secrets live"},
{"GET", "/api/docker/containers/gitea/logs", false, "logs leak"},
{"GET", "/api/docker/stacks/gitea", false, "a stack's compose file and .env"},
{"GET", "/api/alerts", false, "a channel URL is a key to his phone"},
{"GET", "/api/cron", false, "cron jobs are commands"},
{"GET", "/api/updates", false, "what is unpatched here"},
{"GET", "/api/tokens", false, "tokens"},
{"GET", "/api/users", false, "the account list"},
{"GET", "/api/sessions", false, "sessions"},
{"GET", "/api/guests", false, "a guest cannot see or make guests"},
{"GET", "/kvm/1", false, "a KVM is a keyboard on a machine"},
{"GET", "/api/debug/pprof/heap", false, "the profiler"},
// anything that changes anything
{"POST", "/api/power/poweroff", false, "turning the box off"},
{"POST", "/api/docker/stacks/gitea/deploy", false, "deploying"},
{"POST", "/api/docker/containers/gitea/restart", false, "restarting a container"},
{"POST", "/api/services/ssh.service/restart", false, "restarting a service"},
{"PUT", "/api/files/write", false, "writing a file"},
{"POST", "/api/procs/1/signal", false, "killing a process"},
{"POST", "/api/users", false, "making an account"},
{"POST", "/api/guests", false, "making a guest login"},
{"DELETE", "/api/guests/guest-abcd", false, "revoking one"},
{"POST", "/api/password", false, "changing a password"},
{"POST", "/api/tokens/read", false, "issuing a token"},
{"POST", "/api/self-update", false, "replacing the binary"},
{"POST", "/api/updates/upgrade", false, "upgrading packages"},
{"PUT", "/api/prefs/history", false, "a machine-wide setting"},
{"PUT", "/api/prefs/sampler", false, "a machine-wide setting"},
{"POST", "/api/nodes", false, "adding a machine"},
{"DELETE", "/api/nodes/grid", false, "removing one"},
{"PUT", "/api/alerts", false, "alert rules"},
{"POST", "/api/space/sda/scan", false, "starting a scan"},
// a managed machine is judged by the same table: the hub proxies as itself, with a
// token that is full control of the node, so this is the only place it can be stopped
{"GET", "/api/nodes/grid/procs", true, "looking at grid"},
{"GET", "/api/nodes/grid/sensors/stream", true, "grid's graphs"},
{"GET", "/api/nodes/grid/docker/stacks", true, "grid's stacks"},
{"GET", "/api/nodes/grid/files/read", false, "reading a file on grid"},
{"GET", "/api/nodes/grid/terminals", false, "a shell on grid"},
{"POST", "/api/nodes/grid/docker/stacks/immich/deploy", false, "deploying on grid"},
{"POST", "/api/nodes/grid/power/reboot", false, "rebooting grid"},
{"PUT", "/api/nodes/grid/files/write", false, "writing a file on grid"},
// and nothing unrouted slips through the catch-alls
{"GET", "/api/nothing-like-this", false, "an unknown API path"},
{"GET", "/api/nodes/grid/nothing-like-this", false, "an unknown path on a machine"},
{"GET", "/anything", false, "a path off the API"},
} {
if got := may(t, s, tc.method, tc.path); got != tc.want {
t.Errorf("%s %s: guest may = %v, want %v (%s)", tc.method, tc.path, got, tc.want, tc.why)
}
}
}
func TestGuestScope(t *testing.T) {
for path, want := range map[string]string{
"/api/procs": "/api/procs",
"/api/nodes": "/api/nodes",
"/api/nodes/grid": "", // the machine record itself, not a route on the machine
"/api/nodes/grid/procs": "/api/procs",
"/api/nodes/grid/docker/containers/x/logs": "/api/docker/containers/x/logs",
"/kvm/1": "/kvm/1",
} {
if got := guestScope(path); got != want {
t.Errorf("guestScope(%q) = %q, want %q", path, got, want)
}
}
}
// A guest whose time is up is stopped at the door, whether or not the minute-by-minute
// sweep has got to their account yet — and their session is dropped on the way, so the
// console they left open goes back to the login form.
func TestExpiredGuestIsRefusedAndSignedOut(t *testing.T) {
for _, tc := range []struct {
name string
expires time.Time
wantOK bool
}{
{"still has time", time.Now().Add(10 * time.Minute), true},
{"time is up", time.Now().Add(-time.Second), false},
{"no expiry at all", time.Time{}, false},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
cfg := config.Default(filepath.Join(dir, "config.json"))
if err := cfg.Update(func(c *config.Config) {
c.Users = []config.User{{Name: "guest-abcd", Hash: "x", Guest: true, Expires: tc.expires}}
}); err != nil {
t.Fatal(err)
}
st, err := store.Open(filepath.Join(dir, "state.json"))
if err != nil {
t.Fatal(err)
}
s := &Server{cfg: cfg, store: st, sessions: auth.NewSessions(st)}
tok, err := s.sessions.Create("guest-abcd", "10.0.0.5", "curl")
if err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("GET", "/api/me", nil)
r.AddCookie(&http.Cookie{Name: cookieName, Value: tok})
w := httptest.NewRecorder()
a, ok, answered := s.cookieActor(w, r)
if ok != tc.wantOK {
t.Fatalf("ok = %v, want %v", ok, tc.wantOK)
}
if tc.wantOK {
if !a.Guest || a.User != "guest-abcd" {
t.Errorf("actor = %+v, want the guest account marked as one", a)
}
if answered {
t.Error("answered the caller for a guest that still has time")
}
return
}
if !answered || w.Code != 401 {
t.Errorf("answered = %v, code = %d, want true and 401", answered, w.Code)
}
if _, live := s.sessions.Lookup(tok, "10.0.0.5"); live {
t.Error("the session of an expired guest is still live")
}
})
}
}
+86 -19
View File
@@ -140,9 +140,18 @@ func New(cfg *config.Config, sessions *auth.Sessions, mgr *term.Manager, col *me
}
go s.keepFleetInStep()
}
go s.watchGuests()
go s.watchForUpdates(context.Background())
go s.watchDockerEvents(context.Background())
s.mux = s.routes()
return s
}
// routes is the whole HTTP surface. A method of its own, rather than inline in New, so a
// test can build the real router without the machinery behind it — which is what the guest
// gate is checked against, since it decides a request by asking this router where it would go.
func (s *Server) routes() *http.ServeMux {
m := http.NewServeMux()
m.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) })
m.HandleFunc("POST /api/login", s.login)
@@ -289,6 +298,9 @@ func New(cfg *config.Config, sessions *auth.Sessions, mgr *term.Manager, col *me
m.HandleFunc("POST /api/users", s.auth(s.addUser))
m.HandleFunc("DELETE /api/users/{name}", s.auth(s.removeUser))
m.HandleFunc("POST /api/users/{name}/password", s.auth(s.resetPassword))
m.HandleFunc("GET /api/guests", s.auth(s.listGuests))
m.HandleFunc("POST /api/guests", s.auth(s.addGuest))
m.HandleFunc("DELETE /api/guests/{name}", s.auth(s.revokeGuest))
m.HandleFunc("GET /api/sessions", s.auth(s.listSessions))
m.HandleFunc("DELETE /api/sessions/{id}", s.auth(s.revokeSession))
m.HandleFunc("POST /api/sessions/revoke-others", s.auth(s.revokeOtherSessions))
@@ -318,8 +330,7 @@ func New(cfg *config.Config, sessions *auth.Sessions, mgr *term.Manager, col *me
jsonErr(w, 404, "not found")
}))
m.HandleFunc("/", s.static)
s.mux = m
return s
return m
}
// sensorPath reports whether a path belongs to the read-only sensor API.
@@ -394,25 +405,71 @@ func (s *Server) setCookie(w http.ResponseWriter, r *http.Request, tok string, m
})
}
// signedIn reports whether a request carries a live browser session, without the
// side effects of the auth middleware.
// signedIn reports whether a request carries a live browser session of a real account,
// without the side effects of the auth middleware. A guest login is not one: this is what
// lets a KVM's own assets through, and a KVM is a keyboard on a machine.
func (s *Server) signedIn(r *http.Request) bool {
c, err := r.Cookie(cookieName)
if err != nil {
return false
}
_, ok := s.sessions.Lookup(c.Value, clientKey(r))
return ok
ses, ok := s.sessions.Lookup(c.Value, clientKey(r))
if !ok {
return false
}
var u config.User
var found bool
s.cfg.View(func(cf *config.Config) { u, found = cf.User(ses.User) })
return found && !u.Guest
}
// auth accepts the browser session cookie or a bearer API token issued to a hub.
// guestRefusal is what a guest login is told, wherever it reaches for something.
const guestRefusal = "a guest login can only look around"
// cookieActor resolves the session cookie to who is calling. answered means the caller has
// already been sent an error and the handler must not run: the account behind a live session
// has gone away, or a guest login's time is up — so a console left open on a visitor's phone
// stops at the expiry, not at whatever they click next.
func (s *Server) cookieActor(w http.ResponseWriter, r *http.Request) (a actor, ok, answered bool) {
c, err := r.Cookie(cookieName)
if err != nil {
return actor{}, false, false
}
ses, live := s.sessions.Lookup(c.Value, clientKey(r))
if !live {
return actor{}, false, false
}
var u config.User
var found bool
s.cfg.View(func(cf *config.Config) { u, found = cf.User(ses.User) })
if !found || u.Expired(time.Now()) {
s.sessions.Delete(c.Value)
s.setCookie(w, r, "", -1)
if found {
jsonErr(w, 401, "this guest login has expired")
} else {
jsonErr(w, 401, "that account no longer exists")
}
return actor{}, false, true
}
return actor{User: ses.User, Session: ses.ID, token: c.Value, Guest: u.Guest, Expires: u.Expires}, true, false
}
// auth accepts the browser session cookie or a bearer API token issued to a hub. A guest
// login only reaches the handful of routes guestRoutes names (internal/api/guests.go).
func (s *Server) auth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if c, err := r.Cookie(cookieName); err == nil {
if ses, ok := s.sessions.Lookup(c.Value, clientKey(r)); ok {
next(w, withActor(r, actor{User: ses.User, Session: ses.ID, token: c.Value}))
a, ok, answered := s.cookieActor(w, r)
if answered {
return
}
if ok {
if a.Guest && !s.guestMay(r) {
jsonErr(w, 403, guestRefusal)
return
}
next(w, withActor(r, a))
return
}
if h := r.Header.Get("Authorization"); strings.HasPrefix(h, "Bearer ") {
var hashes, names []string
@@ -446,11 +503,15 @@ func (s *Server) sensorAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ok, trusted := false, false
var patterns []string
if c, err := r.Cookie(cookieName); err == nil {
if ses, valid := s.sessions.Lookup(c.Value, clientKey(r)); valid {
ok, trusted = true, true
r = withActor(r, actor{User: ses.User, Session: ses.ID, token: c.Value})
if a, live, answered := s.cookieActor(w, r); answered {
return
} else if live {
if a.Guest && !s.guestMay(r) {
jsonErr(w, 403, guestRefusal)
return
}
ok, trusted = true, true
r = withActor(r, a)
}
if !ok {
presented, fromURL := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "), false
@@ -919,11 +980,11 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
// name is allowed only while there is exactly one account — what a client from before
// user names sends, and what a hub pairing with a one-user node may leave out.
func (s *Server) checkLogin(username, password string) (string, bool) {
var users []config.User
s.cfg.View(func(c *config.Config) { users = append(users, c.Users...) })
var users, real []config.User
s.cfg.View(func(c *config.Config) { users, real = append(users, c.Users...), c.Accounts() })
username = strings.TrimSpace(username)
if username == "" && len(users) == 1 {
username = users[0].Name
if username == "" && len(real) == 1 { // guest logins are not the account an empty name means
username = real[0].Name
}
if username == "" {
auth.CheckUser(nil, "", password) // take as long as a real check
@@ -1058,8 +1119,14 @@ func (s *Server) me(w http.ResponseWriter, r *http.Request) {
addr = h // the address this console listens on, for the machine menu
}
})
me := actorOf(r)
var guestUntil any
if me.Guest {
guestUntil = me.Expires
}
jsonOK(w, 200, map[string]any{
"host": s.hostName(), "user": s.user, "account": actorOf(r).User, "version": s.version,
"host": s.hostName(), "user": s.user, "account": me.User, "version": s.version,
"guest": me.Guest, "guest_until": guestUntil,
"load": load, "uptime": uptime, "service_started": s.started,
"reboot_needed": rebootErr == nil, "fingerprint": s.fingerprint, "arch": runtime.GOARCH, "addr": addr,
"update_available": updateVersion,
+12 -2
View File
@@ -26,6 +26,10 @@ type actor struct {
Session string // session ID, "" for a token
token string // the raw cookie token, so a handler can spare the current session
Token string // token name, "" for a session
// Guest marks a temporary look-around login, and Expires is when it stops working. What
// a guest may reach is decided in the middleware, not here; see internal/api/guests.go.
Guest bool
Expires time.Time
}
type ctxKey int
@@ -44,6 +48,8 @@ func actorOf(r *http.Request) actor {
// who names the caller for a log line: "core@10.0.0.5" for a person, "token:hub:core@…" for a hub.
func (a actor) String() string {
switch {
case a.User != "" && a.Guest:
return "guest:" + a.User
case a.User != "":
return a.User
case a.Token != "":
@@ -59,7 +65,7 @@ func (s *Server) listUsers(w http.ResponseWriter, r *http.Request) {
counts := s.sessions.Count()
var out []map[string]any
s.cfg.View(func(c *config.Config) {
for _, u := range c.Users {
for _, u := range c.Accounts() { // guest logins are listed on their own, see listGuests
var seen any
if !u.LastSeen.IsZero() {
seen = u.LastSeen
@@ -84,6 +90,10 @@ func (s *Server) addUser(w http.ResponseWriter, r *http.Request) {
jsonErr(w, 400, "a user name is 1–32 lower-case letters, digits, . _ or -, starting with a letter or digit")
return
}
if strings.HasPrefix(name, guestPrefix) {
jsonErr(w, 400, "names starting with "+guestPrefix+" belong to guest logins")
return
}
if len(body.Password) < auth.MinPasswordLen {
jsonErr(w, 400, "password must be at least 12 characters")
return
@@ -141,7 +151,7 @@ func (s *Server) removeUser(w http.ResponseWriter, r *http.Request) {
}
found, last := false, false
if err := s.cfg.Update(func(c *config.Config) {
if len(c.Users) <= 1 {
if len(c.Accounts()) <= 1 { // guest logins don't keep the last real account alive
last = true
return
}