Re-mint watchpr's Gitea token when it expires
Vault-minted Gitea tokens last ~1h, far less than a watch, and every poll past expiry 401'd into a warning while watchpr looked healthy. - retry a rejected request once with a freshly minted token - abort the watch when the fresh token is rejected too - poll anonymously when no token can be minted, mint only on a real 401/403
This commit is contained in:
@@ -2,9 +2,11 @@ package agent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -231,3 +233,219 @@ func TestGiteaAPIError(t *testing.T) {
|
||||
t.Fatal("expected error on 422")
|
||||
}
|
||||
}
|
||||
|
||||
// expiringGitea serves the PR endpoint, rejecting every token other than
|
||||
// wantToken with a 401 exactly as Gitea does once a Vault-minted token expires.
|
||||
// It records the tokens it saw, newest last.
|
||||
func expiringGitea(t *testing.T, wantToken string, seen *[]string) *httptest.Server {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/repos/unkin/repo/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
tok := strings.TrimPrefix(r.Header.Get("Authorization"), "token ")
|
||||
*seen = append(*seen, tok)
|
||||
if tok != wantToken {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = io.WriteString(w, `{"message":"invalid username, password or token"}`)
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"number":7,"state":"open","mergeable":true,"head":{"sha":"cafebabe"}}`)
|
||||
})
|
||||
return httptest.NewServer(mux)
|
||||
}
|
||||
|
||||
// The production failure: the token expired mid-run. The client must re-mint
|
||||
// once and replay the request with the fresh token.
|
||||
func TestExpiredTokenIsRemintedAndRetried(t *testing.T) {
|
||||
var seen []string
|
||||
srv := expiringGitea(t, "fresh", &seen)
|
||||
defer srv.Close()
|
||||
|
||||
refreshes := 0
|
||||
c := &GiteaClient{BaseURL: srv.URL, Token: "stale", HTTP: srv.Client(),
|
||||
Refresh: func() (string, error) { refreshes++; return "fresh", nil }}
|
||||
|
||||
pr, err := c.GetPR("unkin/repo", 7)
|
||||
if err != nil {
|
||||
t.Fatalf("GetPR after re-mint: %v", err)
|
||||
}
|
||||
if pr.Number != 7 {
|
||||
t.Errorf("PR number = %d, want 7", pr.Number)
|
||||
}
|
||||
if refreshes != 1 {
|
||||
t.Errorf("refreshes = %d, want 1", refreshes)
|
||||
}
|
||||
if len(seen) != 2 || seen[0] != "stale" || seen[1] != "fresh" {
|
||||
t.Errorf("tokens seen = %v, want [stale fresh]", seen)
|
||||
}
|
||||
if c.Token != "fresh" {
|
||||
t.Errorf("client token = %q, want the refreshed token", c.Token)
|
||||
}
|
||||
}
|
||||
|
||||
// A fresh token that is also rejected is a real auth failure: report it as one
|
||||
// rather than re-minting forever.
|
||||
func TestAuthFailureSurvivesRemint(t *testing.T) {
|
||||
var seen []string
|
||||
srv := expiringGitea(t, "never-issued", &seen)
|
||||
defer srv.Close()
|
||||
|
||||
refreshes := 0
|
||||
c := &GiteaClient{BaseURL: srv.URL, Token: "stale", HTTP: srv.Client(),
|
||||
Refresh: func() (string, error) { refreshes++; return "still-bad", nil }}
|
||||
|
||||
_, err := c.GetPR("unkin/repo", 7)
|
||||
if err == nil {
|
||||
t.Fatal("GetPR should fail when the fresh token is rejected too")
|
||||
}
|
||||
if !IsAuthError(err) {
|
||||
t.Errorf("IsAuthError(%v) = false, want true", err)
|
||||
}
|
||||
if refreshes != 1 {
|
||||
t.Errorf("refreshes = %d, want 1 (re-mint exactly once)", refreshes)
|
||||
}
|
||||
if len(seen) != 2 {
|
||||
t.Errorf("requests = %d, want 2", len(seen))
|
||||
}
|
||||
}
|
||||
|
||||
// A refresh that itself fails must surface as an auth error, not as a silent
|
||||
// success or a bare Vault error.
|
||||
func TestRemintErrorIsReportedAsAuthFailure(t *testing.T) {
|
||||
var seen []string
|
||||
srv := expiringGitea(t, "fresh", &seen)
|
||||
defer srv.Close()
|
||||
|
||||
c := &GiteaClient{BaseURL: srv.URL, Token: "stale", HTTP: srv.Client(),
|
||||
Refresh: func() (string, error) { return "", errors.New("vault approle login: HTTP 503") }}
|
||||
|
||||
_, err := c.GetPR("unkin/repo", 7)
|
||||
if err == nil || !IsAuthError(err) {
|
||||
t.Fatalf("GetPR error = %v, want an auth error", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "vault approle login") {
|
||||
t.Errorf("error %q should name the re-mint failure", err)
|
||||
}
|
||||
if len(seen) != 1 {
|
||||
t.Errorf("requests = %d, want 1 (no replay without a token)", len(seen))
|
||||
}
|
||||
}
|
||||
|
||||
// A 5xx is transient, not an auth problem: no re-mint, no retry, and the caller
|
||||
// keeps its existing retry behaviour.
|
||||
func TestServerErrorDoesNotRemint(t *testing.T) {
|
||||
requests := 0
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/repos/unkin/repo/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
refreshes := 0
|
||||
c := &GiteaClient{BaseURL: srv.URL, Token: "t", HTTP: srv.Client(),
|
||||
Refresh: func() (string, error) { refreshes++; return "fresh", nil }}
|
||||
|
||||
_, err := c.GetPR("unkin/repo", 7)
|
||||
if err == nil {
|
||||
t.Fatal("expected error on 502")
|
||||
}
|
||||
if IsAuthError(err) {
|
||||
t.Errorf("502 must not be an auth error")
|
||||
}
|
||||
if refreshes != 0 || requests != 1 {
|
||||
t.Errorf("refreshes = %d, requests = %d, want 0 and 1", refreshes, requests)
|
||||
}
|
||||
}
|
||||
|
||||
// The replayed request must carry the original body, not an empty one.
|
||||
func TestRemintReplaysRequestBody(t *testing.T) {
|
||||
var bodies []CreatePROptions
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/repos/unkin/repo/pulls", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body CreatePROptions
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
bodies = append(bodies, body)
|
||||
if strings.TrimPrefix(r.Header.Get("Authorization"), "token ") != "fresh" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"number":7}`)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
c := &GiteaClient{BaseURL: srv.URL, Token: "stale", HTTP: srv.Client(),
|
||||
Refresh: func() (string, error) { return "fresh", nil }}
|
||||
|
||||
if _, err := c.CreatePR("unkin/repo", CreatePROptions{Base: "main", Head: "feature", Title: "T", Body: "B"}); err != nil {
|
||||
t.Fatalf("CreatePR: %v", err)
|
||||
}
|
||||
if len(bodies) != 2 {
|
||||
t.Fatalf("requests = %d, want 2", len(bodies))
|
||||
}
|
||||
if bodies[1] != bodies[0] {
|
||||
t.Errorf("replayed body = %+v, want %+v", bodies[1], bodies[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsAuthError(t *testing.T) {
|
||||
tests := []struct {
|
||||
status int
|
||||
want bool
|
||||
}{
|
||||
{http.StatusUnauthorized, true},
|
||||
{http.StatusForbidden, true},
|
||||
{http.StatusNotFound, false},
|
||||
{http.StatusUnprocessableEntity, false},
|
||||
{http.StatusBadGateway, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
err := error(&APIError{Method: "GET", Path: "/p", StatusCode: tt.status})
|
||||
if got := IsAuthError(err); got != tt.want {
|
||||
t.Errorf("IsAuthError(HTTP %d) = %v, want %v", tt.status, got, tt.want)
|
||||
}
|
||||
}
|
||||
if IsAuthError(errors.New("dial tcp: timeout")) {
|
||||
t.Errorf("a network error is not an auth error")
|
||||
}
|
||||
}
|
||||
|
||||
// Anonymous polling of a public repo is a supported mode: with no token the
|
||||
// client must send no Authorization header, and must never reach for Vault.
|
||||
func TestAnonymousPollingNeverMints(t *testing.T) {
|
||||
authHeaders := 0
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/repos/unkin/repo/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "" {
|
||||
authHeaders++
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"number":7,"state":"open","mergeable":true,"head":{"sha":"cafebabe"}}`)
|
||||
})
|
||||
mux.HandleFunc("/api/v1/repos/unkin/repo/commits/cafebabe/status", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.WriteString(w, `{"state":"success"}`)
|
||||
})
|
||||
mux.HandleFunc("/api/v1/repos/unkin/repo/issues/7/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.WriteString(w, `[]`)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
refreshes := 0
|
||||
c := &GiteaClient{BaseURL: srv.URL, HTTP: srv.Client(),
|
||||
Refresh: func() (string, error) { refreshes++; return "", errors.New("vault unreachable") }}
|
||||
|
||||
st, err := FetchState(c, PRRef{Owner: "unkin", Repo: "repo", Number: 7}, "unkin-agent")
|
||||
if err != nil {
|
||||
t.Fatalf("anonymous FetchState: %v", err)
|
||||
}
|
||||
if st.State != "open" || st.CIStatus != "success" || st.HeadSHA != "cafebabe" {
|
||||
t.Errorf("state = %+v", st)
|
||||
}
|
||||
if refreshes != 0 {
|
||||
t.Errorf("refreshes = %d, want 0 (a 200 must never trigger a mint)", refreshes)
|
||||
}
|
||||
if authHeaders != 0 {
|
||||
t.Errorf("sent %d Authorization headers, want none", authHeaders)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user