agentbbs/internal/forgejo/forgejo.go
Anthony Ettinger f210b4296b 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>
2026-06-23 08:39:37 +00:00

195 lines
5.8 KiB
Go

// Package forgejo provisions a git.profullstack.com account for every verified
// AgentBBS member (free and paid alike) on the self-hosted Forgejo backend that
// powers AgentGit. BBS membership *is* the git account: when a member verifies
// their email, EnsureUser creates the matching Forgejo user. It is idempotent —
// an existing account is left untouched. When unconfigured (no admin token)
// Configured() reports false and callers skip provisioning entirely.
//
// This mirrors the AgentGit ForgejoAdapter.ensureUser contract in
// profullstack/logicsrc (plugins/agentgit). Plan (free vs. premium) never
// affects whether the account exists — only quotas, which are enforced
// server-side by AgentGit merge policy, not here.
//
// Config (env):
//
// AGENTBBS_FORGEJO_URL base URL, e.g. https://git.profullstack.com
// AGENTBBS_FORGEJO_ADMIN_TOKEN Forgejo admin access token
package forgejo
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
// Config holds the Forgejo base URL and admin token.
type Config struct {
BaseURL string
Token string
}
// ConfigFromEnv reads the Forgejo settings from the environment.
func ConfigFromEnv() Config {
return Config{
BaseURL: strings.TrimRight(os.Getenv("AGENTBBS_FORGEJO_URL"), "/"),
Token: os.Getenv("AGENTBBS_FORGEJO_ADMIN_TOKEN"),
}
}
// Configured reports whether accounts can actually be provisioned.
func (c Config) Configured() bool { return c.BaseURL != "" && c.Token != "" }
// EnsureUser creates a Forgejo account for username (forwarding to email) if it
// does not already exist. It is idempotent: created is false when the account
// was already present. New accounts are created with must_change_password — git
// access is via SSH keys, so the generated password is never used interactively.
func (c Config) EnsureUser(username, email string) (created bool, err error) {
if !c.Configured() {
return false, fmt.Errorf("forgejo not configured")
}
exists, err := c.userExists(username)
if err != nil {
return false, err
}
if exists {
return false, nil
}
pw, err := randomPassword()
if err != nil {
return false, err
}
body, _ := json.Marshal(map[string]any{
"username": username,
"email": email,
"password": pw,
"must_change_password": true,
})
status, resp, err := c.do(http.MethodPost, "/admin/users", body)
if err != nil {
return false, err
}
if status < 200 || status >= 300 {
return false, fmt.Errorf("forgejo create user %q: %d: %s", username, status, truncate(resp, 200))
}
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.
func (c Config) userExists(username string) (bool, error) {
status, resp, err := c.do(http.MethodGet, "/users/"+username, nil)
if err != nil {
return false, err
}
switch {
case status == http.StatusOK:
return true, nil
case status == http.StatusNotFound:
return false, nil
default:
return false, fmt.Errorf("forgejo lookup user %q: %d: %s", username, status, truncate(resp, 200))
}
}
func (c Config) do(method, path string, body []byte) (int, string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
var reader io.Reader
if body != nil {
reader = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+"/api/v1"+path, reader)
if err != nil {
return 0, "", err
}
req.Header.Set("Authorization", "token "+c.Token)
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return 0, "", err
}
defer res.Body.Close()
out, _ := io.ReadAll(res.Body)
return res.StatusCode, string(out), nil
}
func randomPassword() (string, error) {
buf := make([]byte, 24)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return hex.EncodeToString(buf), nil
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n]
}