grafana/pkg/services/authn/clients/anonymous_test.go
Karl Persson 2e53a58bc3
Authn: Add client for api keys (#60339)
* AuthN: Add functionallity to test if auth client should be used

* AuthN: Add bolierplate client for api keys and register it

* AuthN: Add tests for api key client

* Inject service

* AuthN: Update client names

* ContextHandler: Set authn service

* AuthN: Implement authentication for api key client

* ContextHandler: Use authn service for api keys if flag is enabled

* AuthN: refactor authentication method to return additional value to
indicate if client could perform authentication

* update prefixes

* Add namespaced id to identity

* AuthN: Expand the Identity struct to include required fields from signed
in user

* Add error for disabled service account

* Add function to write error response based on errutil.Error

* Add error to log

* Return errors based on errutil.Error

* pass error

* update log message

* Fix namespaced ids

* Add tests

* Lint
2022-12-19 09:22:11 +01:00

67 lines
1.6 KiB
Go

package clients
import (
"context"
"fmt"
"testing"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/org/orgtest"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAnonymous_Authenticate(t *testing.T) {
type TestCase struct {
desc string
org *org.Org
cfg *setting.Cfg
err error
}
tests := []TestCase{
{
desc: "should success with valid org configured",
org: &org.Org{ID: 1, Name: "some org"},
cfg: &setting.Cfg{
AnonymousOrgName: "some org",
AnonymousOrgRole: "Viewer",
},
},
{
desc: "should return error if any error occurs during org lookup",
err: fmt.Errorf("some error"),
cfg: &setting.Cfg{
AnonymousOrgName: "some org",
AnonymousOrgRole: "Viewer",
},
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
c := Anonymous{
cfg: tt.cfg,
log: log.NewNopLogger(),
orgService: &orgtest.FakeOrgService{ExpectedOrg: tt.org, ExpectedError: tt.err},
}
identity, err := c.Authenticate(context.Background(), &authn.Request{})
if err != nil {
require.Error(t, err)
require.Nil(t, identity)
} else {
require.Nil(t, err)
assert.Equal(t, true, identity.ID == "")
assert.Equal(t, tt.org.ID, identity.OrgID)
assert.Equal(t, tt.org.Name, identity.OrgName)
assert.Equal(t, tt.cfg.AnonymousOrgRole, string(identity.Role()))
}
})
}
}