Skip to content
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
68 changes: 68 additions & 0 deletions pkg/auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<!-- gomarkdoc:embed:start -->

<!-- Code generated by gomarkdoc. DO NOT EDIT -->

# auth

```go
import "github.com/greenbone/opensight-golang-libraries/pkg/auth"
```

Package auth provides a client to authenticate against a Keycloak server.

## Index

- [type KeycloakClient](<#KeycloakClient>)
- [func NewKeycloakClient\(httpClient \*http.Client, cfg KeycloakConfig\) \*KeycloakClient](<#NewKeycloakClient>)
- [func \(c \*KeycloakClient\) GetToken\(ctx context.Context\) \(string, error\)](<#KeycloakClient.GetToken>)
- [type KeycloakConfig](<#KeycloakConfig>)


<a name="KeycloakClient"></a>
## type [KeycloakClient](<https://github.com/greenbone/opensight-golang-libraries/blob/main/pkg/auth/auth_client.go#L42-L47>)

KeycloakClient can be used to authenticate against a Keycloak server.

```go
type KeycloakClient struct {
// contains filtered or unexported fields
}
```

<a name="NewKeycloakClient"></a>
### func [NewKeycloakClient](<https://github.com/greenbone/opensight-golang-libraries/blob/main/pkg/auth/auth_client.go#L50>)

```go
func NewKeycloakClient(httpClient *http.Client, cfg KeycloakConfig) *KeycloakClient
```

NewKeycloakClient creates a new KeycloakClient.

<a name="KeycloakClient.GetToken"></a>
### func \(\*KeycloakClient\) [GetToken](<https://github.com/greenbone/opensight-golang-libraries/blob/main/pkg/auth/auth_client.go#L60>)

```go
func (c *KeycloakClient) GetToken(ctx context.Context) (string, error)
```

GetToken retrieves a valid access token. The token is cached and refreshed before expiry. The token is obtained by \`Resource owner password credentials grant\` flow. Ref: https://www.keycloak.org/docs/latest/server_admin/index.html#_oidc-auth-flows-direct

<a name="KeycloakConfig"></a>
## type [KeycloakConfig](<https://github.com/greenbone/opensight-golang-libraries/blob/main/pkg/auth/auth_client.go#L23-L29>)

KeycloakConfig holds the credentials and configuration details

```go
type KeycloakConfig struct {
ClientID string
Username string
Password string
AuthURL string
KeycloakRealm string
}
```

Generated by [gomarkdoc](<https://github.com/princjef/gomarkdoc>)


<!-- gomarkdoc:embed:end -->
144 changes: 144 additions & 0 deletions pkg/auth/auth_client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// SPDX-FileCopyrightText: 2025 Greenbone AG <https://greenbone.net>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

// Package auth provides a client to authenticate against a Keycloak server.
package auth

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
)

type Clock interface {
Now() time.Time
}

type realClock struct{}

func (realClock) Now() time.Time { return time.Now() }

const tokenRefreshMargin = 10 * time.Second

// KeycloakConfig holds the credentials and configuration details
type KeycloakConfig struct {
ClientID string
Username string
Password string
AuthURL string
KeycloakRealm string
}

type tokenInfo struct {
AccessToken string
ExpiresAt time.Time
}

type authResponse struct {
Comment thread
mgoetzegb marked this conversation as resolved.
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"` // in seconds
Comment thread
mgoetzegb marked this conversation as resolved.
}

// KeycloakClient can be used to authenticate against a Keycloak server.
type KeycloakClient struct {
httpClient *http.Client
cfg KeycloakConfig
tokenInfo tokenInfo
tokenMutex sync.RWMutex

clock Clock // to mock time in tests
}

// NewKeycloakClient creates a new KeycloakClient.
func NewKeycloakClient(httpClient *http.Client, cfg KeycloakConfig) *KeycloakClient {
Comment thread
mgoetzegb marked this conversation as resolved.
return &KeycloakClient{
httpClient: httpClient,
cfg: cfg,
clock: realClock{},
}
}

// GetToken retrieves a valid access token. The token is cached and refreshed before expiry.
// The token is obtained by `Resource owner password credentials grant` flow.
// Ref: https://www.keycloak.org/docs/latest/server_admin/index.html#_oidc-auth-flows-direct
func (c *KeycloakClient) GetToken(ctx context.Context) (string, error) {
Comment thread
alex-heine marked this conversation as resolved.
token, ok := c.getCachedToken()
if ok {
return token, nil
}

// need to retrieve new token
c.tokenMutex.Lock()
Comment thread
alex-heine marked this conversation as resolved.
defer c.tokenMutex.Unlock()

// check again in case another goroutine already refreshed the token
if c.clock.Now().Before(c.tokenInfo.ExpiresAt.Add(-tokenRefreshMargin)) {
return c.tokenInfo.AccessToken, nil
}

authResponse, err := c.requestToken(ctx)
if err != nil {
return "", fmt.Errorf("failed to request token: %w", err)
}

c.tokenInfo = tokenInfo{
AccessToken: authResponse.AccessToken,
ExpiresAt: c.clock.Now().UTC().Add(time.Duration(authResponse.ExpiresIn) * time.Second),
}

return authResponse.AccessToken, nil
}

func (c *KeycloakClient) getCachedToken() (token string, ok bool) {
c.tokenMutex.RLock()
defer c.tokenMutex.RUnlock()
if c.clock.Now().Before(c.tokenInfo.ExpiresAt.Add(-tokenRefreshMargin)) {
return c.tokenInfo.AccessToken, true
}
return "", false
}

func (c *KeycloakClient) requestToken(ctx context.Context) (*authResponse, error) {
data := url.Values{}
data.Set("client_id", c.cfg.ClientID)
data.Set("password", c.cfg.Password)
data.Set("username", c.cfg.Username)
data.Set("grant_type", "password")

authenticationURL := fmt.Sprintf("%s/realms/%s/protocol/openid-connect/token",
c.cfg.AuthURL, c.cfg.KeycloakRealm)

req, err := http.NewRequestWithContext(ctx, http.MethodPost, authenticationURL, strings.NewReader(data.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to create authentication request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to execute authentication request: %w", err)
}
defer func() { _ = resp.Body.Close() }()

if resp.StatusCode != http.StatusOK {
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("authentication request failed with status: %s: %w body: %s", resp.Status, err, string(respBody))
}
return nil, fmt.Errorf("authentication request failed with status: %s: %s", resp.Status, string(respBody))
}

var authResp authResponse
if err := json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
return nil, fmt.Errorf("failed to parse authentication response: %w", err)
}
Comment thread
alex-heine marked this conversation as resolved.

return &authResp, nil
}
137 changes: 137 additions & 0 deletions pkg/auth/auth_client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// SPDX-FileCopyrightText: 2025 Greenbone AG <https://greenbone.net>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package auth

import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestKeycloakClient_GetToken(t *testing.T) {
tests := map[string]struct {
responseBody string
responseCode int
wantErr bool
wantToken string
}{
"successful token retrieval": {
responseBody: `{"access_token": "test-token", "expires_in": 3600}`,
responseCode: http.StatusOK,
wantErr: false,
wantToken: "test-token",
},
"failed authentication": {
responseBody: `{}`,
responseCode: http.StatusUnauthorized,
wantErr: true,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
var serverCallCount atomic.Int32
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
serverCallCount.Add(1)
w.WriteHeader(tt.responseCode)
_, err := w.Write([]byte(tt.responseBody))
require.NoError(t, err)
}))
defer mockServer.Close()

client := NewKeycloakClient(http.DefaultClient, KeycloakConfig{
AuthURL: mockServer.URL,
// the other fields are also required in real scenario, but omit here for brevity
})
gotToken, err := client.GetToken(context.Background())
assert.Greater(t, serverCallCount.Load(), int32(0), "server was not called")

if tt.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
assert.Equal(t, tt.wantToken, gotToken)
}
})
}
}

type fakeClock struct {
currentTime time.Time
}

func (fc *fakeClock) Now() time.Time {
return fc.currentTime
}

func (fc *fakeClock) Advance(d time.Duration) {
fc.currentTime = fc.currentTime.Add(d)
}

func NewFakeClock(startTime time.Time) *fakeClock {
return &fakeClock{currentTime: startTime}
}

func TestKeycloakClient_GetToken_Refresh(t *testing.T) {
tokenValidity := 60 * time.Second
kcMockResponse := []byte(fmt.Sprintf(`{"access_token": "test-token", "expires_in": %d}`, int(tokenValidity.Seconds())))

tests := map[string]struct {
responseBody string
responseCode int
requestAfter time.Duration
wantServerCalled int
wantToken string
}{
"token is cached": {
requestAfter: tokenValidity - tokenRefreshMargin - time.Nanosecond,
wantServerCalled: 1, // should be called only once due to caching
wantToken: "test-token",
},
"token expiry handling": {
requestAfter: tokenValidity - tokenRefreshMargin + time.Nanosecond,
wantServerCalled: 2, // should be called twice due to expiry
wantToken: "test-token",
},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
fakeClock := NewFakeClock(time.Now())

var serverCallCount atomic.Int32
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
serverCallCount.Add(1)
w.WriteHeader(200)
_, err := w.Write(kcMockResponse)
require.NoError(t, err)
}))
defer mockServer.Close()

client := NewKeycloakClient(http.DefaultClient, KeycloakConfig{
AuthURL: mockServer.URL,
// the other fields are also required in real scenario, but omit here for brevity
})
client.clock = fakeClock

_, err := client.GetToken(context.Background())
require.NoError(t, err)

fakeClock.Advance(tc.requestAfter)

gotToken, err := client.GetToken(context.Background()) // second call to test caching/refresh
require.NoError(t, err)

assert.Equal(t, tc.wantServerCalled, int(serverCallCount.Load()), "unexpected number of server calls")
assert.Equal(t, tc.wantToken, gotToken)
})
}
}
Loading
Loading