Phase 11, part 1: agents and their keys
Agents are users of kind agent, each given modules to read, or to read and act on, and the CRM scope. Admins make them under Settings → Agents, on every edition; keys (sm_…) are shown once and kept as hashes, can expire, be rotated (the old one works a day) or revoked, and record their last use. /mcp takes agent keys and offers each agent only the tools its scopes allow. On the local edition, mcp-token is the key of a built-in Hermes agent with the CRM and the Market. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,228 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/slug"
|
||||
)
|
||||
|
||||
// Agents are users of kind Agent: no password, no sign-in page, but keys
|
||||
// that reach /mcp. Each has modules like a member ("read" is View, "read
|
||||
// and act" is Edit), and maybe the CRM scope.
|
||||
|
||||
// CRMScope is the scope of the tools that work the CRM queue through the
|
||||
// Core (Hermes' bridge). It's kept with the modules.
|
||||
const CRMScope = "crm"
|
||||
|
||||
// KeyPrefix starts every agent key.
|
||||
const KeyPrefix = "sm_"
|
||||
|
||||
// RotationGrace is how long a key replaced by a new one keeps working.
|
||||
const RotationGrace = 24 * time.Hour
|
||||
|
||||
// Key is one of an agent's keys (never the key itself).
|
||||
type Key struct {
|
||||
ID int64
|
||||
User int64
|
||||
Prefix string // sm_ and its first characters
|
||||
Created time.Time
|
||||
Expires time.Time // zero: never
|
||||
Retires time.Time // zero, or when a rotation ends it
|
||||
Revoked time.Time
|
||||
Used time.Time
|
||||
UsedFrom string
|
||||
}
|
||||
|
||||
// Working says whether the key opens /mcp now.
|
||||
func (k *Key) Working(now time.Time) bool {
|
||||
return k.Revoked.IsZero() && (k.Expires.IsZero() || now.Before(k.Expires)) && (k.Retires.IsZero() || now.Before(k.Retires))
|
||||
}
|
||||
|
||||
// ErrBadKey is a key that's unknown, revoked, expired, retired, or whose
|
||||
// agent is turned off.
|
||||
var ErrBadKey = errors.New("this key doesn't work")
|
||||
|
||||
// CreateAgent adds an agent: a user of kind Agent, active, with a made-up
|
||||
// address no mail goes to.
|
||||
func CreateAgent(d *db.DB, name, description string, now time.Time) (*User, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return nil, errors.New("give the agent a name")
|
||||
}
|
||||
tag := make([]byte, 4)
|
||||
_, _ = rand.Read(tag)
|
||||
base := slug.Make(name)
|
||||
if base == "" {
|
||||
base = "agent"
|
||||
}
|
||||
u := &User{Email: base + "-" + strings.ToLower(b32.EncodeToString(tag)[:6]) + "@agents.invalid", Name: name, Description: description, Kind: Agent, Status: Active}
|
||||
return u, Create(d, u, now)
|
||||
}
|
||||
|
||||
// SaveAgent changes an agent's name and description.
|
||||
func SaveAgent(d *db.DB, id int64, name, description string) error {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return errors.New("give the agent a name")
|
||||
}
|
||||
_, err := d.Exec(`UPDATE users SET name = ?, description = ? WHERE id = ? AND kind = 'agent'`, name, strings.TrimSpace(description), id)
|
||||
return err
|
||||
}
|
||||
|
||||
const keyAlphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||||
|
||||
// newKey is sm_ and 40 random characters (about 230 bits).
|
||||
func newKey() (string, error) {
|
||||
var b strings.Builder
|
||||
b.WriteString(KeyPrefix)
|
||||
max := big.NewInt(int64(len(keyAlphabet)))
|
||||
for i := 0; i < 40; i++ {
|
||||
n, err := rand.Int(rand.Reader, max)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
b.WriteByte(keyAlphabet[n.Int64()])
|
||||
}
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
// NewKey makes a key for an agent, valid until expires (zero: never), and
|
||||
// returns it: the only time it's seen.
|
||||
func NewKey(d *db.DB, user int64, expires, now time.Time) (string, *Key, error) {
|
||||
key, err := newKey()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
k, err := AddKey(d, user, key, expires, now)
|
||||
return key, k, err
|
||||
}
|
||||
|
||||
// AddKey keeps a key made elsewhere (the local edition's mcp-token).
|
||||
func AddKey(d *db.DB, user int64, key string, expires, now time.Time) (*Key, error) {
|
||||
prefix := key
|
||||
if len(prefix) > 10 {
|
||||
prefix = prefix[:10]
|
||||
}
|
||||
k := &Key{User: user, Prefix: prefix, Created: now, Expires: expires}
|
||||
var err error
|
||||
k.ID, err = d.Insert(`INSERT INTO agent_keys (user_id, hash, prefix, created_at, expires_at) VALUES (?, ?, ?, ?, ?)`,
|
||||
user, hashToken(key), prefix, ts(now), tsOrEmpty(expires))
|
||||
return k, err
|
||||
}
|
||||
|
||||
func tsOrEmpty(t time.Time) string {
|
||||
if t.IsZero() {
|
||||
return ""
|
||||
}
|
||||
return ts(t)
|
||||
}
|
||||
|
||||
// Rotate makes a new key for an agent; the working ones it had keep
|
||||
// working for RotationGrace, then stop. The new key keeps the old one's
|
||||
// expiry date (none, if any had none).
|
||||
func Rotate(d *db.DB, user int64, now time.Time) (string, *Key, error) {
|
||||
keys, err := Keys(d, user)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
var expires time.Time
|
||||
for _, k := range keys {
|
||||
if k.Working(now) && !k.Expires.IsZero() && k.Expires.After(expires) {
|
||||
expires = k.Expires
|
||||
}
|
||||
}
|
||||
for _, k := range keys {
|
||||
if k.Working(now) && k.Expires.IsZero() {
|
||||
expires = time.Time{}
|
||||
break
|
||||
}
|
||||
}
|
||||
if _, err := d.Exec(`UPDATE agent_keys SET retires_at = ? WHERE user_id = ? AND revoked_at = '' AND (retires_at = '' OR retires_at > ?)`,
|
||||
ts(now.Add(RotationGrace)), user, ts(now.Add(RotationGrace))); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return NewKey(d, user, expires, now)
|
||||
}
|
||||
|
||||
// Revoke stops one of an agent's keys at once.
|
||||
func Revoke(d *db.DB, user, key int64, now time.Time) error {
|
||||
_, err := d.Exec(`UPDATE agent_keys SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at = ''`, ts(now), key, user)
|
||||
return err
|
||||
}
|
||||
|
||||
// RevokeAll stops all of an agent's keys at once.
|
||||
func RevokeAll(d *db.DB, user int64, now time.Time) error {
|
||||
_, err := d.Exec(`UPDATE agent_keys SET revoked_at = ? WHERE user_id = ? AND revoked_at = ''`, ts(now), user)
|
||||
return err
|
||||
}
|
||||
|
||||
const keyCols = `id, user_id, prefix, created_at, expires_at, retires_at, revoked_at, used_at, used_from`
|
||||
|
||||
func scanKey(row interface{ Scan(...any) error }) (*Key, error) {
|
||||
var k Key
|
||||
var created, expires, retires, revoked, used string
|
||||
if err := row.Scan(&k.ID, &k.User, &k.Prefix, &created, &expires, &retires, &revoked, &used, &k.UsedFrom); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
k.Created, k.Expires, k.Retires, k.Revoked, k.Used = parseTS(created), parseTS(expires), parseTS(retires), parseTS(revoked), parseTS(used)
|
||||
return &k, nil
|
||||
}
|
||||
|
||||
// Keys are an agent's keys, newest first.
|
||||
func Keys(d *db.DB, user int64) ([]*Key, error) {
|
||||
rows, err := d.Query(`SELECT `+keyCols+` FROM agent_keys WHERE user_id = ? ORDER BY id DESC`, user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*Key
|
||||
for rows.Next() {
|
||||
k, err := scanKey(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, k)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// usedEvery is how often a key's use is written down.
|
||||
const usedEvery = time.Minute
|
||||
|
||||
// Authenticate finds the agent a key belongs to, if the key works, and
|
||||
// notes its use.
|
||||
func Authenticate(d *db.DB, key, from string, now time.Time) (*User, *Key, error) {
|
||||
if !strings.HasPrefix(key, KeyPrefix) && len(key) < 32 {
|
||||
return nil, nil, ErrBadKey
|
||||
}
|
||||
k, err := scanKey(d.QueryRow(`SELECT `+keyCols+` FROM agent_keys WHERE hash = ?`, hashToken(key)))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil, ErrBadKey
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !k.Working(now) {
|
||||
return nil, nil, ErrBadKey
|
||||
}
|
||||
u, err := ByID(d, k.User)
|
||||
if errors.Is(err, ErrNotFound) || (err == nil && (u.Kind != Agent || u.Status != Active)) {
|
||||
return nil, nil, ErrBadKey
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if now.Sub(k.Used) >= usedEvery || k.UsedFrom != from {
|
||||
k.Used, k.UsedFrom = now, from
|
||||
if _, err := d.Exec(`UPDATE agent_keys SET used_at = ?, used_from = ? WHERE id = ?`, ts(now), from, k.ID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
return u, k, nil
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAgentKeys(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)
|
||||
a, err := CreateAgent(d, "Morning writer", "Drafts posts from What to write next.", now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.Kind != Agent || a.Status != Active || !strings.HasSuffix(a.Email, "@agents.invalid") || !strings.HasPrefix(a.Email, "morning-writer-") {
|
||||
t.Errorf("agent %+v", a)
|
||||
}
|
||||
if _, err := CreateAgent(d, " ", "", now); err == nil {
|
||||
t.Error("no name accepted")
|
||||
}
|
||||
// Agents never sign in with a password.
|
||||
if CheckPassword(a, "") {
|
||||
t.Error("password")
|
||||
}
|
||||
|
||||
key, k, err := NewKey(d, a.ID, now.Add(30*24*time.Hour), now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(key, "sm_") || len(key) != 43 || k.Prefix != key[:10] {
|
||||
t.Errorf("key %q, prefix %q", key, k.Prefix)
|
||||
}
|
||||
u, got, err := Authenticate(d, key, "203.0.113.7", now)
|
||||
if err != nil || u.ID != a.ID || got.ID != k.ID {
|
||||
t.Fatalf("auth: %v", err)
|
||||
}
|
||||
keys, _ := Keys(d, a.ID)
|
||||
if keys[0].UsedFrom != "203.0.113.7" || !keys[0].Used.Equal(now) {
|
||||
t.Errorf("use not noted: %+v", keys[0])
|
||||
}
|
||||
for _, bad := range []string{"", "sm_nope", key + "x", strings.ToUpper(key)} {
|
||||
if _, _, err := Authenticate(d, bad, "", now); !errors.Is(err, ErrBadKey) {
|
||||
t.Errorf("%q: %v", bad, err)
|
||||
}
|
||||
}
|
||||
// Expiry.
|
||||
if _, _, err := Authenticate(d, key, "", now.Add(31*24*time.Hour)); !errors.Is(err, ErrBadKey) {
|
||||
t.Error("expired key works")
|
||||
}
|
||||
|
||||
// Rotation: the old key works for a day; the new one keeps the expiry.
|
||||
key2, k2, err := Rotate(d, a.ID, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !k2.Expires.Equal(now.Add(30 * 24 * time.Hour)) {
|
||||
t.Errorf("new key's expiry %v", k2.Expires)
|
||||
}
|
||||
if _, _, err := Authenticate(d, key, "", now.Add(23*time.Hour)); err != nil {
|
||||
t.Error("old key stopped within the day")
|
||||
}
|
||||
if _, _, err := Authenticate(d, key, "", now.Add(RotationGrace)); !errors.Is(err, ErrBadKey) {
|
||||
t.Error("old key works after a day")
|
||||
}
|
||||
if _, _, err := Authenticate(d, key2, "", now.Add(RotationGrace)); err != nil {
|
||||
t.Error("new key doesn't work")
|
||||
}
|
||||
|
||||
// Revoking stops it at once; turning the agent off stops every key.
|
||||
Revoke(d, a.ID, k2.ID, now)
|
||||
if _, _, err := Authenticate(d, key2, "", now); !errors.Is(err, ErrBadKey) {
|
||||
t.Error("revoked key works")
|
||||
}
|
||||
key3, _, _ := NewKey(d, a.ID, time.Time{}, now)
|
||||
SetStatus(d, a.ID, Disabled)
|
||||
if _, _, err := Authenticate(d, key3, "", now); !errors.Is(err, ErrBadKey) {
|
||||
t.Error("a turned-off agent's key works")
|
||||
}
|
||||
SetStatus(d, a.ID, Active)
|
||||
RevokeAll(d, a.ID, now)
|
||||
if _, _, err := Authenticate(d, key3, "", now); !errors.Is(err, ErrBadKey) {
|
||||
t.Error("revoke all")
|
||||
}
|
||||
|
||||
// A person's "key" never authenticates, even if one were stored.
|
||||
p := &User{Email: "pat@example.com", Status: Active}
|
||||
Create(d, p, now)
|
||||
AddKey(d, p.ID, "sm_person_key_0123456789012345678901234", time.Time{}, now)
|
||||
if _, _, err := Authenticate(d, "sm_person_key_0123456789012345678901234", "", now); !errors.Is(err, ErrBadKey) {
|
||||
t.Error("a person's key works")
|
||||
}
|
||||
|
||||
// A legacy token (64 hex digits) is a key too.
|
||||
legacy := strings.Repeat("ab", 32)
|
||||
AddKey(d, a.ID, legacy, time.Time{}, now)
|
||||
if _, _, err := Authenticate(d, legacy, "", now); err != nil {
|
||||
t.Errorf("legacy token: %v", err)
|
||||
}
|
||||
if err := Delete(d, a.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ks, _ := Keys(d, a.ID); len(ks) != 0 {
|
||||
t.Error("keys outlived the agent")
|
||||
}
|
||||
}
|
||||
@@ -76,6 +76,7 @@ type User struct {
|
||||
Kind Kind
|
||||
Status Status
|
||||
Title string
|
||||
Description string // an agent's: what it's for
|
||||
TimeZone string
|
||||
Photo string
|
||||
Emails []string // the emails they want (the daily SEO email, …)
|
||||
@@ -137,13 +138,13 @@ func NormalEmail(s string) (string, error) {
|
||||
return strings.ToLower(s), nil
|
||||
}
|
||||
|
||||
const userCols = `id, email, name, kind, status, password_hash, title, time_zone, photo, emails, created_at, signed_in_at, failed_signins, locked_at, two_factor, totp_step, recovery_codes`
|
||||
const userCols = `id, email, name, kind, status, password_hash, title, description, time_zone, photo, emails, created_at, signed_in_at, failed_signins, locked_at, two_factor, totp_step, recovery_codes`
|
||||
|
||||
func scanUser(row interface{ Scan(...any) error }) (*User, error) {
|
||||
var u User
|
||||
var kind, status, emails, created, signedIn, locked, codes string
|
||||
var twoFactor int
|
||||
err := row.Scan(&u.ID, &u.Email, &u.Name, &kind, &status, &u.passwordHash, &u.Title, &u.TimeZone, &u.Photo, &emails, &created, &signedIn,
|
||||
err := row.Scan(&u.ID, &u.Email, &u.Name, &kind, &status, &u.passwordHash, &u.Title, &u.Description, &u.TimeZone, &u.Photo, &emails, &created, &signedIn,
|
||||
&u.FailedSignIns, &locked, &twoFactor, &u.totpStep, &codes)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
@@ -184,9 +185,9 @@ func Create(d *db.DB, u *User, now time.Time) error {
|
||||
}
|
||||
emails, _ := json.Marshal(u.Emails)
|
||||
u.Created = now
|
||||
u.ID, err = d.Insert(`INSERT INTO users (email, name, kind, status, password_hash, title, time_zone, photo, emails, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
u.Email, strings.TrimSpace(u.Name), string(u.Kind), string(u.Status), u.passwordHash, u.Title, u.TimeZone, u.Photo, string(emails), ts(now))
|
||||
u.ID, err = d.Insert(`INSERT INTO users (email, name, kind, status, password_hash, title, description, time_zone, photo, emails, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
u.Email, strings.TrimSpace(u.Name), string(u.Kind), string(u.Status), u.passwordHash, u.Title, strings.TrimSpace(u.Description), u.TimeZone, u.Photo, string(emails), ts(now))
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -264,7 +265,7 @@ func Delete(d *db.DB, id int64) error {
|
||||
defer tx.Rollback()
|
||||
// Not left to ON DELETE CASCADE: SQLite enforces it only with
|
||||
// foreign_keys on, and an imported database may not have had them.
|
||||
for _, q := range []string{`DELETE FROM sessions WHERE user_id = ?`, `DELETE FROM links WHERE user_id = ?`, `DELETE FROM memberships WHERE user_id = ?`, `DELETE FROM users WHERE id = ?`} {
|
||||
for _, q := range []string{`DELETE FROM sessions WHERE user_id = ?`, `DELETE FROM links WHERE user_id = ?`, `DELETE FROM agent_keys WHERE user_id = ?`, `DELETE FROM memberships WHERE user_id = ?`, `DELETE FROM users WHERE id = ?`} {
|
||||
if _, err := tx.Exec(q, id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user