Skip to content

CLOUDP-330236: Adds NewServiceAccountTransport #4075

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

Merged
merged 3 commits into from
Aug 1, 2025
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: 1 addition & 0 deletions build/ci/library_owners.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"go.uber.org/mock": "apix-2",
"golang.org/x/mod": "apix-2",
"golang.org/x/net": "apix-2",
"golang.org/x/oauth2": "apix-2",
"golang.org/x/sys": "apix-2",
"golang.org/x/tools": "apix-2",
"google.golang.org/api": "apix-2",
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ require (
go.uber.org/multierr v1.11.0 // indirect
go4.org v0.0.0-20230225012048-214862532bf5 // indirect
golang.org/x/crypto v0.40.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/oauth2 v0.30.0
golang.org/x/sync v0.16.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
Expand Down
18 changes: 18 additions & 0 deletions internal/transport/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,17 @@
package transport

import (
"context"
"net"
"net/http"
"time"

"github.com/mongodb-forks/digest"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/oauth"
"go.mongodb.org/atlas-sdk/v20250312005/auth/clientcredentials"
atlasauth "go.mongodb.org/atlas/auth"
"golang.org/x/oauth2"
)

const (
Expand Down Expand Up @@ -110,3 +113,18 @@ func (tr *tokenTransport) RoundTrip(req *http.Request) (*http.Response, error) {

return tr.base.RoundTrip(req)
}

func NewServiceAccountTransport(clientID, clientSecret string, base http.RoundTripper) (http.RoundTripper, error) {
cfg := clientcredentials.NewConfig(clientID, clientSecret)
if config.OpsManagerURL() != "" {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what if is "" ?

Copy link
Collaborator Author

@cveticm cveticm Aug 1, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clientcredentials.NewConfig already sets TokenURL and RevokeURL but points them to https://cloud.mongodb.com.

So this logic is to ensure we point to the correct cloud environment if OpsManagerURL is pointing to dev or qa.

cfg.RevokeURL = config.OpsManagerURL() + "api/oauth/revoke"
cfg.TokenURL = config.OpsManagerURL() + "api/oauth/token"
}

ctx := context.Background()

return &oauth2.Transport{
Base: base,
Source: cfg.TokenSource(ctx),
}, nil
}
88 changes: 88 additions & 0 deletions internal/transport/transport_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright 2025 MongoDB Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build unit

package transport

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/stretchr/testify/require"
"go.mongodb.org/atlas/auth"
)

func TestNewAccessTokenTransport(t *testing.T) {
mockToken := &auth.Token{
AccessToken: "mock-access-token",
RefreshToken: "mock-refresh-token",
}

saveToken := func(_ *auth.Token) error { return nil }

base := Default()
accessTokenTransport, err := NewAccessTokenTransport(mockToken, base, saveToken)
require.NoError(t, err)
require.NotNil(t, accessTokenTransport)

req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
resp, err := accessTokenTransport.RoundTrip(req)
require.NoError(t, err)
require.NotNil(t, resp)

authHeader := req.Header.Get("Authorization")
expectedHeader := "Bearer " + mockToken.AccessToken
require.Equal(t, expectedHeader, authHeader)
}

func TestNewServiceAccountTransport(t *testing.T) {
// Mock the token endpoint since the actual endpoint requires a valid client ID and secret.
tokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
if _, err := w.Write([]byte(`{"access_token":"mock-token","token_type":"bearer","expires_in":3600}`)); err != nil {
t.Errorf("Failed to write response: %v", err)
}
}))
defer tokenServer.Close()

// Temporarily set OpsManagerURL to mock tokenServer URL
originalURL := config.OpsManagerURL()
config.SetOpsManagerURL(tokenServer.URL + "/")
defer func() { config.SetOpsManagerURL(originalURL) }()

clientID := "mock-client-id"
clientSecret := "mock-client-secret" //nolint:gosec
base := http.DefaultTransport

tr, err := NewServiceAccountTransport(clientID, clientSecret, base)
require.NoError(t, err)
require.NotNil(t, tr)

// Create request to check authentication header
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("Authorization"); got != "Bearer mock-token" {
t.Errorf("Expected Authorization header to be 'Bearer mock-token', but got: %v", got)
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()

req := httptest.NewRequest(http.MethodGet, server.URL, nil)
resp, err := tr.RoundTrip(req)
require.NoError(t, err)
require.NotNil(t, resp)
}
Loading