github.com/distbuild/reclient@v0.0.0-20240401075343-3de72e395564/internal/pkg/auth/fakes/fakeadc.go (about)

     1  package fakes
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"strconv"
     8  	"testing"
     9  	"time"
    10  )
    11  
    12  // StartTokenValidationServer sets up a fake tokeninfo endpoint that responds with the given expiry for the given token.
    13  func StartTokenValidationServer(t *testing.T, exp time.Time, validToken string) string {
    14  	t.Helper()
    15  	fakeTokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    16  		switch r.URL.Path {
    17  		case "/tokeninfo":
    18  			token := r.URL.Query().Get("access_token")
    19  			if token != validToken {
    20  				t.Errorf("Expected query param access_token=%s, got access_token=%s", validToken, token)
    21  			}
    22  			resp := map[string]interface{}{
    23  				"exp": strconv.FormatInt(exp.Unix(), 10),
    24  			}
    25  			w.WriteHeader(http.StatusOK)
    26  			json.NewEncoder(w).Encode(resp)
    27  		case "/token":
    28  			resp := map[string]interface{}{
    29  				"access_token":  "adcToken",
    30  				"expires_in":    3600,
    31  				"refresh_token": "refresh",
    32  				"scope":         "https://www.googleapis.com/auth/pubsub",
    33  				"token_type":    "Bearer",
    34  			}
    35  			w.Header().Set("Content-Type", "application/json")
    36  			w.WriteHeader(http.StatusOK)
    37  			json.NewEncoder(w).Encode(resp)
    38  		default:
    39  			t.Errorf("Unexpected request path, got '%s'", r.URL.Path)
    40  		}
    41  	}))
    42  	t.Cleanup(fakeTokenServer.Close)
    43  	return fakeTokenServer.URL
    44  }