-
Notifications
You must be signed in to change notification settings - Fork 1
fix: notifications - cache token to avoid auth failure on repeated calls #273
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
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
4f48136
fix: notifications - cache token to avoid auth failure on repeated calls
mgoetzegb d33594b
code review: use ctx, split method, remove else, explicitly discard
mgoetzegb 2cf2bd1
code review changes
mgoetzegb 09868b1
make linter happy
mgoetzegb 41b2b64
code review changes
mgoetzegb dba7b37
fix test (add type conversion)
mgoetzegb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 --> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { | ||
| AccessToken string `json:"access_token"` | ||
| ExpiresIn int `json:"expires_in"` // in seconds | ||
|
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 { | ||
|
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) { | ||
|
alex-heine marked this conversation as resolved.
|
||
| token, ok := c.getCachedToken() | ||
| if ok { | ||
| return token, nil | ||
| } | ||
|
|
||
| // need to retrieve new token | ||
| c.tokenMutex.Lock() | ||
|
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) | ||
| } | ||
|
alex-heine marked this conversation as resolved.
|
||
|
|
||
| return &authResp, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| }) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.