MCPcopy Create free account
hub / github.com/prometheus/common / TestOAuth2WithFile

Function TestOAuth2WithFile

config/http_config_test.go:2015–2095  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

2013}
2014
2015func TestOAuth2WithFile(t *testing.T) {
2016 expectedAuth := new(string)
2017 ts := newTestOAuthServer(t, func(t testing.TB, auth string) {
2018 require.Equalf(t, *expectedAuth, auth, "bad auth, expected %s, got %s", *expectedAuth, auth)
2019 })
2020 defer ts.close()
2021
2022 secretFile, err := os.CreateTemp("", "oauth2_secret")
2023 require.NoError(t, err)
2024 defer os.Remove(secretFile.Name())
2025
2026 yamlConfig := fmt.Sprintf(`
2027client_id: 1
2028client_secret_file: %s
2029scopes:
2030 - A
2031 - B
2032token_url: %s
2033endpoint_params:
2034 hi: hello
2035`, secretFile.Name(), ts.tokenURL())
2036 expectedConfig := OAuth2{
2037 ClientID: "1",
2038 ClientSecretFile: secretFile.Name(),
2039 Scopes: []string{"A", "B"},
2040 EndpointParams: map[string]string{"hi": "hello"},
2041 TokenURL: ts.tokenURL(),
2042 }
2043
2044 var unmarshalledConfig OAuth2
2045 err = yaml.Unmarshal([]byte(yamlConfig), &unmarshalledConfig)
2046 require.NoErrorf(t, err, "Expected no error unmarshalling yaml, got %v", err)
2047 require.Truef(t, reflect.DeepEqual(unmarshalledConfig, expectedConfig), "Got unmarshalled config %v, expected %v", unmarshalledConfig, expectedConfig)
2048
2049 secret := NewFileSecret(expectedConfig.ClientSecretFile)
2050 rt := NewOAuth2RoundTripper(secret, &expectedConfig, http.DefaultTransport)
2051
2052 client := http.Client{
2053 Transport: rt,
2054 }
2055
2056 // Empty secret file.
2057 *expectedAuth = "Basic MTo="
2058 resp, err := client.Get(ts.url())
2059 require.NoError(t, err)
2060
2061 authorization := resp.Request.Header.Get("Authorization")
2062 require.Equalf(t, "Bearer 12345", authorization, "Expected authorization header to be 'Bearer', got '%s'", authorization)
2063
2064 // Making a second request with the same file content should not re-call the token API.
2065 _, err = client.Get(ts.url())
2066 require.NoError(t, err)
2067
2068 // File populated.
2069 *expectedAuth = "Basic MToxMjM0NTY="
2070 _, err = secretFile.Write([]byte("123456"))
2071 require.NoError(t, err)
2072 resp, err = client.Get(ts.url())

Callers

nothing calls this directly

Calls 8

newTestOAuthServerFunction · 0.85
NewFileSecretFunction · 0.85
NewOAuth2RoundTripperFunction · 0.85
closeMethod · 0.80
tokenURLMethod · 0.80
GetMethod · 0.80
urlMethod · 0.80
NameMethod · 0.45

Tested by

no test coverage detected