Files
redtea 86cb0226ab feat: machine status page, speed test, live presence, forwards without ufw (0.0.5)
Status page per machine: CPU load, RAM and disk of the client, sampled
by the agent only while the page is open and visible (one reading
serves every open tab), plus a button that has the agent measure its
link to the host: ping, down and up.

Online/offline now comes from the control polls the hub holds open, so
a dropped agent shows offline at once instead of 45 s later, and the
dashboard keeps the status column live.

A forward rule can be created "without ufw": the panel opens nothing in
ufw for it and so revokes nothing when it is deleted. The checkbox is
shown only while the ufw integration is on.

Dashboard row actions are icons; a status action is added.
2026-10-13 18:56:15 +03:00

74 lines
1.8 KiB
Go

package server
import (
"net/http"
"strings"
)
// authenticateAgent resolves the agent identified by the Bearer token on the
// request, verifying the token against the stored hash in constant time.
// Returns nil if authentication fails.
func (s *Server) authenticateAgent(r *http.Request) *Agent {
id := r.Header.Get("X-Agent-Id")
token := bearerToken(r)
if id == "" || token == "" {
return nil
}
a, err := s.db.GetAgent(id)
if err != nil || a == nil {
return nil
}
if !constantTimeEqual(a.TokenHash, hashToken(token)) {
return nil
}
return a
}
// online reports whether the agent is connected right now: the hub knows from
// its control polls. Right after a start it cannot tell yet, so the last poll
// recorded in the database decides.
func (s *Server) online(a *Agent) bool {
if on, ok := s.hub.Online(a.ID); ok {
return on
}
return a.recentlySeen()
}
func bearerToken(r *http.Request) string {
h := r.Header.Get("Authorization")
if strings.HasPrefix(h, "Bearer ") {
return strings.TrimPrefix(h, "Bearer ")
}
return ""
}
// enroll creates a new agent record for a valid enroll secret and returns the
// generated id plus a one-time plaintext token (only the hash is stored).
func (s *Server) enroll(name, hostname, os, arch, version, runUser string) (id, token string, err error) {
id = randToken()[:16]
token = randToken()
a := Agent{
ID: id,
Name: firstNonEmpty(name, hostname, id),
Hostname: hostname,
OS: os,
Arch: arch,
Version: version,
RunUser: runUser,
TokenHash: hashToken(token),
}
if err = s.db.CreateAgent(a); err != nil {
return "", "", err
}
return id, token, nil
}
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if strings.TrimSpace(v) != "" {
return v
}
}
return ""
}