mirror of
https://github.com/profullstack/agentbbs.git
synced 2026-08-13 22:37:28 +00:00
Merge pull request #50 from profullstack/feat/agentgit-ssh-keys
feat(agentgit): SSH-key auth for git.profullstack.com + push
This commit is contained in:
commit
3c3b1b1b06
4 changed files with 161 additions and 7 deletions
|
|
@ -400,6 +400,13 @@ func (a *app) teaHandler(s ssh.Session) (tea.Model, []tea.ProgramOption) {
|
|||
// provisions their @host email alias on the transition).
|
||||
a.ensurePremium(&su)
|
||||
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")
|
||||
|
|
@ -779,7 +786,7 @@ func (a *app) verifyEmailInteractive(s ssh.Session, in *bufio.Reader, u *store.U
|
|||
}
|
||||
if ok {
|
||||
*u = vu
|
||||
a.provisionGit(u)
|
||||
a.provisionGit(u, authorizedKey(s))
|
||||
wish.Println(s, " Email confirmed ✓")
|
||||
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.")))
|
||||
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 ✓",
|
||||
"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.
|
||||
// Failures are logged but never block BBS verification, and it is a no-op when
|
||||
// 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 == "" {
|
||||
return
|
||||
}
|
||||
|
|
@ -976,6 +983,25 @@ func (a *app) provisionGit(u *store.User) {
|
|||
if created {
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -84,6 +84,58 @@ func (c Config) EnsureUser(username, email string) (created bool, err error) {
|
|||
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)
|
||||
|
|
|
|||
|
|
@ -93,3 +93,65 @@ func TestEnsureUserNoOpWhenExists(t *testing.T) {
|
|||
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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
22
setup.sh
22
setup.sh
|
|
@ -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_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_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' "$*"; }
|
||||
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##*:}
|
||||
DOMAIN = ${GIT_DOMAIN}
|
||||
ROOT_URL = https://${GIT_DOMAIN}/
|
||||
DISABLE_SSH = true
|
||||
START_SSH_SERVER = false
|
||||
SSH_DOMAIN = ${GIT_DOMAIN}
|
||||
# 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]
|
||||
DB_TYPE = sqlite3
|
||||
|
|
@ -850,7 +858,10 @@ ROOT = ${FORGEJO_DATA}/repos
|
|||
|
||||
[service]
|
||||
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
|
||||
|
||||
[security]
|
||||
|
|
@ -896,6 +907,9 @@ UNIT
|
|||
systemctl is-active --quiet forgejo \
|
||||
|| 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
|
||||
# an admin-scoped token in agentbbs.env. Guarded on the token being empty so
|
||||
# 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 \
|
||||
|| true
|
||||
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)
|
||||
if [ -n "$FJ_TOKEN" ]; then
|
||||
upsert_env AGENTBBS_FORGEJO_URL "https://${GIT_DOMAIN}"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue