Files
threshold/internal/tests/api/authmethods/authmethod_test.go
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

469 lines
17 KiB
Go
Raw Normal View History

// Copyright IBM Corp. 2020, 2026
// SPDX-License-Identifier: BUSL-1.1
2023-02-02 17:15:17 -08:00
2021-04-08 20:54:32 -04:00
package authmethods_test
import (
"fmt"
2021-04-08 20:54:32 -04:00
"net/http"
"os"
"sync"
2021-04-08 20:54:32 -04:00
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"repo.anhonesthost.net/CyberCoveLLC/threshold/api"
"repo.anhonesthost.net/CyberCoveLLC/threshold/api/authmethods"
"repo.anhonesthost.net/CyberCoveLLC/threshold/globals"
"repo.anhonesthost.net/CyberCoveLLC/threshold/internal/cmd/config"
"repo.anhonesthost.net/CyberCoveLLC/threshold/internal/daemon/controller"
"repo.anhonesthost.net/CyberCoveLLC/threshold/internal/event"
tests_api "repo.anhonesthost.net/CyberCoveLLC/threshold/internal/tests/api"
2021-04-08 20:54:32 -04:00
capoidc "github.com/hashicorp/cap/oidc"
"github.com/hashicorp/go-hclog"
2021-04-08 20:54:32 -04:00
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const global = "global"
func TestCrud(t *testing.T) {
assert, require := assert.New(t), require.New(t)
eventConfig := event.TestEventerConfig(t, "TestCrud", event.TestWithAuditSink(t))
testLock := &sync.Mutex{}
testLogger := hclog.New(&hclog.LoggerOptions{
Mutex: testLock,
Name: "test",
})
require.NoError(event.InitSysEventer(testLogger, testLock, "TestCrud", event.WithEventerConfig(&eventConfig.EventerConfig)))
tcConfig, err := config.DevController()
require.NoError(err)
tcConfig.Eventing = &eventConfig.EventerConfig
tc := controller.NewTestController(t, &controller.TestControllerOpts{Config: tcConfig})
2021-04-08 20:54:32 -04:00
client := tc.Client()
token := tc.Token()
client.SetToken(token.Token)
amClient := authmethods.NewClient(client)
checkAuthMethod := func(step string, u *authmethods.AuthMethod, wantedName string, wantedVersion uint32) {
require.NotNil(u, "returned no resource", step)
gotName := ""
if u.Name != "" {
gotName = u.Name
}
assert.Equal(wantedName, gotName, step)
assert.EqualValues(wantedVersion, u.Version)
}
require.NotNil(eventConfig.AuditEvents)
_ = os.WriteFile(eventConfig.AuditEvents.Name(), nil, 0o666) // clean out audit events from previous calls
pw, err := amClient.Create(tc.Context(), "password", global,
2021-04-08 20:54:32 -04:00
authmethods.WithName("bar"))
require.NoError(err)
t.Cleanup(func() {
_, err = amClient.Delete(tc.Context(), pw.Item.Id)
require.NoError(err)
})
checkAuthMethod("create", pw.Item, "bar", 1)
2021-04-08 20:54:32 -04:00
got := tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name())
2022-10-25 18:29:38 -05:00
reqItem := tests_api.GetEventDetails(t, got, "request")["item"].(map[string]any)
tests_api.AssertRedactedValues(t, reqItem)
tests_api.AssertRedactedValues(t, reqItem["Attrs"])
2022-10-25 18:29:38 -05:00
tests_api.AssertRedactedValues(t, reqItem["Attrs"].(map[string]any)["PasswordAuthMethodAttributes"])
2022-10-25 18:29:38 -05:00
respItem := tests_api.GetEventDetails(t, got, "response")["item"].(map[string]any)
tests_api.AssertRedactedValues(t, respItem)
tests_api.AssertRedactedValues(t, respItem["Attrs"])
2022-10-25 18:29:38 -05:00
tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]any)["PasswordAuthMethodAttributes"])
_ = os.WriteFile(eventConfig.AuditEvents.Name(), nil, 0o666) // clean out audit events from previous calls
pw, err = amClient.Read(tc.Context(), pw.Item.Id)
2021-04-08 20:54:32 -04:00
require.NoError(err)
checkAuthMethod("read", pw.Item, "bar", 1)
2021-04-08 20:54:32 -04:00
got = tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name())
tests_api.AssertRedactedValues(t, tests_api.GetEventDetails(t, got, "request"))
2022-10-25 18:29:38 -05:00
respItem = tests_api.GetEventDetails(t, got, "response")["item"].(map[string]any)
tests_api.AssertRedactedValues(t, respItem)
tests_api.AssertRedactedValues(t, respItem["Attrs"])
2022-10-25 18:29:38 -05:00
tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]any)["PasswordAuthMethodAttributes"])
_ = os.WriteFile(eventConfig.AuditEvents.Name(), nil, 0o666) // clean out audit events from previous calls
pw, err = amClient.Update(tc.Context(), pw.Item.Id, pw.Item.Version, authmethods.WithName("buz"))
2021-04-08 20:54:32 -04:00
require.NoError(err)
checkAuthMethod("update", pw.Item, "buz", 2)
got = tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name())
2022-10-25 18:29:38 -05:00
tests_api.AssertRedactedValues(t, tests_api.GetEventDetails(t, got, "request")["item"].(map[string]any))
2022-10-25 18:29:38 -05:00
respItem = tests_api.GetEventDetails(t, got, "response")["item"].(map[string]any)
tests_api.AssertRedactedValues(t, respItem)
tests_api.AssertRedactedValues(t, respItem["Attrs"])
2022-10-25 18:29:38 -05:00
tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]any)["PasswordAuthMethodAttributes"])
2021-04-08 20:54:32 -04:00
pw, err = amClient.Update(tc.Context(), pw.Item.Id, pw.Item.Version, authmethods.DefaultName())
2021-04-08 20:54:32 -04:00
require.NoError(err)
checkAuthMethod("update", pw.Item, "", 3)
2021-04-08 20:54:32 -04:00
_ = os.WriteFile(eventConfig.AuditEvents.Name(), nil, 0o666) // clean out audit events from previous calls
2021-04-08 20:54:32 -04:00
// OIDC auth methods
oidc, err := amClient.Create(tc.Context(), "oidc", global,
2021-04-08 20:54:32 -04:00
authmethods.WithName("foo"),
authmethods.WithOidcAuthMethodApiUrlPrefix("https://api.com"),
authmethods.WithOidcAuthMethodIssuer("https://example.com"),
authmethods.WithOidcAuthMethodClientSecret("secret"),
authmethods.WithOidcAuthMethodClientId("client-id"))
require.NoError(err)
t.Cleanup(func() {
_, err = amClient.Delete(tc.Context(), oidc.Item.Id)
require.NoError(err)
})
checkAuthMethod("create", oidc.Item, "foo", 1)
got = tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name())
2022-10-25 18:29:38 -05:00
reqItem = tests_api.GetEventDetails(t, got, "request")["item"].(map[string]any)
tests_api.AssertRedactedValues(t, reqItem)
tests_api.AssertRedactedValues(t, reqItem["Attrs"])
2022-10-25 18:29:38 -05:00
tests_api.AssertRedactedValues(t, reqItem["Attrs"].(map[string]any)["OidcAuthMethodsAttributes"])
2022-10-25 18:29:38 -05:00
respItem = tests_api.GetEventDetails(t, got, "response")["item"].(map[string]any)
tests_api.AssertRedactedValues(t, respItem)
tests_api.AssertRedactedValues(t, respItem["Attrs"])
2022-10-25 18:29:38 -05:00
tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]any)["OidcAuthMethodsAttributes"])
oidc, err = amClient.Read(tc.Context(), oidc.Item.Id)
require.NoError(err)
checkAuthMethod("read", oidc.Item, "foo", 1)
2021-04-08 20:54:32 -04:00
oidc, err = amClient.Update(tc.Context(), oidc.Item.Id, oidc.Item.Version, authmethods.WithName("bar"))
2021-04-08 20:54:32 -04:00
require.NoError(err)
checkAuthMethod("update", oidc.Item, "bar", 2)
2021-04-08 20:54:32 -04:00
oidc, err = amClient.Update(tc.Context(), oidc.Item.Id, oidc.Item.Version, authmethods.DefaultName())
require.NoError(err)
checkAuthMethod("update", oidc.Item, "", 3)
_ = os.WriteFile(eventConfig.AuditEvents.Name(), nil, 0o666) // clean out audit events from previous calls
// ldap auth methods
ldap, err := amClient.Create(tc.Context(), "ldap", global,
authmethods.WithName("ldap-foo"),
authmethods.WithLdapAuthMethodUrls([]string{"ldaps://ldap1"}),
authmethods.WithLdapAuthMethodBindDn("bind-dn"),
authmethods.WithLdapAuthMethodBindPassword("pass"))
require.NoError(err)
t.Cleanup(func() {
_, err = amClient.Delete(tc.Context(), ldap.Item.Id)
require.NoError(err)
})
checkAuthMethod("create", ldap.Item, "ldap-foo", 1)
got = tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name())
reqItem = tests_api.GetEventDetails(t, got, "request")["item"].(map[string]any)
tests_api.AssertRedactedValues(t, reqItem)
tests_api.AssertRedactedValues(t, reqItem["Attrs"])
tests_api.AssertRedactedValues(t, reqItem["Attrs"].(map[string]any)["LdapAuthMethodsAttributes"])
respItem = tests_api.GetEventDetails(t, got, "response")["item"].(map[string]any)
tests_api.AssertRedactedValues(t, respItem)
tests_api.AssertRedactedValues(t, respItem["Attrs"])
tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]any)["LdapAuthMethodsAttributes"])
ldap, err = amClient.Read(tc.Context(), ldap.Item.Id)
require.NoError(err)
checkAuthMethod("read", ldap.Item, "ldap-foo", 1)
ldap, err = amClient.Update(tc.Context(), ldap.Item.Id, ldap.Item.Version, authmethods.WithName("ldap-bar"))
require.NoError(err)
checkAuthMethod("update", ldap.Item, "ldap-bar", 2)
ldap, err = amClient.Update(tc.Context(), ldap.Item.Id, ldap.Item.Version, authmethods.DefaultName())
require.NoError(err)
checkAuthMethod("update", ldap.Item, "", 3)
}
func TestList(t *testing.T) {
assert, require := assert.New(t), require.New(t)
tcConfig, err := config.DevController()
require.NoError(err)
tc := controller.NewTestController(t, &controller.TestControllerOpts{Config: tcConfig})
client := tc.Client()
token := tc.Token()
client.SetToken(token.Token)
amClient := authmethods.NewClient(client)
result, err := amClient.List(tc.Context(), global)
require.NoError(err)
2023-05-02 18:00:24 -07:00
require.Len(result.Items, 3)
2023-12-21 14:58:21 -05:00
genLDAPAM := result.Items[0]
genOIDCAM := result.Items[1]
genPWAM := result.Items[2]
pwAM, err := amClient.Create(tc.Context(), "password", global,
authmethods.WithName("bar"),
authmethods.WithPasswordAuthMethodMinPasswordLength(10),
)
require.NoError(err)
t.Cleanup(func() {
_, err = amClient.Delete(tc.Context(), pwAM.Item.Id)
require.NoError(err)
})
result, err = amClient.List(tc.Context(), global)
require.NoError(err)
2023-05-02 18:00:24 -07:00
require.Len(result.Items, 4)
assert.Empty(
cmp.Diff(
result.Items,
2023-05-02 18:00:24 -07:00
[]*authmethods.AuthMethod{genOIDCAM, genPWAM, genLDAPAM, pwAM.Item},
cmpopts.IgnoreUnexported(authmethods.AuthMethod{}),
cmpopts.SortSlices(func(a, b *authmethods.AuthMethod) bool {
return a.Name < b.Name
}),
cmpopts.SortSlices(func(a, b string) bool {
return a < b
}),
),
)
oidcAM, err := amClient.Create(tc.Context(), "oidc", global,
authmethods.WithName("foo"),
authmethods.WithOidcAuthMethodApiUrlPrefix("https://api.com"),
authmethods.WithOidcAuthMethodIssuer("https://example.com"),
authmethods.WithOidcAuthMethodClientSecret("secret"),
authmethods.WithOidcAuthMethodClientId("client-id"))
require.NoError(err)
t.Cleanup(func() {
_, err = amClient.Delete(tc.Context(), oidcAM.Item.Id)
require.NoError(err)
})
result, err = amClient.List(tc.Context(), global)
require.NoError(err)
2023-05-02 18:00:24 -07:00
require.Len(result.Items, 5)
assert.Empty(
cmp.Diff(
result.Items,
2023-05-02 18:00:24 -07:00
[]*authmethods.AuthMethod{genOIDCAM, genPWAM, genLDAPAM, pwAM.Item, oidcAM.Item},
cmpopts.IgnoreUnexported(authmethods.AuthMethod{}),
cmpopts.SortSlices(func(a, b *authmethods.AuthMethod) bool {
return a.Name < b.Name
}),
cmpopts.SortSlices(func(a, b string) bool {
return a < b
}),
),
)
ldapAm, err := amClient.Create(tc.Context(), "ldap", global,
authmethods.WithName("ldap-foo"),
authmethods.WithLdapAuthMethodUrls([]string{"ldaps://ldap1"}))
require.NoError(err)
t.Cleanup(func() {
_, err = amClient.Delete(tc.Context(), ldapAm.Item.Id)
require.NoError(err)
})
result, err = amClient.List(tc.Context(), global)
require.NoError(err)
2023-05-02 18:00:24 -07:00
require.Len(result.Items, 6)
assert.Empty(
cmp.Diff(
result.Items,
2023-05-02 18:00:24 -07:00
[]*authmethods.AuthMethod{genOIDCAM, genPWAM, genLDAPAM, pwAM.Item, oidcAM.Item, ldapAm.Item},
cmpopts.IgnoreUnexported(authmethods.AuthMethod{}),
cmpopts.SortSlices(func(a, b *authmethods.AuthMethod) bool {
return a.Name < b.Name
}),
cmpopts.SortSlices(func(a, b string) bool {
return a < b
}),
),
)
result, err = amClient.List(tc.Context(), global,
authmethods.WithFilter(`"/item/attributes/client_id"=="client-id"`))
2021-04-08 20:54:32 -04:00
require.NoError(err)
require.Len(result.Items, 1)
assert.Empty(cmp.Diff(
oidcAM.Item,
result.Items[0],
cmpopts.IgnoreUnexported(authmethods.AuthMethod{}),
cmpopts.SortSlices(func(a, b string) bool {
return a < b
}),
))
2021-04-08 20:54:32 -04:00
result, err = amClient.List(tc.Context(), global,
authmethods.WithFilter(`"/item/attributes/min_login_name_length"==3`))
2021-04-08 20:54:32 -04:00
require.NoError(err)
require.Len(result.Items, 2)
assert.Empty(
cmp.Diff(
result.Items,
[]*authmethods.AuthMethod{genPWAM, pwAM.Item},
cmpopts.IgnoreUnexported(authmethods.AuthMethod{}),
cmpopts.SortSlices(func(a, b *authmethods.AuthMethod) bool {
return a.Name < b.Name
}),
cmpopts.SortSlices(func(a, b string) bool {
return a < b
}),
),
)
2021-04-08 20:54:32 -04:00
result, err = amClient.List(tc.Context(), global,
authmethods.WithFilter(`"/item/attributes/min_password_length"==10`))
2021-04-08 20:54:32 -04:00
require.NoError(err)
require.Len(result.Items, 1)
assert.Empty(cmp.Diff(
pwAM.Item,
result.Items[0],
cmpopts.IgnoreUnexported(authmethods.AuthMethod{}),
cmpopts.SortSlices(func(a, b string) bool {
return a < b
}),
))
2021-04-08 20:54:32 -04:00
}
func TestCustomMethods(t *testing.T) {
assert, require := assert.New(t), require.New(t)
eventConfig := event.TestEventerConfig(t, "TestCrud", event.TestWithAuditSink(t))
testLock := &sync.Mutex{}
testLogger := hclog.New(&hclog.LoggerOptions{
Mutex: testLock,
Name: "test",
})
require.NoError(event.InitSysEventer(testLogger, testLock, "TestCrud", event.WithEventerConfig(&eventConfig.EventerConfig)))
tcConfig, err := config.DevController()
require.NoError(err)
tcConfig.Eventing = &eventConfig.EventerConfig
tc := controller.NewTestController(t, &controller.TestControllerOpts{Config: tcConfig})
2021-04-08 20:54:32 -04:00
defer tc.Shutdown()
client := tc.Client()
token := tc.Token()
client.SetToken(token.Token)
amClient := authmethods.NewClient(client)
tp := capoidc.StartTestProvider(t)
tpClientId := "alice-rp"
tpClientSecret := "her-dog's-name"
tp.SetClientCreds(tpClientId, tpClientSecret)
u, err := amClient.Create(tc.Context(), "oidc", global,
authmethods.WithName("foo"),
authmethods.WithOidcAuthMethodIssuer(tp.Addr()),
authmethods.WithOidcAuthMethodApiUrlPrefix("https://example.com"),
authmethods.WithOidcAuthMethodClientSecret("secret"),
authmethods.WithOidcAuthMethodClientId("client-id"),
authmethods.WithOidcAuthMethodSigningAlgorithms([]string{string("EdDSA")}),
2021-04-08 20:54:32 -04:00
authmethods.WithOidcAuthMethodIdpCaCerts([]string{tp.CACert()}))
require.NoError(err)
2021-04-08 20:54:32 -04:00
const newState = "active-private"
nilU, err := amClient.ChangeState(tc.Context(), u.Item.Id, u.Item.Version, newState)
require.Error(err)
assert.Nil(nilU)
_ = os.WriteFile(eventConfig.AuditEvents.Name(), nil, 0o666) // clean out audit events from previous calls
u, err = amClient.ChangeState(tc.Context(), u.Item.Id, u.Item.Version, newState, authmethods.WithOidcAuthMethodDisableDiscoveredConfigValidation(true))
require.NoError(err)
assert.NotNil(u)
assert.Equal(newState, u.Item.Attributes["state"])
got := tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name())
reqDetails := tests_api.GetEventDetails(t, got, "request")
tests_api.AssertRedactedValues(t, reqDetails)
tests_api.AssertRedactedValues(t, reqDetails["Attrs"])
2022-10-25 18:29:38 -05:00
tests_api.AssertRedactedValues(t, reqDetails["Attrs"].(map[string]any)["OidcChangeStateAttributes"])
2022-10-25 18:29:38 -05:00
respItem := tests_api.GetEventDetails(t, got, "response")["item"].(map[string]any)
tests_api.AssertRedactedValues(t, respItem)
2022-10-25 18:29:38 -05:00
tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]any)["OidcAuthMethodsAttributes"])
2021-04-08 20:54:32 -04:00
_, err = amClient.ChangeState(tc.Context(), u.Item.Id, u.Item.Version, "", authmethods.WithOidcAuthMethodDisableDiscoveredConfigValidation(true))
assert.Error(err)
2021-04-08 20:54:32 -04:00
}
func TestErrors(t *testing.T) {
assert, require := assert.New(t), require.New(t)
tc := controller.NewTestController(t, nil)
defer tc.Shutdown()
client := tc.Client()
token := tc.Token()
client.SetToken(token.Token)
amClient := authmethods.NewClient(client)
u, err := amClient.Create(tc.Context(), "password", global,
authmethods.WithName("foo"))
require.NoError(err)
assert.NotNil(u)
// A malformed id is processed as the id and not a different path to the api.
_, err = amClient.Read(tc.Context(), fmt.Sprintf("%s/../", u.Item.Id))
require.Error(err)
apiErr := api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
require.Len(apiErr.Details.RequestFields, 1)
assert.Equal(apiErr.Details.RequestFields[0].Name, "id")
2021-04-08 20:54:32 -04:00
// Updating the wrong version should fail.
_, err = amClient.Update(tc.Context(), u.Item.Id, 73, authmethods.WithName("anything"))
require.Error(err)
apiErr = api.AsServerError(err)
2021-04-08 20:54:32 -04:00
require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
// Create another resource with the same name.
_, err = amClient.Create(tc.Context(), "password", global,
authmethods.WithName("foo"))
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
// TODO: Confirm that we can't create an oidc auth method with the same name.
_, err = amClient.Read(tc.Context(), globals.PasswordAuthMethodPrefix+"_doesntexis")
2021-04-08 20:54:32 -04:00
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = amClient.Read(tc.Context(), "invalid id")
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
_, err = amClient.Update(tc.Context(), u.Item.Id, u.Item.Version)
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
// Passing in a invalid authentication method sub-type should return an error
2022-10-25 18:29:38 -05:00
_, err = amClient.Authenticate(tc.Context(), "ampwd_1234567890", "login", map[string]any{
"login_name": "admin",
"password": "password",
})
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
assert.Len(apiErr.Details.RequestFields, 1)
assert.EqualValues(apiErr.Details.RequestFields, []*api.FieldError{
{
Name: "attributes",
Description: "unknown subtype in ID: ampwd_1234567890",
},
})
2021-04-08 20:54:32 -04:00
}