feat(agentgit): register members' SSH keys + enable git push over SSH

Make git.profullstack.com a real, key-authenticated git host for every BBS
member ("BBS membership is the git account", SSH-key auth end to end):

- forgejo.EnsureKey: register a member's SSH public key on their Forgejo
  account (idempotent, ignores the key comment). So the key they sign in to
  the BBS with is also their git push key.
- provisionGit now takes the session public key and registers it after
  ensuring the account; called on email verification AND (newly) on every
  member login, so members who predate AgentGit — or whose key wasn't
  registered yet — are backfilled automatically and off the hot path.
- setup.sh:
  - admin token scopes write:admin,read:user,write:user (the old write:admin
    alone failed userExists' /users lookup, so provisioning never worked).
  - REQUIRE_SIGNIN_VIEW=false so member profiles + public repos are viewable
    at git.profullstack.com/<name> (private repos stay private; accounts are
    still created only by agentbbs).
  - Enable Forgejo's built-in SSH server (port 2222, BUILTIN_SSH_SERVER_USER=git)
    and open the firewall, so members push to git@git.profullstack.com:2222.

Verified live: all members provisioned, git.profullstack.com/chovy serves the
profile, and a push over ssh://git@host:2222 with a registered key succeeds.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-06-23 08:39:37 +00:00
parent c5489a458e
commit f210b4296b
4 changed files with 161 additions and 7 deletions

View file

@ -400,6 +400,13 @@ func (a *app) teaHandler(s ssh.Session) (tea.Model, []tea.ProgramOption) {
// provisions their @host email alias on the transition). // provisions their @host email alias on the transition).
a.ensurePremium(&su) a.ensurePremium(&su)
u = auth.User{Name: su.Name, Kind: auth.Kind(su.Kind), PubKeyFP: fp, StoreID: su.ID} u = auth.User{Name: su.Name, Kind: auth.Kind(su.Kind), PubKeyFP: fp, StoreID: su.ID}
// Backfill the git.profullstack.com account + SSH key on login. Idempotent
// and off the hot path: members who verified before AgentGit existed (or
// before their key was registered) get provisioned on their next visit.
if su.EmailVerified {
suCopy, key := su, authorizedKey(s)
go a.provisionGit(&suCopy, key)
}
} }
sessID, _ := a.st.RecordSession(u.StoreID, s.User(), remoteIP(s), "hub") sessID, _ := a.st.RecordSession(u.StoreID, s.User(), remoteIP(s), "hub")
@ -779,7 +786,7 @@ func (a *app) verifyEmailInteractive(s ssh.Session, in *bufio.Reader, u *store.U
} }
if ok { if ok {
*u = vu *u = vu
a.provisionGit(u) a.provisionGit(u, authorizedKey(s))
wish.Println(s, " Email confirmed ✓") wish.Println(s, " Email confirmed ✓")
return true return true
} }
@ -954,7 +961,7 @@ func (a *app) handleVerify(w http.ResponseWriter, r *http.Request) {
"Run <code>ssh join@"+a.host+"</code> to get a fresh confirmation link."))) "Run <code>ssh join@"+a.host+"</code> to get a fresh confirmation link.")))
return return
} }
a.provisionGit(&u) a.provisionGit(&u, "") // web flow: no SSH session key; key is added on next BBS login
_, _ = w.Write([]byte(verifyPage("Email confirmed ✓", _, _ = w.Write([]byte(verifyPage("Email confirmed ✓",
"Welcome, "+u.Name+". Your account is active — <code>ssh "+u.Name+"@"+a.host+"</code>."))) "Welcome, "+u.Name+". Your account is active — <code>ssh "+u.Name+"@"+a.host+"</code>.")))
} }
@ -964,7 +971,7 @@ func (a *app) handleVerify(w http.ResponseWriter, r *http.Request) {
// alike; plan only affects quotas, enforced by AgentGit, not account existence. // alike; plan only affects quotas, enforced by AgentGit, not account existence.
// Failures are logged but never block BBS verification, and it is a no-op when // Failures are logged but never block BBS verification, and it is a no-op when
// Forgejo is unconfigured. // Forgejo is unconfigured.
func (a *app) provisionGit(u *store.User) { func (a *app) provisionGit(u *store.User, pubKey string) {
if u == nil || !a.forgejo.Configured() || u.Name == "" || u.Email == "" { if u == nil || !a.forgejo.Configured() || u.Name == "" || u.Email == "" {
return return
} }
@ -976,6 +983,25 @@ func (a *app) provisionGit(u *store.User) {
if created { if created {
log.Info("provisioned git account", "user", u.Name, "host", a.forgejo.BaseURL) log.Info("provisioned git account", "user", u.Name, "host", a.forgejo.BaseURL)
} }
// Register the BBS SSH key so the member can push with the same key they sign
// in with. No-op when called without a session key (e.g. the web verify flow).
if pubKey != "" {
if added, err := a.forgejo.EnsureKey(u.Name, "agentbbs", pubKey); err != nil {
log.Error("forgejo ssh key", "user", u.Name, "err", err)
} else if added {
log.Info("registered git ssh key", "user", u.Name)
}
}
}
// authorizedKey renders the session's public key as a single authorized_keys
// line, or "" when the session has no key (guests / keyboard-interactive).
func authorizedKey(s ssh.Session) string {
pk := s.PublicKey()
if pk == nil {
return ""
}
return strings.TrimSpace(string(gossh.MarshalAuthorizedKey(pk)))
} }
// verifyPage renders the minimal confirmation result page. // verifyPage renders the minimal confirmation result page.

View file

@ -84,6 +84,58 @@ func (c Config) EnsureUser(username, email string) (created bool, err error) {
return true, nil return true, nil
} }
// EnsureKey registers an SSH public key on the member's Forgejo account so the
// key they use for the BBS is also their git push key ("BBS membership is the
// git account"). It is idempotent: added is false when the same key material is
// already present. A blank key is a no-op. title labels the key in Forgejo.
func (c Config) EnsureKey(username, title, pubKey string) (added bool, err error) {
if !c.Configured() {
return false, fmt.Errorf("forgejo not configured")
}
pubKey = strings.TrimSpace(pubKey)
if pubKey == "" {
return false, nil
}
// Skip if this key (ignoring the trailing comment) is already on the account.
if status, resp, e := c.do(http.MethodGet, "/users/"+username+"/keys", nil); e == nil && status == http.StatusOK {
var keys []struct {
Key string `json:"key"`
}
if json.Unmarshal([]byte(resp), &keys) == nil {
want := keyMaterial(pubKey)
for _, k := range keys {
if keyMaterial(k.Key) == want {
return false, nil
}
}
}
}
body, _ := json.Marshal(map[string]any{"title": title, "key": pubKey, "read_only": false})
status, resp, err := c.do(http.MethodPost, "/admin/users/"+username+"/keys", body)
if err != nil {
return false, err
}
if status == http.StatusUnprocessableEntity {
return false, nil // key already exists (raced or comment differs)
}
if status < 200 || status >= 300 {
return false, fmt.Errorf("forgejo add key %q: %d: %s", username, status, truncate(resp, 200))
}
return true, nil
}
// keyMaterial returns the type+base64 of an authorized-key line, dropping the
// optional comment so the same key compares equal regardless of how it's labeled.
func keyMaterial(authorizedKey string) string {
f := strings.Fields(strings.TrimSpace(authorizedKey))
if len(f) >= 2 {
return f[0] + " " + f[1]
}
return strings.TrimSpace(authorizedKey)
}
// userExists reports whether a Forgejo user with this name is present. // userExists reports whether a Forgejo user with this name is present.
func (c Config) userExists(username string) (bool, error) { func (c Config) userExists(username string) (bool, error) {
status, resp, err := c.do(http.MethodGet, "/users/"+username, nil) status, resp, err := c.do(http.MethodGet, "/users/"+username, nil)

View file

@ -93,3 +93,65 @@ func TestEnsureUserNoOpWhenExists(t *testing.T) {
t.Fatal("must not POST when the user already exists") t.Fatal("must not POST when the user already exists")
} }
} }
const aliceKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAITESTKEY alice@bbs"
func TestEnsureKeyAddsWhenMissing(t *testing.T) {
var posted map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/users/alice/keys":
_, _ = w.Write([]byte(`[]`))
case r.Method == http.MethodPost && r.URL.Path == "/api/v1/admin/users/alice/keys":
_ = json.NewDecoder(r.Body).Decode(&posted)
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"id":1}`))
default:
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
}
}))
defer srv.Close()
c := Config{BaseURL: srv.URL, Token: "secret"}
added, err := c.EnsureKey("alice", "agentbbs", aliceKey)
if err != nil {
t.Fatalf("EnsureKey: %v", err)
}
if !added {
t.Fatal("expected added=true")
}
if posted["key"] != aliceKey {
t.Errorf("posted key = %v", posted["key"])
}
}
func TestEnsureKeyIdempotentIgnoringComment(t *testing.T) {
posted := false
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
posted = true
}
// Same key material, different comment — must be treated as already present.
_, _ = w.Write([]byte(`[{"key":"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAITESTKEY different-comment"}]`))
}))
defer srv.Close()
c := Config{BaseURL: srv.URL, Token: "secret"}
added, err := c.EnsureKey("alice", "agentbbs", aliceKey)
if err != nil {
t.Fatalf("EnsureKey: %v", err)
}
if added {
t.Fatal("expected added=false when key material already present")
}
if posted {
t.Fatal("must not POST when the key already exists")
}
}
func TestEnsureKeyBlankIsNoOp(t *testing.T) {
c := Config{BaseURL: "https://git.example.com", Token: "t"}
if added, err := c.EnsureKey("alice", "agentbbs", " "); err != nil || added {
t.Fatalf("blank key should be a silent no-op, got added=%v err=%v", added, err)
}
}

View file

@ -53,6 +53,7 @@ MAIL_DOMAIN="${MAIL_DOMAIN:-mail.${DOMAIN#*.}}" # mail host (default: mail.<roo
FORGEJO_HTTP_ADDR="${FORGEJO_HTTP_ADDR:-127.0.0.1:3000}" # Forgejo loopback HTTP (Caddy fronts it) FORGEJO_HTTP_ADDR="${FORGEJO_HTTP_ADDR:-127.0.0.1:3000}" # Forgejo loopback HTTP (Caddy fronts it)
FORGEJO_DATA="${FORGEJO_DATA:-/var/lib/forgejo}" # Forgejo state dir (repos, db) FORGEJO_DATA="${FORGEJO_DATA:-/var/lib/forgejo}" # Forgejo state dir (repos, db)
FORGEJO_ADMIN_USER="${FORGEJO_ADMIN_USER:-agentgit-admin}" # Forgejo admin used to provision members FORGEJO_ADMIN_USER="${FORGEJO_ADMIN_USER:-agentgit-admin}" # Forgejo admin used to provision members
FORGEJO_SSH_PORT="${FORGEJO_SSH_PORT:-2222}" # Forgejo built-in SSH server port (git push); host :22 is agentbbs, :2202 admin
log() { printf '\033[1;36m==>\033[0m %s\n' "$*"; } log() { printf '\033[1;36m==>\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[warn]\033[0m %s\n' "$*" >&2; } warn() { printf '\033[1;33m[warn]\033[0m %s\n' "$*" >&2; }
@ -838,8 +839,15 @@ HTTP_ADDR = ${FORGEJO_HTTP_ADDR%%:*}
HTTP_PORT = ${FORGEJO_HTTP_ADDR##*:} HTTP_PORT = ${FORGEJO_HTTP_ADDR##*:}
DOMAIN = ${GIT_DOMAIN} DOMAIN = ${GIT_DOMAIN}
ROOT_URL = https://${GIT_DOMAIN}/ ROOT_URL = https://${GIT_DOMAIN}/
DISABLE_SSH = true SSH_DOMAIN = ${GIT_DOMAIN}
START_SSH_SERVER = false # Built-in SSH server (in-process, runs as the forgejo user) so members can push
# with the same key they use for the BBS. Host :22 is agentbbs and :2202 is the
# admin OpenSSH, so Forgejo gets its own port; clones use ssh://git@host:PORT/.
DISABLE_SSH = false
START_SSH_SERVER = true
SSH_USER = git
SSH_PORT = ${FORGEJO_SSH_PORT}
SSH_LISTEN_PORT = ${FORGEJO_SSH_PORT}
[database] [database]
DB_TYPE = sqlite3 DB_TYPE = sqlite3
@ -850,7 +858,10 @@ ROOT = ${FORGEJO_DATA}/repos
[service] [service]
DISABLE_REGISTRATION = true DISABLE_REGISTRATION = true
REQUIRE_SIGNIN_VIEW = true # Public read: member profiles (git.${DOMAIN#*.}/<name>) and public repos are
# viewable without signing in; private repos stay private. Accounts are created
# only by agentbbs (DISABLE_REGISTRATION), never self-serve.
REQUIRE_SIGNIN_VIEW = false
DEFAULT_KEEP_EMAIL_PRIVATE = true DEFAULT_KEEP_EMAIL_PRIVATE = true
[security] [security]
@ -896,6 +907,9 @@ UNIT
systemctl is-active --quiet forgejo \ systemctl is-active --quiet forgejo \
|| warn "forgejo failed to start — check: journalctl -u forgejo -n50" || warn "forgejo failed to start — check: journalctl -u forgejo -n50"
# Open the Forgejo SSH port so members can push (git@${GIT_DOMAIN}:${FORGEJO_SSH_PORT}).
ufw allow "${FORGEJO_SSH_PORT}/tcp" >/dev/null 2>&1 || true
# First-run: create the admin agentbbs uses to mint member accounts, and store # First-run: create the admin agentbbs uses to mint member accounts, and store
# an admin-scoped token in agentbbs.env. Guarded on the token being empty so # an admin-scoped token in agentbbs.env. Guarded on the token being empty so
# reruns never create duplicate tokens. # reruns never create duplicate tokens.
@ -906,7 +920,7 @@ UNIT
--password "$FJ_ADMIN_PW" --must-change-password=false --config "$FORGEJO_CONF" >/dev/null 2>&1 \ --password "$FJ_ADMIN_PW" --must-change-password=false --config "$FORGEJO_CONF" >/dev/null 2>&1 \
|| true || true
FJ_TOKEN=$(sudo -u forgejo GITEA_WORK_DIR="$FORGEJO_DATA" /usr/local/bin/forgejo admin user generate-access-token \ FJ_TOKEN=$(sudo -u forgejo GITEA_WORK_DIR="$FORGEJO_DATA" /usr/local/bin/forgejo admin user generate-access-token \
--username "$FORGEJO_ADMIN_USER" --token-name "agentbbs-$(date +%s)" --scopes write:admin \ --username "$FORGEJO_ADMIN_USER" --token-name "agentbbs-$(date +%s)" --scopes write:admin,read:user,write:user \
--config "$FORGEJO_CONF" 2>/dev/null | grep -oE '[0-9a-f]{40}' | head -1) --config "$FORGEJO_CONF" 2>/dev/null | grep -oE '[0-9a-f]{40}' | head -1)
if [ -n "$FJ_TOKEN" ]; then if [ -n "$FJ_TOKEN" ]; then
upsert_env AGENTBBS_FORGEJO_URL "https://${GIT_DOMAIN}" upsert_env AGENTBBS_FORGEJO_URL "https://${GIT_DOMAIN}"