rotate/gitea: multi-reference blast-and-cutover (LIVE-VM)
Rotate one Gitea PAT and rewrite it in EVERY on-disk reference in lockstep, so a real in-use token can rotate without breaking git auth. The blob carries one ref=<file> per reference; Rotate mints the new token, proves it authenticates, then rewrites the old->new token literal in each ref file (atomic temp+rename, minGiteaTokenLen-guarded), Verify asserts the new token is present in each ref, and the spine revokes the old token last. A dead token is never written into a git config; any failure leaves every ref on a live token. Adds internal/rotate/gitea_refs.go (read-only reference enumerator) + driver and enumerator unit tests. Proven end-to-end against real Gitea 1.25.0 in the sandbox VM via lab/lab-gitea-blast-vm.sh (GITEA_BLAST_VM_OK): one rotation rewrote a fake .git-credentials, an embedded git-remote URL, and a tea config; new->200, old->401. Two documented follow-ons before any in-use host PAT: gopass-entry-sync (PAT duplicated across other gopass entries) and token-scope-cloning (preserve the old token's repo scopes on mint, like sendgrid). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
+74
-17
@@ -8,6 +8,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -68,13 +69,20 @@ func (g *Gitea) client() *http.Client {
|
||||
|
||||
// giteaSecret is the parsed credential blob. None of its fields are ever logged.
|
||||
type giteaSecret struct {
|
||||
base string // scheme://host[:port]
|
||||
user string
|
||||
token string
|
||||
name string // token name (for DELETE)
|
||||
pw string // optional mgmt password (basic auth)
|
||||
base string // scheme://host[:port]
|
||||
user string // Gitea username
|
||||
token string // the PAT being rotated
|
||||
name string // token name (for DELETE)
|
||||
pw string // optional mgmt password (basic auth)
|
||||
refs []string // optional on-disk files that embed the token literally (multi-reference cutover)
|
||||
}
|
||||
|
||||
// minGiteaTokenLen guards the literal on-disk reference rewrite: the old token is the
|
||||
// search key we ReplaceAll across .git-credentials / git remotes / tea config, so a
|
||||
// too-short token could sweep through unrelated file contents. Real Gitea PATs are
|
||||
// 40 hex chars; refuse to rewrite references keyed on anything implausibly short.
|
||||
const minGiteaTokenLen = 20
|
||||
|
||||
// parseGiteaSecret reads the single-line blob from the vault and decomposes it.
|
||||
func parseGiteaSecret(v *vault.Vault, h *vault.Handle) (giteaSecret, error) {
|
||||
buf, err := v.Open(h)
|
||||
@@ -102,6 +110,7 @@ func parseGiteaSecret(v *vault.Vault, h *vault.Handle) (giteaSecret, error) {
|
||||
token: tok,
|
||||
name: q.Get("name"),
|
||||
pw: q.Get("pw"),
|
||||
refs: q["ref"],
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -118,6 +127,9 @@ func (s giteaSecret) build() string {
|
||||
if s.pw != "" {
|
||||
q.Set("pw", s.pw)
|
||||
}
|
||||
for _, r := range s.refs {
|
||||
q.Add("ref", r)
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
@@ -176,27 +188,47 @@ func (g *Gitea) Rotate(ctx context.Context, c discover.Credential, v *vault.Vaul
|
||||
return nil, fmt.Errorf("gitea: create token: empty token in response")
|
||||
}
|
||||
|
||||
ns := s // carry base/user/pw forward
|
||||
ns := s // carry base/user/pw/refs forward
|
||||
ns.token = created.SHA1
|
||||
ns.name = created.Name
|
||||
if ns.name == "" {
|
||||
ns.name = newName
|
||||
}
|
||||
|
||||
// Multi-reference cutover: rewrite the old token → new token, in place, in every
|
||||
// on-disk file that embeds it (git-credentials, embedded git-remote URLs, tea
|
||||
// config). This is what lets a real IN-USE token rotate without breaking git auth.
|
||||
//
|
||||
// SAFETY ORDERING: we do this ONLY after proving the new token authenticates, so a
|
||||
// dead token is never written into a git config; both the old and new tokens stay
|
||||
// valid until RevokeOld (run last by the spine), so any later failure leaves every
|
||||
// reference pointing at a working token. The replacement is keyed on the old token
|
||||
// literal (a 40-hex string), atomic per file (temp+rename), and length-guarded.
|
||||
if len(ns.refs) > 0 {
|
||||
if len(s.token) < minGiteaTokenLen {
|
||||
return nil, fmt.Errorf("gitea: token too short to rewrite references safely (<%d chars)", minGiteaTokenLen)
|
||||
}
|
||||
if err := g.tokenAuthenticates(ctx, ns.base, ns.user, ns.token); err != nil {
|
||||
return nil, fmt.Errorf("gitea: new token failed pre-rewrite auth check: %w", err)
|
||||
}
|
||||
for _, ref := range ns.refs {
|
||||
if _, err := replaceInFile(ref, s.token, ns.token); err != nil {
|
||||
return nil, fmt.Errorf("gitea: rewrite ref %s: %w", ref, redactErr(err, s.token, ns.token))
|
||||
}
|
||||
}
|
||||
}
|
||||
return v.Store([]byte(ns.build())), nil
|
||||
}
|
||||
|
||||
// Verify proves the newly minted token authenticates by calling GET /api/v1/user
|
||||
// with it and checking the returned login matches.
|
||||
func (g *Gitea) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Vault) error {
|
||||
s, err := parseGiteaSecret(v, newSecret)
|
||||
// tokenAuthenticates proves a token is live by calling GET /api/v1/user with it and
|
||||
// (when a username is known) checking the returned login matches. Shared by Rotate's
|
||||
// pre-rewrite gate and Verify.
|
||||
func (g *Gitea) tokenAuthenticates(ctx context.Context, base, user, token string) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/api/v1/user", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.base+"/api/v1/user", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "token "+s.token)
|
||||
req.Header.Set("Authorization", "token "+token)
|
||||
resp, err := g.client().Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("gitea verify: %w", err)
|
||||
@@ -211,8 +243,33 @@ func (g *Gitea) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Va
|
||||
if err := json.NewDecoder(resp.Body).Decode(&who); err != nil {
|
||||
return fmt.Errorf("gitea verify: decode user: %w", err)
|
||||
}
|
||||
if s.user != "" && who.Login != "" && !strings.EqualFold(who.Login, s.user) {
|
||||
return fmt.Errorf("gitea verify: token authenticates as %q, expected %q", who.Login, s.user)
|
||||
if user != "" && who.Login != "" && !strings.EqualFold(who.Login, user) {
|
||||
return fmt.Errorf("gitea verify: token authenticates as %q, expected %q", who.Login, user)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify proves the newly minted token authenticates (GET /api/v1/user, login match)
|
||||
// AND that the multi-reference cutover landed: the new token is present in every
|
||||
// on-disk reference file. Reading a ref that is missing the new token means the
|
||||
// rewrite did not take, so Verify fails and the spine short-circuits before RevokeOld
|
||||
// (old token stays live — no breakage).
|
||||
func (g *Gitea) Verify(ctx context.Context, newSecret *vault.Handle, v *vault.Vault) error {
|
||||
s, err := parseGiteaSecret(v, newSecret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := g.tokenAuthenticates(ctx, s.base, s.user, s.token); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, ref := range s.refs {
|
||||
b, err := os.ReadFile(ref)
|
||||
if err != nil {
|
||||
return fmt.Errorf("gitea verify: read ref %s: %w", ref, err)
|
||||
}
|
||||
if !strings.Contains(string(b), s.token) {
|
||||
return fmt.Errorf("gitea verify: new token missing from ref %s", ref)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package rotate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Reference enumeration for the gitea blast-and-cutover.
|
||||
//
|
||||
// A real IN-USE Gitea PAT does not live only in the gopass blob the driver is
|
||||
// handed — the same 40-hex string is embedded VERBATIM in several on-disk files:
|
||||
// ~/.git-credentials lines, embedded git-remote URLs in each repo's .git/config,
|
||||
// and the `tea` CLI config. Rotating the blob alone would break git auth in every
|
||||
// un-updated place. The blast-and-cutover fixes this by writing one `ref=<file>`
|
||||
// into the blob for every reference file; Rotate then rewrites the old token → new
|
||||
// in each. This file produces that reference list, READ-ONLY.
|
||||
//
|
||||
// SECURITY: the token value is used only as a search key for a literal substring
|
||||
// match; it is never logged, and no candidate file is modified here.
|
||||
|
||||
// giteaWellKnownRefFiles returns the standard credential files that commonly embed a
|
||||
// Gitea token, resolved under the given home dir and honoring $XDG_CONFIG_HOME for
|
||||
// the tea config (matching internal/discover/tea.go). Existence is NOT checked here —
|
||||
// enumerateGiteaRefs filters to the files that actually contain the token.
|
||||
func giteaWellKnownRefFiles(home string) []string {
|
||||
teaDir := filepath.Join(home, ".config", "tea")
|
||||
if x := os.Getenv("XDG_CONFIG_HOME"); x != "" {
|
||||
teaDir = filepath.Join(x, "tea")
|
||||
}
|
||||
return []string{
|
||||
filepath.Join(home, ".git-credentials"),
|
||||
filepath.Join(teaDir, "config.yml"),
|
||||
filepath.Join(teaDir, "config.yaml"),
|
||||
}
|
||||
}
|
||||
|
||||
// giteaGitConfigRefFiles returns the `.git/config` path for each given repo root that
|
||||
// has one. These configs can embed a token inside a remote URL (a per-remote credential
|
||||
// helper or a token baked into the URL). Roots are supplied by the caller (e.g. from the
|
||||
// git scanner's known repos); this does not walk the filesystem on its own.
|
||||
func giteaGitConfigRefFiles(roots ...string) []string {
|
||||
var out []string
|
||||
for _, root := range roots {
|
||||
cfg := filepath.Join(root, ".git", "config")
|
||||
if fi, err := os.Stat(cfg); err == nil && !fi.IsDir() {
|
||||
out = append(out, cfg)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// enumerateGiteaRefs filters a candidate list down to the files that LITERALLY contain
|
||||
// the token, returning the reference set for the blast-and-cutover. It is read-only and
|
||||
// never logs the token. Non-existent or unreadable candidates are skipped silently — a
|
||||
// missing well-known file simply isn't a reference. Duplicate paths are collapsed.
|
||||
//
|
||||
// It refuses a token shorter than minGiteaTokenLen: a short literal could match unrelated
|
||||
// bytes in these files, which would later cause the rewrite to corrupt them.
|
||||
func enumerateGiteaRefs(token string, candidates []string) ([]string, error) {
|
||||
if len(token) < minGiteaTokenLen {
|
||||
return nil, fmt.Errorf("gitea: refusing to enumerate references for a token shorter than %d chars", minGiteaTokenLen)
|
||||
}
|
||||
var refs []string
|
||||
seen := map[string]bool{}
|
||||
for _, c := range candidates {
|
||||
if c == "" {
|
||||
continue
|
||||
}
|
||||
abs, err := filepath.Abs(c)
|
||||
if err != nil {
|
||||
abs = c
|
||||
}
|
||||
if seen[abs] {
|
||||
continue
|
||||
}
|
||||
seen[abs] = true
|
||||
b, err := os.ReadFile(abs)
|
||||
if err != nil {
|
||||
continue // missing/unreadable → not a reference
|
||||
}
|
||||
if strings.Contains(string(b), token) {
|
||||
refs = append(refs, abs)
|
||||
}
|
||||
}
|
||||
return refs, nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package rotate
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const refTestTok = "0123456789abcdef0123456789abcdef01234567" // 40-hex, > minGiteaTokenLen
|
||||
|
||||
// TestEnumerateGiteaRefs proves the enumerator returns exactly the files that literally
|
||||
// hold the token, skips files that do not, and skips missing/unreadable candidates.
|
||||
func TestEnumerateGiteaRefs(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
hit1 := filepath.Join(dir, ".git-credentials")
|
||||
hit2 := filepath.Join(dir, "config") // embedded git remote URL
|
||||
miss := filepath.Join(dir, "unrelated.txt")
|
||||
absent := filepath.Join(dir, "does-not-exist")
|
||||
|
||||
mustWrite(t, hit1, "http://alice:"+refTestTok+"@gitea.local\n")
|
||||
mustWrite(t, hit2, "\turl = http://alice:"+refTestTok+"@gitea.local/a/b.git\n")
|
||||
mustWrite(t, miss, "nothing sensitive here\n")
|
||||
|
||||
got, err := enumerateGiteaRefs(refTestTok, []string{hit1, hit2, miss, absent, ""})
|
||||
if err != nil {
|
||||
t.Fatalf("enumerate: %v", err)
|
||||
}
|
||||
want := map[string]bool{hit1: true, hit2: true}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("got %v, want the two files holding the token", got)
|
||||
}
|
||||
for _, g := range got {
|
||||
if !want[g] {
|
||||
t.Errorf("unexpected ref %q", g)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestEnumerateGiteaRefsDedup proves duplicate candidate paths (absolute vs relative to
|
||||
// the same file) collapse to a single reference.
|
||||
func TestEnumerateGiteaRefsDedup(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
f := filepath.Join(dir, ".git-credentials")
|
||||
mustWrite(t, f, "http://bob:"+refTestTok+"@gitea.local\n")
|
||||
|
||||
got, err := enumerateGiteaRefs(refTestTok, []string{f, f})
|
||||
if err != nil {
|
||||
t.Fatalf("enumerate: %v", err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("expected dedup to 1 ref, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEnumerateGiteaRefsRejectsShortToken proves the length guard: a short token is
|
||||
// refused before any file is read, so it can never match unrelated bytes.
|
||||
func TestEnumerateGiteaRefsRejectsShortToken(t *testing.T) {
|
||||
if _, err := enumerateGiteaRefs("short", []string{"/etc/hosts"}); err == nil ||
|
||||
!strings.Contains(err.Error(), "shorter than") {
|
||||
t.Fatalf("expected short-token refusal, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGiteaGitConfigRefFiles proves only repo roots with a real .git/config are returned.
|
||||
func TestGiteaGitConfigRefFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
repo := filepath.Join(dir, "repo")
|
||||
if err := os.MkdirAll(filepath.Join(repo, ".git"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := filepath.Join(repo, ".git", "config")
|
||||
mustWrite(t, cfg, "[core]\n")
|
||||
noRepo := filepath.Join(dir, "not-a-repo") // no .git at all
|
||||
|
||||
got := giteaGitConfigRefFiles(repo, noRepo)
|
||||
if len(got) != 1 || got[0] != cfg {
|
||||
t.Fatalf("expected only %q, got %v", cfg, got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGiteaWellKnownRefFilesXDG proves the tea config path honors $XDG_CONFIG_HOME.
|
||||
func TestGiteaWellKnownRefFilesXDG(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", "/xdg")
|
||||
got := giteaWellKnownRefFiles("/home/alice")
|
||||
joined := strings.Join(got, "\n")
|
||||
if !strings.Contains(joined, "/home/alice/.git-credentials") {
|
||||
t.Errorf("missing git-credentials in %v", got)
|
||||
}
|
||||
if !strings.Contains(joined, "/xdg/tea/config.yml") {
|
||||
t.Errorf("tea config should honor XDG_CONFIG_HOME, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func mustWrite(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatalf("write %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -182,6 +184,163 @@ func TestGiteaRotateRealCutover(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// giteaRefBlob builds the single-line blob with userinfo + name= + one ref= per file.
|
||||
func giteaRefBlob(srvURL, user, tok, name string, refs ...string) string {
|
||||
b := strings.Replace(srvURL, "http://", "http://"+user+":"+tok+"@", 1) + "/?name=" + name
|
||||
for _, r := range refs {
|
||||
b += "&ref=" + r
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// TestGiteaMultiReferenceCutover proves the blast-and-cutover: the old token literal,
|
||||
// embedded verbatim in several on-disk reference files (a .git-credentials line, an
|
||||
// embedded git-remote URL, a tea config), is rewritten to the freshly minted token in
|
||||
// EVERY file after Rotate — and Verify confirms the new token is present in each.
|
||||
func TestGiteaMultiReferenceCutover(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
ctx := context.Background()
|
||||
|
||||
const user, seedName = "alice", "seed"
|
||||
const oldTok = "0123456789abcdef0123456789abcdef01234567" // 40-hex, > minGiteaTokenLen
|
||||
emu := newGiteaEmu(t, user, seedName, oldTok)
|
||||
|
||||
dir := t.TempDir()
|
||||
// Three distinct real-world shapes, all embedding the old token verbatim.
|
||||
gitCreds := filepath.Join(dir, ".git-credentials")
|
||||
gitConfig := filepath.Join(dir, "config") // embedded git remote URL
|
||||
teaConfig := filepath.Join(dir, "tea.yml")
|
||||
host := strings.TrimPrefix(emu.srv.URL, "http://")
|
||||
writeFile(t, gitCreds, "http://"+user+":"+oldTok+"@"+host+"\n")
|
||||
writeFile(t, gitConfig, "[remote \"origin\"]\n\turl = http://"+user+":"+oldTok+"@"+host+"/alice/repo.git\n")
|
||||
writeFile(t, teaConfig, "logins:\n - name: gitea\n token: "+oldTok+"\n")
|
||||
|
||||
oldBlob := giteaRefBlob(emu.srv.URL, user, oldTok, seedName, gitCreds, gitConfig, teaConfig)
|
||||
cred := discover.Credential{
|
||||
Source: "gitea",
|
||||
Kind: discover.KindToken,
|
||||
Identity: user + " @ gitea",
|
||||
Location: "imported/gitea/alice",
|
||||
Secret: v.Store([]byte(oldBlob)),
|
||||
}
|
||||
|
||||
g := &Gitea{}
|
||||
newH, err := g.Rotate(ctx, cred, v)
|
||||
if err != nil {
|
||||
t.Fatalf("Rotate: %v", err)
|
||||
}
|
||||
ns, err := parseGiteaSecret(v, newH)
|
||||
if err != nil {
|
||||
t.Fatalf("parse new secret: %v", err)
|
||||
}
|
||||
if ns.token == oldTok || !emu.valid(ns.token) {
|
||||
t.Fatalf("expected a fresh valid token, got %q", ns.token)
|
||||
}
|
||||
|
||||
// Every reference file must now hold the NEW token and NOT the old one.
|
||||
for _, ref := range []string{gitCreds, gitConfig, teaConfig} {
|
||||
b, err := os.ReadFile(ref)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", ref, err)
|
||||
}
|
||||
if strings.Contains(string(b), oldTok) {
|
||||
t.Errorf("old token still present in %s after cutover", ref)
|
||||
}
|
||||
if !strings.Contains(string(b), ns.token) {
|
||||
t.Errorf("new token missing from %s after cutover", ref)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify(new) must pass now that every ref holds the new token.
|
||||
if err := g.Verify(ctx, newH, v); err != nil {
|
||||
t.Fatalf("Verify(new): %v", err)
|
||||
}
|
||||
|
||||
// RevokeOld deletes the old token — refs already point at the new one, so nothing breaks.
|
||||
if err := g.RevokeOld(ctx, cred, v); err != nil {
|
||||
t.Fatalf("RevokeOld: %v", err)
|
||||
}
|
||||
if emu.valid(oldTok) {
|
||||
t.Fatal("old token must be dead after revoke")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGiteaVerifyFailsWhenRefMissingToken proves Verify short-circuits the spine (before
|
||||
// RevokeOld) if a reference file does not contain the new token — e.g. an external edit
|
||||
// clobbered it. The old token must stay live in that case.
|
||||
func TestGiteaVerifyFailsWhenRefMissingToken(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
ctx := context.Background()
|
||||
|
||||
const user, seedName = "alice", "seed"
|
||||
const oldTok = "0123456789abcdef0123456789abcdef01234567"
|
||||
emu := newGiteaEmu(t, user, seedName, oldTok)
|
||||
|
||||
dir := t.TempDir()
|
||||
ref := filepath.Join(dir, ".git-credentials")
|
||||
host := strings.TrimPrefix(emu.srv.URL, "http://")
|
||||
writeFile(t, ref, "http://"+user+":"+oldTok+"@"+host+"\n")
|
||||
|
||||
oldBlob := giteaRefBlob(emu.srv.URL, user, oldTok, seedName, ref)
|
||||
cred := discover.Credential{Source: "gitea", Secret: v.Store([]byte(oldBlob))}
|
||||
|
||||
g := &Gitea{}
|
||||
newH, err := g.Rotate(ctx, cred, v)
|
||||
if err != nil {
|
||||
t.Fatalf("Rotate: %v", err)
|
||||
}
|
||||
// Simulate an external clobber: wipe the ref so the new token is no longer present.
|
||||
writeFile(t, ref, "http://"+user+":deadbeef@"+host+"\n")
|
||||
if err := g.Verify(ctx, newH, v); err == nil {
|
||||
t.Fatal("Verify must fail when a ref no longer holds the new token")
|
||||
}
|
||||
// Old token is untouched — spine would leave it live.
|
||||
if !emu.valid(oldTok) {
|
||||
t.Fatal("old token must remain live when Verify fails pre-revoke")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGiteaRefRewriteRejectsShortToken proves the length guard: a too-short old token
|
||||
// (below minGiteaTokenLen) is refused before any file is touched, so a short literal can
|
||||
// never sweep through unrelated file contents.
|
||||
func TestGiteaRefRewriteRejectsShortToken(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
ctx := context.Background()
|
||||
|
||||
const user, seedName = "alice", "seed"
|
||||
const shortTok = "abc123" // < minGiteaTokenLen
|
||||
emu := newGiteaEmu(t, user, seedName, shortTok)
|
||||
|
||||
dir := t.TempDir()
|
||||
ref := filepath.Join(dir, ".git-credentials")
|
||||
host := strings.TrimPrefix(emu.srv.URL, "http://")
|
||||
const orig = "http://" + user + ":" + shortTok + "@HOST\n"
|
||||
writeFile(t, ref, strings.Replace(orig, "HOST", host, 1))
|
||||
|
||||
oldBlob := giteaRefBlob(emu.srv.URL, user, shortTok, seedName, ref)
|
||||
cred := discover.Credential{Source: "gitea", Secret: v.Store([]byte(oldBlob))}
|
||||
|
||||
g := &Gitea{}
|
||||
if _, err := g.Rotate(ctx, cred, v); err == nil || !strings.Contains(err.Error(), "too short") {
|
||||
t.Fatalf("expected too-short refusal, got %v", err)
|
||||
}
|
||||
// The ref file must be untouched (still holds the original short-token line).
|
||||
b, _ := os.ReadFile(ref)
|
||||
if !strings.Contains(string(b), shortTok) {
|
||||
t.Fatal("ref file was modified despite the length guard")
|
||||
}
|
||||
}
|
||||
|
||||
func writeFile(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatalf("write %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaRevokeRequiresName(t *testing.T) {
|
||||
v := vault.New()
|
||||
defer v.Purge()
|
||||
|
||||
Reference in New Issue
Block a user