Skip to content

Add support for OIDC token exchange in Access manager #1103

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 12 commits into from
Apr 6, 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
6 changes: 6 additions & 0 deletions access/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,9 @@ func (sm *AccessServicesManager) GetLoginAuthenticationToken(uuid string) (auth.
loginService.ServiceDetails = sm.config.GetServiceDetails()
return loginService.GetLoginAuthenticationToken(uuid)
}

func (sm *AccessServicesManager) ExchangeOidcToken(params services.CreateOidcTokenParams) (auth.OidcTokenResponseData, error) {
tokenService := services.NewTokenService(sm.client)
tokenService.ServiceDetails = sm.config.GetServiceDetails()
return tokenService.ExchangeOidcToken(params)
}
44 changes: 42 additions & 2 deletions access/services/accesstoken.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,13 @@ import (
"net/http"
)

// #nosec G101 jfrog-ignore -- False positive - no hardcoded credentials.
const tokensApi = "api/v1/tokens"
// #nosec G101 -- False positive - no hardcoded credentials.
const (
// jfrog-ignore - not a real token
tokensApi = "api/v1/tokens"
// jfrog-ignore - not a real token
oidcTokensApi = "api/v1/oidc/token"
)

type TokenService struct {
client *jfroghttpclient.JfrogHttpClient
Expand All @@ -27,6 +32,21 @@ type CreateTokenParams struct {
Description string `json:"description,omitempty"`
}

type CreateOidcTokenParams struct {
GrantType string `json:"grant_type,omitempty"`
SubjectTokenType string `json:"subject_token_type,omitempty"`
OidcTokenID string `json:"subject_token,omitempty"`
ProviderName string `json:"provider_name,omitempty"`
ProjectKey string `json:"project_key,omitempty"`
JobId string `json:"job_id,omitempty"`
RunId string `json:"run_id,omitempty"`
Repo string `json:"repo,omitempty"`
ApplicationKey string `json:"application_key,omitempty"`
Audience string `json:"audience,omitempty"`
IdentityMappingName string `json:"identity_mapping_name,omitempty"`
IncludeReferenceToken *bool `json:"include_reference_token,omitempty"`
}

func NewCreateTokenParams(params CreateTokenParams) CreateTokenParams {
return CreateTokenParams{CommonTokenParams: params.CommonTokenParams, IncludeReferenceToken: params.IncludeReferenceToken}
}
Expand Down Expand Up @@ -84,6 +104,26 @@ func (ps *TokenService) handleUnauthenticated(params CreateTokenParams, httpDeta
return errorutils.CheckErrorf("cannot create access token without credentials")
}

func (ps *TokenService) ExchangeOidcToken(params CreateOidcTokenParams) (auth.OidcTokenResponseData, error) {
var tokenInfo auth.OidcTokenResponseData
httpDetails := ps.ServiceDetails.CreateHttpClientDetails()
httpDetails.SetContentTypeApplicationJson()
requestContent, err := json.Marshal(params)
if errorutils.CheckError(err) != nil {
return tokenInfo, err
}
url := fmt.Sprintf("%s%s", ps.ServiceDetails.GetUrl(), oidcTokensApi)
resp, body, err := ps.client.SendPost(url, requestContent, &httpDetails)
if err != nil {
return tokenInfo, err
}
if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK); err != nil {
return tokenInfo, fmt.Errorf("failed to exchange OIDC token: %w", err)
}
err = json.Unmarshal(body, &tokenInfo)
return tokenInfo, errorutils.CheckError(err)
}

func prepareForRefresh(p CreateTokenParams) (*CreateTokenParams, error) {
// Validate provided parameters
if p.RefreshToken == "" {
Expand Down
6 changes: 6 additions & 0 deletions auth/authutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ type CreateTokenResponseData struct {
TokenId string `json:"token_id,omitempty"`
}

type OidcTokenResponseData struct {
CommonTokenParams
IssuedTokenType string `json:"issued_token_type,omitempty"`
Username string `json:"username,omitempty"`
}

type CommonTokenParams struct {
Scope string `json:"scope,omitempty"`
AccessToken string `json:"access_token,omitempty"`
Expand Down
87 changes: 87 additions & 0 deletions tests/accesstokens_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
package tests

import (
"encoding/json"
accessAuth "github.com/jfrog/jfrog-client-go/access/auth"
"github.com/jfrog/jfrog-client-go/access/services"
"github.com/jfrog/jfrog-client-go/auth"
"github.com/jfrog/jfrog-client-go/http/jfroghttpclient"
"github.com/jfrog/jfrog-client-go/utils"
"github.com/stretchr/testify/assert"
"io"
"net/http"
"net/http/httptest"
"testing"
)

Expand All @@ -15,6 +21,87 @@ func TestAccessTokens(t *testing.T) {
t.Run("createAccessToken", testCreateRefreshableToken)
t.Run("createAccessTokenWithReference", testAccessTokenWithReference)
t.Run("refreshToken", testRefreshTokenTest)
t.Run("exchangeOIDCToken", testExchangeOidcToken)
}

// This test uses a mock response because the subject_token (TokenID) is not available in the test environment
// and should be generated by the OIDC provider.
// Additionally, for this to work, the OIDC integration needs to be defined in the platform.
// This is not supported by CLI commands, The end-to-end tests for exchanging the OIDC token
// are implemented on the CLI side.
// Using a mock response here is necessary to simulate the OIDC token exchange process.
func testExchangeOidcToken(t *testing.T) {
initAccessTest(t)

// Create mock server
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method)
assert.Equal(t, "/access/api/v1/oidc/token", r.URL.Path)

// Verify request body
body, err := io.ReadAll(r.Body)
assert.NoError(t, err)
defer func() {
assert.NoError(t, r.Body.Close())
}()

var req services.CreateOidcTokenParams
err = json.Unmarshal(body, &req)
assert.NoError(t, err)
assert.Equal(t, "mockOidcTokenID", req.OidcTokenID)

// Simulate response
resp := auth.OidcTokenResponseData{
CommonTokenParams: auth.CommonTokenParams{
AccessToken: "mockAccessToken",
},
IssuedTokenType: "mockIssuedTokenType",
Username: "mockUsername",
}
responseBody, err := json.Marshal(resp)
assert.NoError(t, err)

w.WriteHeader(http.StatusOK)
_, err = w.Write(responseBody)
assert.NoError(t, err)
})
ts := httptest.NewServer(handler)
defer ts.Close()

// Setup JFrog client
client, err := jfroghttpclient.JfrogClientBuilder().
SetInsecureTls(true).
Build()
assert.NoError(t, err, "Failed to create JFrog client")

// Setup TokenService
service := services.NewTokenService(client)
serverDetails := accessAuth.NewAccessDetails()
serverDetails.SetUrl(ts.URL + "/access")
service.ServiceDetails = serverDetails

// Define OIDC token parameters
params := services.CreateOidcTokenParams{
GrantType: "authorization_code",
SubjectTokenType: "Generic",
OidcTokenID: "mockOidcTokenID",
ProviderName: "mockProviderName",
ProjectKey: "mockProjectKey",
JobId: "mockJobId",
RunId: "mockRunId",
Repo: "mockRepo",
ApplicationKey: "mockApplicationKey",
Audience: "mockAudience",
IdentityMappingName: "mockIdentityMappingName",
IncludeReferenceToken: utils.Pointer(false),
}

// Execute ExchangeOidcToken
response, err := service.ExchangeOidcToken(params)

// Verify response
assert.NoError(t, err)
assert.NotNil(t, response)
}

func testCreateRefreshableToken(t *testing.T) {
Expand Down