package auth import ( "crypto/rand" "crypto/rsa" "encoding/base64" "net/http" "net/http/httptest" "strconv" "sync/atomic" "testing" "time" "github.com/go-jose/go-jose/v4" "github.com/go-jose/go-jose/v4/jwt" "git.unkin.net/unkin/artifactapi/internal/testsupport" ) func serve(h http.Handler, method, token string) int { if token == "" { return serveAuth(h, method, "") } return serveAuth(h, method, "Bearer "+token) } func serveAuth(h http.Handler, method, authz string) int { r := httptest.NewRequest(method, "/x", nil) if authz != "" { r.Header.Set("Authorization", authz) } w := httptest.NewRecorder() h.ServeHTTP(w, r) return w.Code } func claims(iss string) jwt.Claims { now := time.Now() return jwt.Claims{ Issuer: iss, Subject: "ci", Audience: jwt.Audience{"artifactapi"}, IssuedAt: jwt.NewNumericDate(now.Add(-time.Minute)), Expiry: jwt.NewNumericDate(now.Add(time.Hour)), } } func hs256Token(t *testing.T, c jwt.Claims) string { sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: []byte("0123456789abcdef0123456789abcdef")}, (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", "k1")) if err != nil { t.Fatal(err) } tok, err := jwt.Signed(sig).Claims(c).Serialize() if err != nil { t.Fatal(err) } return tok } func noneToken(iss string) string { enc := base64.RawURLEncoding.EncodeToString return enc([]byte(`{"alg":"none","typ":"JWT","kid":"k1"}`)) + "." + enc([]byte(`{"iss":"`+iss+`","sub":"ci","aud":"artifactapi","exp":`+strconv.FormatInt(time.Now().Add(time.Hour).Unix(), 10)+`}`)) + "." } var ok = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) }) func TestBearerOIDC(t *testing.T) { iss := testsupport.NewOIDCIssuer() defer iss.Close() h := NewBearerOIDC(iss.URL, []string{"other", "artifactapi"}).Require(ok) otherKey, _ := rsa.GenerateKey(rand.Reader, 2048) cases := []struct { name string token string want int }{ {"valid", iss.Token(nil, "artifactapi", "ci", time.Hour), http.StatusNoContent}, {"missing", "", http.StatusUnauthorized}, {"garbage", "not.a.jwt", http.StatusUnauthorized}, {"bad signature", iss.Token(otherKey, "artifactapi", "ci", time.Hour), http.StatusUnauthorized}, {"wrong aud", iss.Token(nil, "nope", "ci", time.Hour), http.StatusUnauthorized}, {"expired", iss.Token(nil, "artifactapi", "ci", -time.Hour), http.StatusUnauthorized}, {"wrong iss", iss.Sign(nil, claims("https://evil.example")), http.StatusUnauthorized}, {"hs256", hs256Token(t, claims(iss.URL)), http.StatusUnauthorized}, {"alg none", noneToken(iss.URL), http.StatusUnauthorized}, } for _, c := range cases { if got := serve(h, http.MethodPost, c.token); got != c.want { t.Errorf("%s: status %d, want %d", c.name, got, c.want) } } valid := iss.Token(nil, "artifactapi", "ci", time.Hour) headers := []struct { name string authz string want int }{ {"lowercase scheme", "bearer " + valid, http.StatusNoContent}, {"extra whitespace", " Bearer " + valid + " ", http.StatusNoContent}, {"empty value", "Bearer ", http.StatusUnauthorized}, {"scheme only", "Bearer", http.StatusUnauthorized}, {"basic scheme", "Basic " + valid, http.StatusUnauthorized}, } for _, c := range headers { if got := serveAuth(h, http.MethodPost, c.authz); got != c.want { t.Errorf("%s: status %d, want %d", c.name, got, c.want) } } } func TestBearerOIDCHangingIssuerBacksOff(t *testing.T) { var hits atomic.Int32 release := make(chan struct{}) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hits.Add(1) select { case <-r.Context().Done(): case <-release: } })) defer srv.Close() defer close(release) b := NewBearerOIDC(srv.URL, nil) b.timeout = 100 * time.Millisecond b.backoff = time.Hour h := b.Require(ok) start := time.Now() if got := serve(h, http.MethodPost, "x.y.z"); got != http.StatusServiceUnavailable { t.Fatalf("hanging issuer: status %d, want 503", got) } if d := time.Since(start); d > 2*time.Second { t.Fatalf("hanging issuer: took %s, timeout not applied", d) } if got := serve(h, http.MethodPost, "x.y.z"); got != http.StatusServiceUnavailable { t.Fatalf("during backoff: status %d, want 503", got) } if n := hits.Load(); n != 1 { t.Fatalf("issuer hit %d times, want 1", n) } } func TestBearerOIDCRetriesAfterBackoff(t *testing.T) { iss := testsupport.NewOIDCIssuer() defer iss.Close() b := NewBearerOIDC(iss.URL, nil) b.failedAt = time.Now() b.backoff = 50 * time.Millisecond tok := iss.Token(nil, "artifactapi", "ci", time.Hour) if got := serve(b.Require(ok), http.MethodPost, tok); got != http.StatusServiceUnavailable { t.Fatalf("within backoff: status %d, want 503", got) } time.Sleep(60 * time.Millisecond) if got := serve(b.Require(ok), http.MethodPost, tok); got != http.StatusNoContent { t.Fatalf("after backoff: status %d, want 204", got) } } func TestBearerOIDCIssuerDown(t *testing.T) { iss := testsupport.NewOIDCIssuer() b := NewBearerOIDC(iss.URL, []string{"artifactapi"}) tok := iss.Token(nil, "artifactapi", "ci", time.Hour) iss.Close() if got := serve(b.Require(ok), http.MethodPost, tok); got != http.StatusServiceUnavailable { t.Errorf("issuer down: status %d, want 503", got) } } func TestBearerOIDCDisabled(t *testing.T) { if got := serve(NewBearerOIDC("", nil).RequireWrites(ok), http.MethodDelete, ""); got != http.StatusNoContent { t.Errorf("disabled: status %d, want 204", got) } } func TestRequireWritesLeavesReadsOpen(t *testing.T) { iss := testsupport.NewOIDCIssuer() defer iss.Close() h := NewBearerOIDC(iss.URL, []string{"artifactapi"}).RequireWrites(ok) for _, m := range []string{http.MethodGet, http.MethodHead, http.MethodOptions} { if got := serve(h, m, ""); got != http.StatusNoContent { t.Errorf("%s: status %d, want 204", m, got) } } for _, m := range []string{http.MethodPost, http.MethodPut, http.MethodDelete} { if got := serve(h, m, ""); got != http.StatusUnauthorized { t.Errorf("%s: status %d, want 401", m, got) } } }