caelum0x 6801c08af9
Some checks failed
ci / cargo test (abacus) (push) Has been cancelled
ci / cargo test (agent-runtime) (push) Has been cancelled
ci / cargo test (context-passport) (push) Has been cancelled
ci / cargo test (game-economy) (push) Has been cancelled
ci / cargo test (ledgerline) (push) Has been cancelled
ci / cargo test (mint) (push) Has been cancelled
ci / cargo test (rago) (push) Has been cancelled
ci / cargo test (relay) (push) Has been cancelled
ci / node suites (push) Has been cancelled
ci / cargo test (toolgate) (push) Has been cancelled
ci / cargo test (turnstile) (push) Has been cancelled
ci / cargo test (vend) (push) Has been cancelled
feat(RIT-OPS,RIT-BRD): rename gitea -> rit everywhere we control, deployed + live-verified
apps/gitea -> apps/rithub-server; compose services/containers renamed
(rithub-server-app/postgres/act-runner) with explicit project name and
volume names pinned to the exact existing Docker volumes (no data loss);
our own GITEA_* compose/env var names -> RIT_*; new rit-admin CLI wrapper
on railyard-box; giteaSession.mjs/giteaOAuth.mjs/giteaInfo.mjs ->
ritSession/ritOAuth/ritInfo across 6 apps; GiteaForgeAdapter -> RitForgeAdapter
+ giteaSyncService/importGiteaRepos/syncGiteaRepos -> rit* in ritgram
(tsc clean); apps/console/lib/gitea.ts -> lib/ritProvision.ts; Go
internal/giteaclient -> internal/ritclient in rithub-async-import (go
build/test clean); new /auth/rit + /forges/rit/connect routes with
/gitea back-compat aliases; locale/swagger/footer/captcha template text
scrubbed of remaining "Gitea" strings.

Deployed to railyard-box: old containers stopped/removed, /srv/railyard-gitea
renamed to /srv/rithub-server with a symlink kept, docker compose up -d from
the new path, act_runner network-alias fix for its persisted instance URL.
Live-verified: docker compose config diff showed zero unintended value
changes, DB row counts unchanged (19 users, 635 repos), full route
regression 200/expected, 0 "gitea" in headers/bodies on every checked page,
real git clone+push over HTTPS and SSH with a disposable account (deleted
after). Deferred on purpose (documented in plans/railyard.md): the forge
discriminator / DB column names / Postgres role+volume names (data
migrations, not a naming change) and the upstream GITEA__ env-to-ini keys
and X-Gitea-* wire headers (hardcoded in the vendored engine binary).

See plans/railyard.md RIT-OPS/RIT-BRD entry for the full old->new map and
live evidence.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-12-01 16:34:39 +03:00

233 lines
9.0 KiB
Go

package migrate
import (
"context"
"encoding/base64"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/caelum0x/railyard/apps/rithub-async-import/internal/jobs"
)
// gitOps is the two git operations a migration needs. It exists as a
// small interface at the point of use so Runner's orchestration (status
// transitions, error handling) can be unit-tested without invoking the
// real `git` binary or any network, while production always uses
// realGitOps.
type gitOps interface {
// Clone mirror-clones cloneAddr into destDir. authHeader, if
// non-empty, is sent as a raw HTTP Authorization header value
// (e.g. "Basic <base64>") for the duration of the clone only.
Clone(ctx context.Context, cloneAddr, destDir, authHeader string) error
// PushMirror mirror-pushes the repo at repoDir to targetURL.
PushMirror(ctx context.Context, repoDir, targetURL, authHeader string) error
}
// Runner performs the slow half of an async migration: clone the source
// repo, then mirror-push it into the placeholder repo Handler already
// created. One Runner can be shared across jobs; Run is safe to call
// concurrently for different jobs.
type Runner struct {
Store JobStore
// Upstream clears the "[migrating] " marker on success. It is NOT
// used to build the push target (see UpstreamBase below) -- only to
// call UpdateRepoDescription.
Upstream RepoCreator
// UpstreamBase is the engine's own loopback API base (e.g.
// http://127.0.0.1:3350). The mirror push targets this, not
// job.HTMLURL -- job.HTMLURL is the engine's *public* ROOT_URL
// (https://rithub.dev/...), which the create-repo call returns
// regardless of which address was used to reach the engine. Pushing
// there round-trips back out through Cloudflare's edge, which is
// exactly the timeout this whole service exists to avoid (confirmed
// live 2026-11-30: a mirror-push of a tiny repo to the public URL
// hung for minutes on an established-but-stalled TLS connection to
// Cloudflare, instead of completing in seconds over loopback).
UpstreamBase string
Ops gitOps // nil means realGitOps{}
WorkDir string // base dir for temp clones; "" means os.TempDir()
}
func (r *Runner) ops() gitOps {
if r.Ops != nil {
return r.Ops
}
return realGitOps{}
}
// Run implements the Worker signature used by Handler. It never panics
// and never returns an error directly — every outcome is recorded in the
// job store, since by the time this runs the HTTP response that started
// it is long gone.
func (r *Runner) Run(ctx context.Context, job jobs.Job, req Request, token string) {
fail := func(err error) {
_ = r.Store.Update(job.ID, func(j *jobs.Job) {
j.Status = jobs.StatusFailed
j.Error = err.Error()
})
}
workDir := r.WorkDir
if workDir == "" {
workDir = os.TempDir()
}
tmpDir, err := os.MkdirTemp(workDir, "async-import-"+job.ID+"-")
if err != nil {
fail(fmt.Errorf("creating work dir: %w", err))
return
}
defer os.RemoveAll(tmpDir)
_ = r.Store.Update(job.ID, func(j *jobs.Job) { j.Status = jobs.StatusCloning })
srcDir := filepath.Join(tmpDir, "src.git")
cloneAuth := basicAuthHeader(req.AuthUsername, req.AuthPassword, req.AuthToken)
if err := r.ops().Clone(ctx, req.CloneAddr, srcDir, cloneAuth); err != nil {
fail(fmt.Errorf("cloning %s: %w", redactURL(req.CloneAddr), err))
return
}
_ = r.Store.Update(job.ID, func(j *jobs.Job) { j.Status = jobs.StatusPushing })
pushAuth := basicAuthHeader("token", "", token)
// Build the push target from the engine's own loopback base, never
// job.HTMLURL (that is the engine's public ROOT_URL -- see the
// UpstreamBase doc comment on Runner for why pushing there defeats
// the purpose of this service).
target := strings.TrimRight(r.UpstreamBase, "/") + "/" + job.RepoOwner + "/" + job.RepoName
if err := r.ops().PushMirror(ctx, srcDir, target+".git", pushAuth); err != nil {
fail(fmt.Errorf("pushing to %s: %w", job.RepoOwner+"/"+job.RepoName, err))
return
}
if err := r.Upstream.UpdateRepoDescription(ctx, token, job.RepoOwner, job.RepoName, req.Description); err != nil {
// Cosmetic only (clearing the "[migrating] " marker) — the
// repo's content already landed successfully, so this does
// not fail the job, it just leaves the marker in place for
// a human to notice and clear by hand.
_ = r.Store.Update(job.ID, func(j *jobs.Job) {
j.Status = jobs.StatusDone
j.Error = "migrated, but could not clear the \"[migrating]\" description marker: " + err.Error()
})
return
}
_ = r.Store.Update(job.ID, func(j *jobs.Job) { j.Status = jobs.StatusDone })
}
// basicAuthHeader builds a "Basic <base64>" Authorization header value.
// Rithub (and GitHub/GitLab) all accept a personal-access-token-as-
// password Basic auth for git-over-HTTP, so a bare token (username/
// password both empty, token set) is handled by using token as the
// password with a placeholder username — exactly how `git clone
// https://<token>@host/owner/repo.git` works under the hood, just
// without ever putting the token in a URL or argv where `ps` could see
// it. Returns "" when there is nothing to authenticate with (anonymous
// clone of a public repo).
func basicAuthHeader(username, password, token string) string {
user, pass := username, password
if user == "" && pass == "" && token == "" {
return ""
}
if user == "" {
if token != "" {
user, pass = token, ""
} else {
user = "token"
}
} else if pass == "" && token != "" {
pass = token
}
raw := user + ":" + pass
return "Basic " + base64.StdEncoding.EncodeToString([]byte(raw))
}
// redactURL strips userinfo (user:pass@) from a URL before it ever goes
// into an error message or log line, in case a caller embedded
// credentials directly in clone_addr instead of using auth_token.
func redactURL(raw string) string {
u, err := url.Parse(raw)
if err != nil || u.User == nil {
return raw
}
u.User = url.UserPassword("redacted", "redacted")
return u.String()
}
// realGitOps shells out to the real `git` binary. authHeader, when
// non-empty, is passed via GIT_CONFIG_COUNT/KEY/VALUE environment
// variables (git >= 2.31) scoped to that one invocation — never written
// to a config file, never part of the clone URL, and deliberately never
// passed as a `-c` command-line flag: a `-c` flag is a literal argv
// entry, and argv is readable by any other local process on the same
// box (`ps -ef`, `/proc/<pid>/cmdline`) for as long as the clone/push
// runs, which for a real repo is minutes, not milliseconds. An
// environment variable set only on this child process is readable only
// from `/proc/<pid>/environ`, which the kernel restricts to root and the
// owning uid — the isolation a git credential actually needs here.
type realGitOps struct {
// Binary overrides which git executable to run; "" means "git" (the
// one on PATH).
Binary string
// Timeout bounds each individual git invocation; <= 0 means no
// extra timeout beyond ctx's own deadline.
Timeout time.Duration
}
func (g realGitOps) binary() string {
if g.Binary != "" {
return g.Binary
}
return "git"
}
func (g realGitOps) run(ctx context.Context, authHeader string, args ...string) error {
if g.Timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, g.Timeout)
defer cancel()
}
cmd := exec.CommandContext(ctx, g.binary(), args...)
if authHeader != "" {
cmd.Env = append(os.Environ(),
"GIT_CONFIG_COUNT=1",
"GIT_CONFIG_KEY_0=http.extraHeader",
"GIT_CONFIG_VALUE_0=Authorization: "+authHeader,
)
}
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out)))
}
return nil
}
func (g realGitOps) Clone(ctx context.Context, cloneAddr, destDir, authHeader string) error {
return g.run(ctx, authHeader, "clone", "--mirror", cloneAddr, destDir)
}
// PushMirror pushes only refs/heads/* and refs/tags/* (with --prune, so a
// branch/tag deleted at the source is deleted here too), never a blanket
// `git push --mirror`. Live-verified 2026-11-30: a real GitHub repo's
// mirror clone (`git clone --mirror`) also fetches GitHub's own
// `refs/pull/N/head` and `refs/pull/N/merge` refs (every repo that has
// ever had a pull request carries these), and Rithub's own receive-pack
// hook unconditionally rejects external pushes to `refs/pull/*` (it is a
// namespace Rithub's own code generates and protects internally) --
// `--mirror` tries to push every fetched ref including those, so it
// exits non-zero ("hook declined") even when every real branch and tag
// landed successfully, which made the job wrongly report `failed` for
// what is, for a real end user, a fully successful import. Scoping the
// refspec to heads/tags only means git never even attempts the refs
// Rithub would reject, so a repo with PR history (the common case, not
// the exception) imports cleanly.
func (g realGitOps) PushMirror(ctx context.Context, repoDir, targetURL, authHeader string) error {
return g.run(ctx, authHeader, "-C", repoDir, "push", "--prune", targetURL,
"refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*")
}