Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(oauth): Replace deprecated check_token usage with introspect #3385

Merged
merged 4 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .tool-versions
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ credhub 2.9.29
cf 8.8.3
concourse 7.10.0
direnv 2.35.0
gcloud 502.0.0
ginkgo 2.22.0
golang 1.22.5
golangci-lint 1.62.2
Expand Down
1 change: 0 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,6 @@ alerts-silence:
.PHONY: docker-login docker docker-image
docker-login: target/docker-login
target/docker-login:
gcloud auth login
docker login ghcr.io
@touch $@
docker-image: docker-login
Expand Down
3 changes: 1 addition & 2 deletions devbox.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,8 @@
"yq-go": "4.44.5",
"act": "0.2.68",
"cloudfoundry-cli": "8.8.1",
"google-cloud-sdk": "latest",
"ginkgo": "2.20.2",
"golangci-lint": "1.62.0",
"golangci-lint": "1.62.2",
"temurin-bin-21": "latest",
"ruby": "3.3.5"
},
Expand Down
80 changes: 16 additions & 64 deletions devbox.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"lockfile_version": "1",
"packages": {
"[email protected]": {
"last_modified": "2024-11-16T04:25:12Z",
"resolved": "github:NixOS/nixpkgs/34a626458d686f1b58139620a8b2793e9e123bba#act",
"last_modified": "2024-11-28T07:51:56Z",
"resolved": "github:NixOS/nixpkgs/226216574ada4c3ecefcbbec41f39ce4655f78ef#act",
"source": "devbox-search",
"version": "0.2.68",
"systems": {
Expand Down Expand Up @@ -901,99 +901,51 @@
}
}
},
"[email protected].0": {
"last_modified": "2024-11-16T04:25:12Z",
"resolved": "github:NixOS/nixpkgs/34a626458d686f1b58139620a8b2793e9e123bba#golangci-lint",
"[email protected].2": {
"last_modified": "2024-11-28T07:51:56Z",
"resolved": "github:NixOS/nixpkgs/226216574ada4c3ecefcbbec41f39ce4655f78ef#golangci-lint",
"source": "devbox-search",
"version": "1.62.0",
"version": "1.62.2",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/3n3m7z2y3wsgsd69r551jqqc1zrq8lwj-golangci-lint-1.62.0",
"path": "/nix/store/yp07jnqgrbnvdibqz1m2i1fgj30vhd2b-golangci-lint-1.62.2",
"default": true
}
],
"store_path": "/nix/store/3n3m7z2y3wsgsd69r551jqqc1zrq8lwj-golangci-lint-1.62.0"
"store_path": "/nix/store/yp07jnqgrbnvdibqz1m2i1fgj30vhd2b-golangci-lint-1.62.2"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/kcp7197947lansarn4x4ddnyh8m7hw0z-golangci-lint-1.62.0",
"path": "/nix/store/77qnd3ix2nrb8f5vppnv1pfd35h4vz04-golangci-lint-1.62.2",
"default": true
}
],
"store_path": "/nix/store/kcp7197947lansarn4x4ddnyh8m7hw0z-golangci-lint-1.62.0"
"store_path": "/nix/store/77qnd3ix2nrb8f5vppnv1pfd35h4vz04-golangci-lint-1.62.2"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/ymg3531fpln5b8bfwnf9gq7c1sr81f2y-golangci-lint-1.62.0",
"path": "/nix/store/ri36lilgaf8d4z2r96xfsk33162zrvwy-golangci-lint-1.62.2",
"default": true
}
],
"store_path": "/nix/store/ymg3531fpln5b8bfwnf9gq7c1sr81f2y-golangci-lint-1.62.0"
"store_path": "/nix/store/ri36lilgaf8d4z2r96xfsk33162zrvwy-golangci-lint-1.62.2"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/3vzfj43k05qsxdhiphw60j3gfvv6yhak-golangci-lint-1.62.0",
"path": "/nix/store/gr55w2x6wrzdvhhbzm4wc28cs4k7g7vr-golangci-lint-1.62.2",
"default": true
}
],
"store_path": "/nix/store/3vzfj43k05qsxdhiphw60j3gfvv6yhak-golangci-lint-1.62.0"
}
}
},
"google-cloud-sdk@latest": {
"last_modified": "2024-11-22T01:27:12Z",
"resolved": "github:NixOS/nixpkgs/8edf06bea5bcbee082df1b7369ff973b91618b8d#google-cloud-sdk",
"source": "devbox-search",
"version": "501.0.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8wq5wd1qkis3q44gvl91kdrbvmcx5rjc-google-cloud-sdk-501.0.0",
"default": true
}
],
"store_path": "/nix/store/8wq5wd1qkis3q44gvl91kdrbvmcx5rjc-google-cloud-sdk-501.0.0"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/bpdjikf06vw6q6pva89gfrnak4i9qbkd-google-cloud-sdk-501.0.0",
"default": true
}
],
"store_path": "/nix/store/bpdjikf06vw6q6pva89gfrnak4i9qbkd-google-cloud-sdk-501.0.0"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/jimm2rhh182spr2vz60k6wiqq9jwf7cr-google-cloud-sdk-501.0.0",
"default": true
}
],
"store_path": "/nix/store/jimm2rhh182spr2vz60k6wiqq9jwf7cr-google-cloud-sdk-501.0.0"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/qary2z3z06wf56aqhirxq39scz8rw0kh-google-cloud-sdk-501.0.0",
"default": true
}
],
"store_path": "/nix/store/qary2z3z06wf56aqhirxq39scz8rw0kh-google-cloud-sdk-501.0.0"
"store_path": "/nix/store/gr55w2x6wrzdvhhbzm4wc28cs4k7g7vr-golangci-lint-1.62.2"
}
}
},
Expand Down Expand Up @@ -1761,9 +1713,9 @@
}
},
"[email protected]": {
"last_modified": "2024-11-16T04:25:12Z",
"last_modified": "2024-11-28T07:51:56Z",
"plugin_version": "0.0.2",
"resolved": "github:NixOS/nixpkgs/34a626458d686f1b58139620a8b2793e9e123bba#ruby",
"resolved": "github:NixOS/nixpkgs/226216574ada4c3ecefcbbec41f39ce4655f78ef#ruby",
"source": "devbox-search",
"version": "3.3.5",
"systems": {
Expand Down
1 change: 0 additions & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@
go-tools
golangci-lint
gopls # See: <https://github.com/golang/vscode-go/blob/master/docs/tools.md>
google-cloud-sdk
jq
maven
nodejs
Expand Down
11 changes: 0 additions & 11 deletions renovate.json
Original file line number Diff line number Diff line change
Expand Up @@ -106,17 +106,6 @@
"datasourceTemplate": "github-releases",
"extractVersionTemplate": "^v(?<version>\\S+)"
},
{
"customType": "regex",
"fileMatch": [
"\\.tool-versions$"
],
"matchStrings": [
"(^|\\n)gcloud (?<currentValue>.+?)\\n"
],
"depNameTemplate": "google/cloud-sdk",
"datasourceTemplate": "docker"
},
{
"customType": "regex",
"fileMatch": [
Expand Down
50 changes: 37 additions & 13 deletions src/autoscaler/cf/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@ type (
}

IntrospectionResponse struct {
Active bool `json:"active"`
Email string `json:"email"`
ClientId string `json:"client_id"`
Active bool `json:"active"`
Email string `json:"email"`
ClientId string `json:"client_id"`
Scopes []string `json:"scope"`
}

AuthClient interface {
Expand Down Expand Up @@ -297,42 +298,65 @@ func (c *Client) IsTokenAuthorized(token, clientId string) (bool, error) {
return c.CtxClient.IsTokenAuthorized(context.Background(), token, clientId)
}
func (c *CtxClient) IsTokenAuthorized(ctx context.Context, token, clientId string) (bool, error) {
endpoints, err := c.GetEndpoints(ctx)
introspectionResponse, err := c.introspectToken(ctx, token)
if err != nil {
return false, err
}
if introspectionResponse.Active && introspectionResponse.ClientId == clientId {
return true, nil
}

return false, nil
}

func (c *CtxClient) introspectToken(ctx context.Context, token string) (*IntrospectionResponse, error) {
endpoints, err := c.GetEndpoints(ctx)
if err != nil {
return nil, err
}
formData := url.Values{"token": {token}}
tokenURL := endpoints.Uaa.Url + PathIntrospectToken
request, err := http.NewRequestWithContext(ctx, "POST", tokenURL, strings.NewReader(formData.Encode()))
if err != nil {
return false, err
return nil, err
}
request.SetBasicAuth(c.conf.ClientID, c.conf.Secret)

err = c.addAuth(ctx, request)
if err != nil {
return nil, err
}

request.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")

resp, err := c.Client.Do(request)
if err != nil {
return false, err
return nil, err
}
if resp.StatusCode != http.StatusOK {
return false, fmt.Errorf("received status code %v while calling /introspect endpoint", resp.Status)
return nil, fmt.Errorf("received status code %v while calling /introspect endpoint", resp.Status)
}
defer func() { _ = resp.Body.Close() }()

responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return false, err
return nil, err
}

introspectionResponse := &IntrospectionResponse{}
err = json.Unmarshal(responseBody, introspectionResponse)
if err != nil {
return false, err
return nil, err
}

if introspectionResponse.Active && introspectionResponse.ClientId == clientId {
return true, nil
return introspectionResponse, nil
}

func (c *CtxClient) addAuth(ctx context.Context, req *http.Request) error {
tokens, err := c.GetTokens(ctx)
if err != nil {
return fmt.Errorf("get token failed: %w", err)
}

return false, nil
req.Header.Set("Authorization", TokenTypeBearer+" "+tokens.AccessToken)
return nil
}
4 changes: 2 additions & 2 deletions src/autoscaler/cf/mocks/mocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,8 @@ func (a AddMock) UserInfo(statusCode int, testUserId string) AddMock {
return a
}

func (a AddMock) CheckToken(testUserScope []string) AddMock {
a.server.RouteToHandler(http.MethodPost, "/check_token",
func (a AddMock) Introspect(testUserScope []string) AddMock {
a.server.RouteToHandler(http.MethodPost, "/introspect",
ghttp.RespondWithJSONEncoded(http.StatusOK,
struct {
Scope []string `json:"scope"`
Expand Down
2 changes: 1 addition & 1 deletion src/autoscaler/cf/mocks/mocks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ var _ = Describe("Cf cloud controller", func() {
BeforeEach(func() {
testUserScope := []string{"cloud_controller.admin"}
mocks.Add().Info(mocks.URL())
mocks.Add().CheckToken(testUserScope).OauthToken("a-test-access-token")
mocks.Add().Introspect(testUserScope).OauthToken("a-test-access-token")
setCfcClient(0, mocks.URL())
DeferCleanup(mocks.Close)
})
Expand Down
54 changes: 2 additions & 52 deletions src/autoscaler/cf/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"

"code.cloudfoundry.org/lager/v3"
)
Expand Down Expand Up @@ -60,12 +58,12 @@ func (c *Client) IsUserAdmin(userToken string) (bool, error) {
return c.CtxClient.IsUserAdmin(context.Background(), userToken)
}
func (c *CtxClient) IsUserAdmin(ctx context.Context, userToken string) (bool, error) {
scopes, err := c.getUserScope(ctx, userToken)
introspectionResponse, err := c.introspectToken(ctx, userToken)
if err != nil {
return false, err
}

for _, scope := range scopes {
for _, scope := range introspectionResponse.Scopes {
if scope == CCAdminScope {
c.logger.Info("user is cc admin")
return true, nil
Expand All @@ -75,42 +73,6 @@ func (c *CtxClient) IsUserAdmin(ctx context.Context, userToken string) (bool, er
return false, nil
}

func (c *CtxClient) getUserScope(ctx context.Context, userToken string) ([]string, error) {
userScopeEndpoint, err := c.getUserScopeEndpoint(ctx, userToken)
if err != nil {
return nil, err
}

req, err := http.NewRequestWithContext(ctx, "POST", userScopeEndpoint, nil)
if err != nil {
c.logger.Error("Failed to create getuserscope request", err, lager.Data{"userScopeEndpoint": userScopeEndpoint})
return nil, err
}
req.SetBasicAuth(c.conf.ClientID, c.conf.Secret)

resp, err := c.Client.Do(req)
if err != nil {
c.logger.Error("Failed to getuserscope, request failed", err, lager.Data{"userScopeEndpoint": userScopeEndpoint})
return nil, err
}

defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
c.logger.Error("Failed to get user scope", nil, lager.Data{"userScopeEndpoint": userScopeEndpoint, "statusCode": resp.StatusCode})
return nil, fmt.Errorf("Failed to get user scope, statusCode : %v", resp.StatusCode)
}

userScope := struct {
Scope []string `json:"scope"`
}{}
err = json.NewDecoder(resp.Body).Decode(&userScope)
if err != nil {
c.logger.Error("Failed to parse user scope response body", err, lager.Data{"userScopeEndpoint": userScopeEndpoint})
return nil, err
}
return userScope.Scope, nil
}

func (c *CtxClient) getUserId(ctx context.Context, userToken string) (UserId, error) {
endpoints, err := c.GetEndpoints(ctx)
if err != nil {
Expand Down Expand Up @@ -167,15 +129,3 @@ func (c *CtxClient) getSpaceId(ctx context.Context, appId Guid) (SpaceId, error)

return spaceId, nil
}

func (c *CtxClient) getUserScopeEndpoint(ctx context.Context, userToken string) (string, error) {
parameters := url.Values{}
parameters.Add("token", strings.Split(userToken, " ")[1])

endpoints, err := c.GetEndpoints(ctx)
if err != nil {
return "", err
}
userScopeEndpoint := endpoints.Uaa.Url + "/check_token?" + parameters.Encode()
return userScopeEndpoint, nil
}
Loading
Loading