Move the server daemons into their own package (#2061)
* Move the server daemons into their own package With this change the internal/server package now is dedicated to the server domain (workers and controllers) and not to the server daemons. The hope is that this will make it easier to keep the daemons decoupled from the representation of the servers in the database.
This commit is contained in:
177 files changed
+275
-275
No files matched your search
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,396 @@
|
||||
package authmethods
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authmethods"
|
||||
pba "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authtokens"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/testing/protocmp"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
func TestTransformAuthenticateRequestAttributes(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name string
|
||||
input *pbs.AuthenticateRequest
|
||||
expected *pbs.AuthenticateRequest
|
||||
}{
|
||||
{
|
||||
name: "empty-request",
|
||||
input: &pbs.AuthenticateRequest{},
|
||||
expected: &pbs.AuthenticateRequest{},
|
||||
},
|
||||
{
|
||||
name: "password-attributes",
|
||||
input: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: "apw_test",
|
||||
Attrs: &pbs.AuthenticateRequest_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"login_name": structpb.NewStringValue("login-name"),
|
||||
"password": structpb.NewStringValue("password"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: "apw_test",
|
||||
Attrs: &pbs.AuthenticateRequest_PasswordLoginAttributes{
|
||||
PasswordLoginAttributes: &pbs.PasswordLoginAttributes{
|
||||
LoginName: "login-name",
|
||||
Password: "password",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "oidc-start-attributes",
|
||||
input: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: "amoidc_test",
|
||||
Command: "start",
|
||||
Attrs: &pbs.AuthenticateRequest_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"roundtrip_payload": structpb.NewStructValue(&structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"field1": structpb.NewBoolValue(true),
|
||||
"field2": structpb.NewStringValue("value2"),
|
||||
},
|
||||
}),
|
||||
"cached_roundtrip_payload": structpb.NewStringValue("cached-roundtrip-payload"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: "amoidc_test",
|
||||
Command: "start",
|
||||
Attrs: &pbs.AuthenticateRequest_OidcStartAttributes{
|
||||
OidcStartAttributes: &pbs.OidcStartAttributes{
|
||||
RoundtripPayload: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"field1": structpb.NewBoolValue(true),
|
||||
"field2": structpb.NewStringValue("value2"),
|
||||
},
|
||||
},
|
||||
CachedRoundtripPayload: "cached-roundtrip-payload",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "oidc-callback-attributes",
|
||||
input: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: "amoidc_test",
|
||||
Command: "callback",
|
||||
Attrs: &pbs.AuthenticateRequest_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"code": structpb.NewStringValue("code"),
|
||||
"state": structpb.NewStringValue("state"),
|
||||
"error": structpb.NewStringValue("error"),
|
||||
"error_description": structpb.NewStringValue("error-description"),
|
||||
"error_uri": structpb.NewStringValue("error-uri"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: "amoidc_test",
|
||||
Command: "callback",
|
||||
Attrs: &pbs.AuthenticateRequest_OidcAuthMethodAuthenticateCallbackRequest{
|
||||
OidcAuthMethodAuthenticateCallbackRequest: &pb.OidcAuthMethodAuthenticateCallbackRequest{
|
||||
Code: "code",
|
||||
State: "state",
|
||||
Error: "error",
|
||||
ErrorDescription: "error-description",
|
||||
ErrorUri: "error-uri",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "oidc-callback-attributes-with-extra-fields",
|
||||
input: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: "amoidc_test",
|
||||
Command: "callback",
|
||||
Attrs: &pbs.AuthenticateRequest_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"code": structpb.NewStringValue("code"),
|
||||
"state": structpb.NewStringValue("state"),
|
||||
"non-callback-field": structpb.NewBoolValue(true),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: "amoidc_test",
|
||||
Command: "callback",
|
||||
Attrs: &pbs.AuthenticateRequest_OidcAuthMethodAuthenticateCallbackRequest{
|
||||
OidcAuthMethodAuthenticateCallbackRequest: &pb.OidcAuthMethodAuthenticateCallbackRequest{
|
||||
Code: "code",
|
||||
State: "state",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "oidc-token-attributes",
|
||||
input: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: "amoidc_test",
|
||||
Command: "token",
|
||||
Attrs: &pbs.AuthenticateRequest_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"token_id": structpb.NewStringValue("token-id"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: "amoidc_test",
|
||||
Command: "token",
|
||||
Attrs: &pbs.AuthenticateRequest_OidcAuthMethodAuthenticateTokenRequest{
|
||||
OidcAuthMethodAuthenticateTokenRequest: &pb.OidcAuthMethodAuthenticateTokenRequest{
|
||||
TokenId: "token-id",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
c := c
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
in := proto.Clone(c.input)
|
||||
require.NoError(t, transformAuthenticateRequestAttributes(in))
|
||||
require.Empty(t, cmp.Diff(c.expected, in, protocmp.Transform()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransformAuthenticateRequestAttributesErrors(t *testing.T) {
|
||||
t.Parallel()
|
||||
t.Run("not-an-authenticate-request", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.Error(t, transformAuthenticateRequestAttributes(&pb.AuthMethod{}))
|
||||
})
|
||||
t.Run("invalid-auth-method-id", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.Error(t, transformAuthenticateRequestAttributes(&pbs.AuthenticateRequest{
|
||||
AuthMethodId: "invalid",
|
||||
Attrs: &pbs.AuthenticateRequest_Attributes{
|
||||
Attributes: &structpb.Struct{},
|
||||
},
|
||||
}))
|
||||
})
|
||||
t.Run("invalid-oidc-command", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.Error(t, transformAuthenticateRequestAttributes(&pbs.AuthenticateRequest{
|
||||
AuthMethodId: "amoidc_test",
|
||||
Command: "invalid",
|
||||
Attrs: &pbs.AuthenticateRequest_Attributes{
|
||||
Attributes: &structpb.Struct{},
|
||||
},
|
||||
}))
|
||||
})
|
||||
t.Run("invalid-password-attributes", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.Error(t, transformAuthenticateRequestAttributes(&pbs.AuthenticateRequest{
|
||||
AuthMethodId: "apw_test",
|
||||
Attrs: &pbs.AuthenticateRequest_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"field1": structpb.NewBoolValue(true),
|
||||
"field2": structpb.NewStringValue("value2"),
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
})
|
||||
t.Run("invalid-oidc-start-attributes", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.Error(t, transformAuthenticateRequestAttributes(&pbs.AuthenticateRequest{
|
||||
AuthMethodId: "amoidc_test",
|
||||
Command: "start",
|
||||
Attrs: &pbs.AuthenticateRequest_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"field1": structpb.NewBoolValue(true),
|
||||
"field2": structpb.NewStringValue("value2"),
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
})
|
||||
t.Run("invalid-oidc-token-attributes", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.Error(t, transformAuthenticateRequestAttributes(&pbs.AuthenticateRequest{
|
||||
AuthMethodId: "amoidc_test",
|
||||
Command: "token",
|
||||
Attrs: &pbs.AuthenticateRequest_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"field1": structpb.NewBoolValue(true),
|
||||
"field2": structpb.NewStringValue("value2"),
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
func TestTransformAuthenticateResponseAttributes(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name string
|
||||
input *pbs.AuthenticateResponse
|
||||
expected *pbs.AuthenticateResponse
|
||||
}{
|
||||
{
|
||||
name: "empty-attributes",
|
||||
input: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
},
|
||||
expected: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unstructured-attributes",
|
||||
input: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
Attrs: &pbs.AuthenticateResponse_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"field1": structpb.NewBoolValue(true),
|
||||
"field2": structpb.NewStringValue("value2"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
Attrs: &pbs.AuthenticateResponse_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"field1": structpb.NewBoolValue(true),
|
||||
"field2": structpb.NewStringValue("value2"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "authtoken-attributes",
|
||||
input: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
Attrs: &pbs.AuthenticateResponse_AuthTokenResponse{
|
||||
AuthTokenResponse: &pba.AuthToken{
|
||||
Id: "token-id",
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
Attrs: &pbs.AuthenticateResponse_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"id": structpb.NewStringValue("token-id"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "oidc-start-attributes",
|
||||
input: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
Attrs: &pbs.AuthenticateResponse_OidcAuthMethodAuthenticateStartResponse{
|
||||
OidcAuthMethodAuthenticateStartResponse: &pb.OidcAuthMethodAuthenticateStartResponse{
|
||||
AuthUrl: "auth-url",
|
||||
TokenId: "token-id",
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
Attrs: &pbs.AuthenticateResponse_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"auth_url": structpb.NewStringValue("auth-url"),
|
||||
"token_id": structpb.NewStringValue("token-id"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "oidc-callback-attributes",
|
||||
input: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
Attrs: &pbs.AuthenticateResponse_OidcAuthMethodAuthenticateCallbackResponse{
|
||||
OidcAuthMethodAuthenticateCallbackResponse: &pb.OidcAuthMethodAuthenticateCallbackResponse{
|
||||
FinalRedirectUrl: "final-redirect-url",
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
Attrs: &pbs.AuthenticateResponse_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"final_redirect_url": structpb.NewStringValue("final-redirect-url"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "oidc-token-attributes",
|
||||
input: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
Attrs: &pbs.AuthenticateResponse_OidcAuthMethodAuthenticateTokenResponse{
|
||||
OidcAuthMethodAuthenticateTokenResponse: &pb.OidcAuthMethodAuthenticateTokenResponse{
|
||||
Status: "status",
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: &pbs.AuthenticateResponse{
|
||||
Command: "testcommand",
|
||||
Attrs: &pbs.AuthenticateResponse_Attributes{
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"status": structpb.NewStringValue("status"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
c := c
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
in := proto.Clone(c.input)
|
||||
require.NoError(t, transformAuthenticateResponseAttributes(in))
|
||||
require.Empty(t, cmp.Diff(c.expected, in, protocmp.Transform()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransformAuthenticateResponseAttributesErrors(t *testing.T) {
|
||||
t.Parallel()
|
||||
t.Run("not-an-authenticate-response", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.Error(t, transformAuthenticateResponseAttributes(&pb.AuthMethod{}))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
package authmethods
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/auth/oidc"
|
||||
oidcstore "github.com/hashicorp/boundary/internal/auth/oidc/store"
|
||||
"github.com/hashicorp/boundary/internal/daemon/controller/auth"
|
||||
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/observability/event"
|
||||
"github.com/hashicorp/boundary/internal/types/action"
|
||||
pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authmethods"
|
||||
"google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
const (
|
||||
// commands
|
||||
startCommand = "start"
|
||||
callbackCommand = "callback"
|
||||
tokenCommand = "token"
|
||||
|
||||
// token request/response fields
|
||||
statusField = "status"
|
||||
|
||||
// field names
|
||||
issuerField = "attributes.issuer"
|
||||
clientSecretField = "attributes.client_secret"
|
||||
clientIdField = "attributes.client_id"
|
||||
clientSecretHmacField = "attributes.client_secret_hmac"
|
||||
stateField = "attributes.state"
|
||||
callbackUrlField = "attributes.callback_url"
|
||||
apiUrlPrefixField = "attributes.api_url_prefix"
|
||||
idpCaCertsField = "attributes.idp_ca_certs"
|
||||
signingAlgorithmField = "attributes.signing_algorithms"
|
||||
disableDiscoveredConfigValidationField = "attributes.disable_discovered_config_validation"
|
||||
roundtripPayloadAttributesField = "attributes.roundtrip_payload"
|
||||
codeField = "attributes.code"
|
||||
claimsScopesField = "attributes.claims_scopes"
|
||||
accountClaimMapsField = "attributes.account_claim_maps"
|
||||
)
|
||||
|
||||
var oidcMaskManager handlers.MaskManager
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if oidcMaskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&oidcstore.AuthMethod{}}, handlers.MaskSource{&pb.AuthMethod{}, &pb.OidcAuthMethodAttributes{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
IdActions[oidc.Subtype] = action.ActionSet{
|
||||
action.NoOp,
|
||||
action.Read,
|
||||
action.Update,
|
||||
action.Delete,
|
||||
action.ChangeState,
|
||||
action.Authenticate,
|
||||
}
|
||||
}
|
||||
|
||||
type oidcState uint
|
||||
|
||||
const (
|
||||
_ oidcState = iota
|
||||
inactiveState
|
||||
privateState
|
||||
publicState
|
||||
)
|
||||
|
||||
var oidcStateMap = map[string]oidcState{
|
||||
inactiveState.String(): inactiveState,
|
||||
privateState.String(): privateState,
|
||||
publicState.String(): publicState,
|
||||
}
|
||||
|
||||
func (o oidcState) String() string {
|
||||
return [...]string{
|
||||
"unknown",
|
||||
"inactive",
|
||||
"active-private",
|
||||
"active-public",
|
||||
}[o]
|
||||
}
|
||||
|
||||
// createOidcInRepo creates an oidc auth method in a repo and returns the result.
|
||||
// This method should never return a nil AuthMethod without returning an error.
|
||||
func (s Service) createOidcInRepo(ctx context.Context, scopeId string, item *pb.AuthMethod) (*oidc.AuthMethod, error) {
|
||||
u, _, _, err := toStorageOidcAuthMethod(ctx, scopeId, item)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
repo, err := s.oidcRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, err := repo.CreateAuthMethod(ctx, u)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to create auth method: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s Service) updateOidcInRepo(ctx context.Context, scopeId string, req *pbs.UpdateAuthMethodRequest) (*oidc.AuthMethod, bool, error) {
|
||||
item := req.GetItem()
|
||||
u, dryRun, forced, err := toStorageOidcAuthMethod(ctx, scopeId, item)
|
||||
if err != nil {
|
||||
return nil, dryRun, err
|
||||
}
|
||||
u.PublicId = req.GetId()
|
||||
|
||||
var opts []oidc.Option
|
||||
if forced {
|
||||
opts = append(opts, oidc.WithForce())
|
||||
}
|
||||
if dryRun {
|
||||
opts = append(opts, oidc.WithDryRun())
|
||||
}
|
||||
|
||||
version := item.GetVersion()
|
||||
dbMask := oidcMaskManager.Translate(req.GetUpdateMask().GetPaths())
|
||||
if len(dbMask) == 0 {
|
||||
return nil, dryRun, handlers.InvalidArgumentErrorf("No valid fields included in the update mask.", map[string]string{"update_mask": "No valid fields provided in the update mask."})
|
||||
}
|
||||
|
||||
repo, err := s.oidcRepoFn()
|
||||
if err != nil {
|
||||
return nil, dryRun, err
|
||||
}
|
||||
out, rowsUpdated, err := repo.UpdateAuthMethod(ctx, u, version, dbMask, opts...)
|
||||
if err != nil {
|
||||
return nil, dryRun, fmt.Errorf("unable to update auth method: %w", err)
|
||||
}
|
||||
if rowsUpdated == 0 && !dryRun && out == nil {
|
||||
return nil, dryRun, handlers.NotFoundErrorf("AuthMethod %q doesn't exist or incorrect version provided.", req.GetId())
|
||||
}
|
||||
return out, dryRun, nil
|
||||
}
|
||||
|
||||
func (s Service) authenticateOidc(ctx context.Context, req *pbs.AuthenticateRequest, authResults *auth.VerifyResults) (*pbs.AuthenticateResponse, error) {
|
||||
const op = "authmethod_service.(Service).authenticateOidc"
|
||||
if req == nil {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request.")
|
||||
}
|
||||
if authResults == nil {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil auth results.")
|
||||
}
|
||||
switch req.GetCommand() {
|
||||
case startCommand:
|
||||
return s.authenticateOidcStart(ctx, req)
|
||||
case callbackCommand:
|
||||
return s.authenticateOidcCallback(ctx, req)
|
||||
case tokenCommand:
|
||||
return s.authenticateOidcToken(ctx, req, authResults)
|
||||
}
|
||||
|
||||
return &pbs.AuthenticateResponse{Command: req.GetCommand()}, nil
|
||||
}
|
||||
|
||||
func (s Service) authenticateOidcStart(ctx context.Context, req *pbs.AuthenticateRequest) (*pbs.AuthenticateResponse, error) {
|
||||
const op = "authmethod_service.(Service).authenticateOidcStart"
|
||||
if req == nil {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request.")
|
||||
}
|
||||
|
||||
var opts []oidc.Option
|
||||
attrs := req.GetOidcStartAttributes()
|
||||
if attrs.GetCachedRoundtripPayload() != "" {
|
||||
opts = append(opts, oidc.WithRoundtripPayload(attrs.GetCachedRoundtripPayload()))
|
||||
}
|
||||
|
||||
authUrl, tokenId, err := oidc.StartAuth(ctx, s.oidcRepoFn, req.GetAuthMethodId(), opts...)
|
||||
if err != nil {
|
||||
// this event.WriteError(...) may cause a dup error to be emitted...
|
||||
// it should be removed if that's the case.
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error starting the oidc authentication flow"))
|
||||
return nil, errors.New(ctx, errors.Internal, op, "Error generating parameters for starting the OIDC flow. See the controller's log for more information.")
|
||||
}
|
||||
|
||||
return &pbs.AuthenticateResponse{
|
||||
Command: req.GetCommand(),
|
||||
Attrs: &pbs.AuthenticateResponse_OidcAuthMethodAuthenticateStartResponse{
|
||||
OidcAuthMethodAuthenticateStartResponse: &pb.OidcAuthMethodAuthenticateStartResponse{
|
||||
AuthUrl: authUrl.String(),
|
||||
TokenId: tokenId,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// authenticateOidcCallback behaves differently than other service methods.
|
||||
// Because of the way it this is called by the end user, it should only return
|
||||
// an error if we are unable to lookup the auth method or the request
|
||||
// parameters were invalid. All other errors should be returned back through
|
||||
// the response as a finalRedirectUrl to an endpoint that can properly show the
|
||||
// error details.
|
||||
func (s Service) authenticateOidcCallback(ctx context.Context, req *pbs.AuthenticateRequest) (*pbs.AuthenticateResponse, error) {
|
||||
const op = "authmethod_service.(Service).authenticateOidcCallback"
|
||||
// TODO: Return all errors (including the validate request based errors
|
||||
// in the redirect URL once we start looking at the url used for this
|
||||
// request instead of requiring the API URL to be set on the auth method.
|
||||
if req == nil {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request.")
|
||||
}
|
||||
|
||||
repo, err := s.oidcRepoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
am, err := repo.LookupAuthMethod(ctx, req.GetAuthMethodId())
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(ctx, err, op)
|
||||
}
|
||||
if am == nil {
|
||||
return nil, errors.New(ctx, errors.RecordNotFound, op, fmt.Sprintf("Auth method %s not found.", req.GetAuthMethodId()))
|
||||
}
|
||||
if am.GetApiUrl() == "" {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "Auth method doesn't have API URL defined.")
|
||||
}
|
||||
|
||||
errRedirectBase := fmt.Sprintf(oidc.AuthenticationErrorsEndpoint, am.GetApiUrl())
|
||||
errResponse := func(err error) (*pbs.AuthenticateResponse, error) {
|
||||
u := make(url.Values)
|
||||
pbErr := handlers.ToApiError(err)
|
||||
out, err := handlers.JSONMarshaler().Marshal(pbErr)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to marshal the error for callback"))
|
||||
}
|
||||
u.Add("error", string(out))
|
||||
errRedirect := fmt.Sprintf("%s?%s", errRedirectBase, u.Encode())
|
||||
return &pbs.AuthenticateResponse{
|
||||
Command: callbackCommand,
|
||||
Attrs: &pbs.AuthenticateResponse_OidcAuthMethodAuthenticateCallbackResponse{
|
||||
OidcAuthMethodAuthenticateCallbackResponse: &pb.OidcAuthMethodAuthenticateCallbackResponse{
|
||||
FinalRedirectUrl: errRedirect,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
attrs := req.GetOidcAuthMethodAuthenticateCallbackRequest()
|
||||
|
||||
var finalRedirectUrl string
|
||||
if attrs.GetError() != "" {
|
||||
err := errors.Wrap(ctx, fmt.Errorf("Error: %q, Details: %q", attrs.GetError(), attrs.GetErrorDescription()), op, errors.WithCode(errors.OidcProviderCallbackError))
|
||||
return errResponse(err)
|
||||
}
|
||||
finalRedirectUrl, err = oidc.Callback(
|
||||
ctx,
|
||||
s.oidcRepoFn,
|
||||
oidc.IamRepoFactory(s.iamRepoFn),
|
||||
s.atRepoFn,
|
||||
am,
|
||||
attrs.GetState(),
|
||||
attrs.GetCode())
|
||||
if err != nil {
|
||||
return errResponse(errors.New(ctx, errors.InvalidParameter, op, "Callback validation failed.", errors.WithWrap(err)))
|
||||
}
|
||||
|
||||
return &pbs.AuthenticateResponse{
|
||||
Command: req.GetCommand(),
|
||||
Attrs: &pbs.AuthenticateResponse_OidcAuthMethodAuthenticateCallbackResponse{
|
||||
OidcAuthMethodAuthenticateCallbackResponse: &pb.OidcAuthMethodAuthenticateCallbackResponse{
|
||||
FinalRedirectUrl: finalRedirectUrl,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s Service) authenticateOidcToken(ctx context.Context, req *pbs.AuthenticateRequest, authResults *auth.VerifyResults) (*pbs.AuthenticateResponse, error) {
|
||||
const op = "authmethod_service.(Service).authenticateOidcToken"
|
||||
if req == nil {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request.")
|
||||
}
|
||||
if authResults == nil {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil auth results.")
|
||||
}
|
||||
if req.GetOidcAuthMethodAuthenticateTokenRequest() == nil {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request attributes.")
|
||||
}
|
||||
|
||||
attrs := req.GetOidcAuthMethodAuthenticateTokenRequest()
|
||||
if attrs.TokenId == "" {
|
||||
return nil, errors.New(ctx, errors.InvalidParameter, op, "Empty token ID in request attributes.")
|
||||
}
|
||||
|
||||
token, err := oidc.TokenRequest(ctx, s.kms, s.atRepoFn, req.GetAuthMethodId(), attrs.TokenId)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Match(errors.T(errors.Forbidden), err):
|
||||
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("Forbidden."))
|
||||
case errors.Match(errors.T(errors.AuthAttemptExpired), err):
|
||||
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("Forbidden."))
|
||||
default:
|
||||
// this event.WriteError(...) may cause a dup error to be emitted...
|
||||
// it should be removed if that's the case.
|
||||
event.WriteError(ctx, op, err, event.WithInfoMsg("error generating parameters for token request"))
|
||||
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("Error generating parameters for token request. See the controller's log for more information."))
|
||||
}
|
||||
}
|
||||
if token == nil {
|
||||
if err != nil {
|
||||
return nil, errors.New(ctx, errors.Internal, op, "Error generating response attributes.", errors.WithWrap(err))
|
||||
}
|
||||
return &pbs.AuthenticateResponse{
|
||||
Command: req.Command,
|
||||
Attrs: &pbs.AuthenticateResponse_OidcAuthMethodAuthenticateTokenResponse{
|
||||
OidcAuthMethodAuthenticateTokenResponse: &pb.OidcAuthMethodAuthenticateTokenResponse{
|
||||
Status: "unknown",
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
responseToken, err := s.ConvertInternalAuthTokenToApiAuthToken(
|
||||
ctx,
|
||||
token,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.New(ctx, errors.Internal, op, "Error converting response to proper format.", errors.WithWrap(err))
|
||||
}
|
||||
return s.convertToAuthenticateResponse(ctx, req, authResults, responseToken)
|
||||
}
|
||||
|
||||
func validateAuthenticateOidcRequest(req *pbs.AuthenticateRequest) error {
|
||||
badFields := make(map[string]string)
|
||||
|
||||
switch req.GetCommand() {
|
||||
case startCommand:
|
||||
if req.GetOidcStartAttributes() != nil {
|
||||
attrs := req.GetOidcStartAttributes()
|
||||
|
||||
// Ensure we pay no attention to cache information provided by the client
|
||||
attrs.CachedRoundtripPayload = ""
|
||||
|
||||
payload := attrs.GetRoundtripPayload()
|
||||
if payload == nil {
|
||||
break
|
||||
}
|
||||
m, err := json.Marshal(payload.AsMap())
|
||||
if err != nil {
|
||||
// We don't know what's in this payload so we swallow the
|
||||
// error, as it could be something sensitive.
|
||||
badFields[roundtripPayloadAttributesField] = "Unable to marshal given value as JSON."
|
||||
} else {
|
||||
// Cache for later
|
||||
attrs.CachedRoundtripPayload = string(m)
|
||||
}
|
||||
}
|
||||
case callbackCommand:
|
||||
attrs := req.GetOidcAuthMethodAuthenticateCallbackRequest()
|
||||
|
||||
if attrs.GetCode() == "" && attrs.GetError() == "" {
|
||||
badFields[codeField] = "Code field not supplied in callback request."
|
||||
}
|
||||
|
||||
if attrs.GetState() == "" {
|
||||
badFields[stateField] = "State field not supplied in callback request."
|
||||
}
|
||||
|
||||
case tokenCommand:
|
||||
tokenType := req.GetType()
|
||||
if tokenType == "" {
|
||||
// Fall back to deprecated field if type is not set
|
||||
tokenType = req.GetTokenType()
|
||||
}
|
||||
tType := strings.ToLower(strings.TrimSpace(tokenType))
|
||||
if tType != "" && tType != "token" && tType != "cookie" {
|
||||
badFields[tokenTypeField] = `The only accepted types are "token" and "cookie".`
|
||||
}
|
||||
|
||||
default:
|
||||
badFields[commandField] = "Invalid command for this auth method type."
|
||||
}
|
||||
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Invalid fields provided in request.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func toStorageOidcAuthMethod(ctx context.Context, scopeId string, in *pb.AuthMethod) (out *oidc.AuthMethod, dryRun, forced bool, err error) {
|
||||
const op = "authmethod_service.toStorageOidcAuthMethod"
|
||||
if in == nil {
|
||||
return nil, false, false, errors.NewDeprecated(errors.InvalidParameter, op, "nil auth method.")
|
||||
}
|
||||
attrs := in.GetOidcAuthMethodsAttributes()
|
||||
clientId := attrs.GetClientId().GetValue()
|
||||
clientSecret := oidc.ClientSecret(attrs.GetClientSecret().GetValue())
|
||||
|
||||
var opts []oidc.Option
|
||||
if in.GetName() != nil {
|
||||
opts = append(opts, oidc.WithName(in.GetName().GetValue()))
|
||||
}
|
||||
if in.GetDescription() != nil {
|
||||
opts = append(opts, oidc.WithDescription(in.GetDescription().GetValue()))
|
||||
}
|
||||
|
||||
if iss := strings.TrimSpace(attrs.GetIssuer().GetValue()); iss != "" {
|
||||
// Strip off everything after and including ".well-known/openid-configuration"
|
||||
// but leave the "/" attached to the end.
|
||||
iss = strings.SplitN(iss, ".well-known/", 2)[0]
|
||||
issuer, err := url.Parse(iss)
|
||||
if err != nil {
|
||||
return nil, false, false, errors.WrapDeprecated(err, op, errors.WithMsg("cannot parse issuer"), errors.WithCode(errors.InvalidParameter))
|
||||
}
|
||||
opts = append(opts, oidc.WithIssuer(issuer))
|
||||
}
|
||||
if apiUrl := strings.TrimSpace(attrs.GetApiUrlPrefix().GetValue()); apiUrl != "" {
|
||||
apiU, err := url.Parse(apiUrl)
|
||||
if err != nil {
|
||||
return nil, false, false, errors.WrapDeprecated(err, op, errors.WithMsg("cannot parse api_url_prefix"), errors.WithCode(errors.InvalidParameter))
|
||||
}
|
||||
opts = append(opts, oidc.WithApiUrl(apiU))
|
||||
}
|
||||
|
||||
if attrs.GetMaxAge() != nil {
|
||||
maxAge := attrs.GetMaxAge().GetValue()
|
||||
if maxAge == 0 {
|
||||
opts = append(opts, oidc.WithMaxAge(-1))
|
||||
} else {
|
||||
opts = append(opts, oidc.WithMaxAge(int(maxAge)))
|
||||
}
|
||||
}
|
||||
var signAlgs []oidc.Alg
|
||||
for _, a := range attrs.GetSigningAlgorithms() {
|
||||
signAlgs = append(signAlgs, oidc.Alg(a))
|
||||
}
|
||||
if len(signAlgs) > 0 {
|
||||
opts = append(opts, oidc.WithSigningAlgs(signAlgs...))
|
||||
}
|
||||
if len(attrs.GetAllowedAudiences()) > 0 {
|
||||
opts = append(opts, oidc.WithAudClaims(attrs.GetAllowedAudiences()...))
|
||||
}
|
||||
|
||||
if len(attrs.GetIdpCaCerts()) > 0 {
|
||||
certs, err := oidc.ParseCertificates(ctx, attrs.GetIdpCaCerts()...)
|
||||
if err != nil {
|
||||
return nil, false, false, err
|
||||
}
|
||||
opts = append(opts, oidc.WithCertificates(certs...))
|
||||
}
|
||||
|
||||
if len(attrs.GetClaimsScopes()) > 0 {
|
||||
opts = append(opts, oidc.WithClaimsScopes(attrs.GetClaimsScopes()...))
|
||||
}
|
||||
|
||||
if len(attrs.GetAccountClaimMaps()) > 0 {
|
||||
claimsMap := make(map[string]oidc.AccountToClaim, len(attrs.GetAccountClaimMaps()))
|
||||
for _, v := range attrs.GetAccountClaimMaps() {
|
||||
acm, err := oidc.ParseAccountClaimMaps(ctx, v)
|
||||
if err != nil {
|
||||
return nil, false, false, errors.WrapDeprecated(err, op)
|
||||
}
|
||||
if len(acm) > 1 {
|
||||
return nil, false, false, errors.NewDeprecated(errors.InvalidParameter, op, fmt.Sprintf("unable to parse account claim map %s", v))
|
||||
}
|
||||
var m oidc.ClaimMap
|
||||
for _, m = range acm {
|
||||
}
|
||||
to, err := oidc.ConvertToAccountToClaim(ctx, m.To)
|
||||
if err != nil {
|
||||
return nil, false, false, errors.WrapDeprecated(err, op)
|
||||
}
|
||||
claimsMap[m.From] = to
|
||||
}
|
||||
opts = append(opts, oidc.WithAccountClaimMap(claimsMap))
|
||||
}
|
||||
|
||||
u, err := oidc.NewAuthMethod(ctx, scopeId, clientId, clientSecret, opts...)
|
||||
if err != nil {
|
||||
return nil, false, false, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build auth method: %v.", err)
|
||||
}
|
||||
return u, attrs.GetDryRun(), attrs.GetDisableDiscoveredConfigValidation(), nil
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,194 @@
|
||||
package authmethods
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/auth/password"
|
||||
pwstore "github.com/hashicorp/boundary/internal/auth/password/store"
|
||||
"github.com/hashicorp/boundary/internal/daemon/controller/auth"
|
||||
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/types/action"
|
||||
pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authmethods"
|
||||
pba "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authtokens"
|
||||
"google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
const (
|
||||
// password field names
|
||||
loginNameField = "login_name"
|
||||
passwordField = "password"
|
||||
loginCommand = "login"
|
||||
)
|
||||
|
||||
var pwMaskManager handlers.MaskManager
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if pwMaskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&pwstore.AuthMethod{}}, handlers.MaskSource{&pb.AuthMethod{}, &pb.PasswordAuthMethodAttributes{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
IdActions[password.Subtype] = action.ActionSet{
|
||||
action.NoOp,
|
||||
action.Read,
|
||||
action.Update,
|
||||
action.Delete,
|
||||
action.Authenticate,
|
||||
}
|
||||
}
|
||||
|
||||
// createPwInRepo creates a password auth method in a repo and returns the result.
|
||||
// This method should never return a nil AuthMethod without returning an error.
|
||||
func (s Service) createPwInRepo(ctx context.Context, scopeId string, item *pb.AuthMethod) (*password.AuthMethod, error) {
|
||||
u, err := toStoragePwAuthMethod(scopeId, item)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
repo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, err := repo.CreateAuthMethod(ctx, u)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to create auth method: %w", err)
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (s Service) updatePwInRepo(ctx context.Context, scopeId, id string, mask []string, item *pb.AuthMethod) (*password.AuthMethod, error) {
|
||||
u, err := toStoragePwAuthMethod(scopeId, item)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
version := item.GetVersion()
|
||||
u.PublicId = id
|
||||
|
||||
dbMask := pwMaskManager.Translate(mask)
|
||||
if len(dbMask) == 0 {
|
||||
return nil, handlers.InvalidArgumentErrorf("No valid fields included in the update mask.", map[string]string{"update_mask": "No valid fields provided in the update mask."})
|
||||
}
|
||||
|
||||
repo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, rowsUpdated, err := repo.UpdateAuthMethod(ctx, u, version, dbMask)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to update auth method: %w", err)
|
||||
}
|
||||
if rowsUpdated == 0 {
|
||||
return nil, handlers.NotFoundErrorf("AuthMethod %q doesn't exist or incorrect version provided.", id)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s Service) authenticatePassword(ctx context.Context, req *pbs.AuthenticateRequest, authResults *auth.VerifyResults) (*pbs.AuthenticateResponse, error) {
|
||||
reqAttrs := req.GetPasswordLoginAttributes()
|
||||
tok, err := s.authenticateWithPwRepo(ctx, authResults.Scope.GetId(), req.GetAuthMethodId(), reqAttrs.LoginName, reqAttrs.Password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.convertToAuthenticateResponse(ctx, req, authResults, tok)
|
||||
}
|
||||
|
||||
func (s Service) authenticateWithPwRepo(ctx context.Context, scopeId, authMethodId, loginName, pw string) (*pba.AuthToken, error) {
|
||||
iamRepo, err := s.iamRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
atRepo, err := s.atRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pwRepo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
acct, err := pwRepo.Authenticate(ctx, scopeId, authMethodId, loginName, pw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if acct == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Unauthenticated, "Unable to authenticate.")
|
||||
}
|
||||
|
||||
u, err := iamRepo.LookupUserWithLogin(ctx, acct.GetPublicId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tok, err := atRepo.CreateAuthToken(ctx, u, acct.GetPublicId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.ConvertInternalAuthTokenToApiAuthToken(
|
||||
ctx,
|
||||
tok,
|
||||
)
|
||||
}
|
||||
|
||||
func validateAuthenticatePasswordRequest(req *pbs.AuthenticateRequest) error {
|
||||
badFields := make(map[string]string)
|
||||
|
||||
attrs := req.GetPasswordLoginAttributes()
|
||||
if attrs.LoginName == "" {
|
||||
badFields["attributes.login_name"] = "This is a required field."
|
||||
}
|
||||
if attrs.Password == "" {
|
||||
badFields["attributes.password"] = "This is a required field."
|
||||
}
|
||||
if req.GetCommand() == "" {
|
||||
// TODO: Eventually, require a command. For now, fall back to "login" for backwards compat.
|
||||
req.Command = loginCommand
|
||||
}
|
||||
if req.Command != loginCommand {
|
||||
badFields[commandField] = "Invalid command for this auth method type."
|
||||
}
|
||||
tokenType := req.GetType()
|
||||
if tokenType == "" {
|
||||
// Fall back to deprecated field if type is not set
|
||||
tokenType = req.GetTokenType()
|
||||
}
|
||||
tType := strings.ToLower(strings.TrimSpace(tokenType))
|
||||
if tType != "" && tType != "token" && tType != "cookie" {
|
||||
badFields[tokenTypeField] = `The only accepted types are "token" and "cookie".`
|
||||
}
|
||||
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Invalid fields provided in request.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func toStoragePwAuthMethod(scopeId string, item *pb.AuthMethod) (*password.AuthMethod, error) {
|
||||
const op = "authmethod_service.toStoragePwAuthMethod"
|
||||
if item == nil {
|
||||
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "nil auth method.")
|
||||
}
|
||||
var opts []password.Option
|
||||
if item.GetName() != nil {
|
||||
opts = append(opts, password.WithName(item.GetName().GetValue()))
|
||||
}
|
||||
if item.GetDescription() != nil {
|
||||
opts = append(opts, password.WithDescription(item.GetDescription().GetValue()))
|
||||
}
|
||||
u, err := password.NewAuthMethod(scopeId, opts...)
|
||||
if err != nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build auth method for creation: %v.", err)
|
||||
}
|
||||
|
||||
pwAttrs := item.GetPasswordAuthMethodAttributes()
|
||||
if pwAttrs.GetMinLoginNameLength() != 0 {
|
||||
u.MinLoginNameLength = pwAttrs.GetMinLoginNameLength()
|
||||
}
|
||||
if pwAttrs.GetMinPasswordLength() != 0 {
|
||||
u.MinPasswordLength = pwAttrs.GetMinPasswordLength()
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
@@ -0,0 +1,689 @@
|
||||
package authmethods_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/boundary/internal/auth/oidc"
|
||||
"github.com/hashicorp/boundary/internal/auth/password"
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/daemon/controller/auth"
|
||||
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/authmethods"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/types/scope"
|
||||
pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authmethods"
|
||||
scopepb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/scopes"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/genproto/protobuf/field_mask"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/protobuf/testing/protocmp"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
)
|
||||
|
||||
func TestUpdate_Password(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.TestRepo(t, conn, wrapper), nil
|
||||
}
|
||||
oidcRepoFn := func() (*oidc.Repository, error) {
|
||||
return oidc.NewRepository(ctx, rw, rw, kms)
|
||||
}
|
||||
pwRepoFn := func() (*password.Repository, error) {
|
||||
return password.NewRepository(rw, rw, kms)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
|
||||
o, _ := iam.TestScopes(t, iamRepo)
|
||||
tested, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
|
||||
require.NoError(t, err, "Error when getting new auth_method service.")
|
||||
|
||||
defaultScopeInfo := &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: o.GetType(), ParentScopeId: scope.Global.String()}
|
||||
|
||||
freshAuthMethod := func() (*pb.AuthMethod, func()) {
|
||||
am, err := tested.CreateAuthMethod(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()),
|
||||
&pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
|
||||
ScopeId: o.GetPublicId(),
|
||||
Name: wrapperspb.String("default"),
|
||||
Description: wrapperspb.String("default"),
|
||||
Type: "password",
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
|
||||
clean := func() {
|
||||
_, err := tested.DeleteAuthMethod(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()),
|
||||
&pbs.DeleteAuthMethodRequest{Id: am.GetItem().GetId()})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
return am.GetItem(), clean
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
req *pbs.UpdateAuthMethodRequest
|
||||
res *pbs.UpdateAuthMethodResponse
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "Update an Existing AuthMethod",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"name", "description"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Type: "password",
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateAuthMethodResponse{
|
||||
Item: &pb.AuthMethod{
|
||||
ScopeId: o.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Type: "password",
|
||||
Attrs: &pb.AuthMethod_PasswordAuthMethodAttributes{
|
||||
PasswordAuthMethodAttributes: &pb.PasswordAuthMethodAttributes{
|
||||
MinPasswordLength: 8,
|
||||
MinLoginNameLength: 3,
|
||||
},
|
||||
},
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: pwAuthorizedActions,
|
||||
AuthorizedCollectionActions: authorizedCollectionActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Multiple Paths in single string",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"name,description,type"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Type: "password",
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateAuthMethodResponse{
|
||||
Item: &pb.AuthMethod{
|
||||
ScopeId: o.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Type: "password",
|
||||
Attrs: &pb.AuthMethod_PasswordAuthMethodAttributes{
|
||||
PasswordAuthMethodAttributes: &pb.PasswordAuthMethodAttributes{
|
||||
MinPasswordLength: 8,
|
||||
MinLoginNameLength: 3,
|
||||
},
|
||||
},
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: pwAuthorizedActions,
|
||||
AuthorizedCollectionActions: authorizedCollectionActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "No Update Mask",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
Item: &pb.AuthMethod{
|
||||
Name: &wrapperspb.StringValue{Value: "updated name"},
|
||||
Description: &wrapperspb.StringValue{Value: "updated desc"},
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "No Paths in Mask",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{Paths: []string{}},
|
||||
Item: &pb.AuthMethod{
|
||||
Name: &wrapperspb.StringValue{Value: "updated name"},
|
||||
Description: &wrapperspb.StringValue{Value: "updated desc"},
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Only non-existant paths in Mask",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{Paths: []string{"nonexistant_field"}},
|
||||
Item: &pb.AuthMethod{
|
||||
Name: &wrapperspb.StringValue{Value: "updated name"},
|
||||
Description: &wrapperspb.StringValue{Value: "updated desc"},
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Cant change type",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{Paths: []string{"name", "type"}},
|
||||
Item: &pb.AuthMethod{
|
||||
Name: &wrapperspb.StringValue{Value: "updated name"},
|
||||
Type: "oidc",
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Cant change is primary",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{Paths: []string{"is_primary"}},
|
||||
Item: &pb.AuthMethod{
|
||||
IsPrimary: true,
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Unset Name",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"name"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
Description: &wrapperspb.StringValue{Value: "ignored"},
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateAuthMethodResponse{
|
||||
Item: &pb.AuthMethod{
|
||||
ScopeId: o.GetPublicId(),
|
||||
Description: &wrapperspb.StringValue{Value: "default"},
|
||||
Type: "password",
|
||||
Attrs: &pb.AuthMethod_PasswordAuthMethodAttributes{
|
||||
PasswordAuthMethodAttributes: &pb.PasswordAuthMethodAttributes{
|
||||
MinPasswordLength: 8,
|
||||
MinLoginNameLength: 3,
|
||||
},
|
||||
},
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: pwAuthorizedActions,
|
||||
AuthorizedCollectionActions: authorizedCollectionActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Update Only Name",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"name"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
Name: &wrapperspb.StringValue{Value: "updated"},
|
||||
Description: &wrapperspb.StringValue{Value: "ignored"},
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateAuthMethodResponse{
|
||||
Item: &pb.AuthMethod{
|
||||
ScopeId: o.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "updated"},
|
||||
Description: &wrapperspb.StringValue{Value: "default"},
|
||||
Type: "password",
|
||||
Attrs: &pb.AuthMethod_PasswordAuthMethodAttributes{
|
||||
PasswordAuthMethodAttributes: &pb.PasswordAuthMethodAttributes{
|
||||
MinPasswordLength: 8,
|
||||
MinLoginNameLength: 3,
|
||||
},
|
||||
},
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: pwAuthorizedActions,
|
||||
AuthorizedCollectionActions: authorizedCollectionActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Update Only Description",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"description"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
Name: &wrapperspb.StringValue{Value: "ignored"},
|
||||
Description: &wrapperspb.StringValue{Value: "notignored"},
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateAuthMethodResponse{
|
||||
Item: &pb.AuthMethod{
|
||||
ScopeId: o.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "default"},
|
||||
Description: &wrapperspb.StringValue{Value: "notignored"},
|
||||
Type: "password",
|
||||
Attrs: &pb.AuthMethod_PasswordAuthMethodAttributes{
|
||||
PasswordAuthMethodAttributes: &pb.PasswordAuthMethodAttributes{
|
||||
MinPasswordLength: 8,
|
||||
MinLoginNameLength: 3,
|
||||
},
|
||||
},
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: pwAuthorizedActions,
|
||||
AuthorizedCollectionActions: authorizedCollectionActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Update a Non Existing AuthMethod",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
Id: password.AuthMethodPrefix + "_DoesntExis",
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"description"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.NotFound),
|
||||
},
|
||||
{
|
||||
name: "Cant change Id",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"id"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
Id: password.AuthMethodPrefix + "_somethinge",
|
||||
Name: &wrapperspb.StringValue{Value: "new"},
|
||||
Description: &wrapperspb.StringValue{Value: "new desc"},
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Cant specify Created Time",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"created_time"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
CreatedTime: timestamppb.Now(),
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Cant specify Updated Time",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"updated_time"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
UpdatedTime: timestamppb.Now(),
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Cant specify Type",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"type"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
Type: "oidc",
|
||||
},
|
||||
},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Update login name length",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"attributes.min_login_name_length"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
Name: &wrapperspb.StringValue{Value: "ignored"},
|
||||
Description: &wrapperspb.StringValue{Value: "ignored"},
|
||||
Attrs: &pb.AuthMethod_PasswordAuthMethodAttributes{
|
||||
PasswordAuthMethodAttributes: &pb.PasswordAuthMethodAttributes{
|
||||
MinLoginNameLength: 42,
|
||||
MinPasswordLength: 55555,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateAuthMethodResponse{
|
||||
Item: &pb.AuthMethod{
|
||||
ScopeId: o.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "default"},
|
||||
Description: &wrapperspb.StringValue{Value: "default"},
|
||||
Type: "password",
|
||||
Attrs: &pb.AuthMethod_PasswordAuthMethodAttributes{
|
||||
PasswordAuthMethodAttributes: &pb.PasswordAuthMethodAttributes{
|
||||
MinPasswordLength: 8,
|
||||
MinLoginNameLength: 42,
|
||||
},
|
||||
},
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: pwAuthorizedActions,
|
||||
AuthorizedCollectionActions: authorizedCollectionActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Update password length",
|
||||
req: &pbs.UpdateAuthMethodRequest{
|
||||
UpdateMask: &field_mask.FieldMask{
|
||||
Paths: []string{"attributes.min_password_length"},
|
||||
},
|
||||
Item: &pb.AuthMethod{
|
||||
Name: &wrapperspb.StringValue{Value: "ignored"},
|
||||
Description: &wrapperspb.StringValue{Value: "ignored"},
|
||||
Attrs: &pb.AuthMethod_PasswordAuthMethodAttributes{
|
||||
PasswordAuthMethodAttributes: &pb.PasswordAuthMethodAttributes{
|
||||
MinLoginNameLength: 5555,
|
||||
MinPasswordLength: 42,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
res: &pbs.UpdateAuthMethodResponse{
|
||||
Item: &pb.AuthMethod{
|
||||
ScopeId: o.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "default"},
|
||||
Description: &wrapperspb.StringValue{Value: "default"},
|
||||
Type: "password",
|
||||
Attrs: &pb.AuthMethod_PasswordAuthMethodAttributes{
|
||||
PasswordAuthMethodAttributes: &pb.PasswordAuthMethodAttributes{
|
||||
MinPasswordLength: 42,
|
||||
MinLoginNameLength: 3,
|
||||
},
|
||||
},
|
||||
Scope: defaultScopeInfo,
|
||||
AuthorizedActions: pwAuthorizedActions,
|
||||
AuthorizedCollectionActions: authorizedCollectionActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
am, cleanup := freshAuthMethod()
|
||||
defer cleanup()
|
||||
|
||||
tc.req.Item.Version = 1
|
||||
|
||||
if tc.req.GetId() == "" {
|
||||
tc.req.Id = am.GetId()
|
||||
}
|
||||
|
||||
if tc.res != nil && tc.res.Item != nil {
|
||||
tc.res.Item.Id = am.GetId()
|
||||
tc.res.Item.CreatedTime = am.GetCreatedTime()
|
||||
}
|
||||
|
||||
got, gErr := tested.UpdateAuthMethod(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.req)
|
||||
if tc.err != nil {
|
||||
require.Error(gErr)
|
||||
assert.True(errors.Is(gErr, tc.err), "UpdateAuthMethod(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
|
||||
}
|
||||
|
||||
if tc.res == nil {
|
||||
require.Nil(got)
|
||||
}
|
||||
|
||||
cmpOptions := []cmp.Option{protocmp.Transform()}
|
||||
if got != nil {
|
||||
assert.NotNilf(tc.res, "Expected UpdateAuthMethod response to be nil, but was %v", got)
|
||||
|
||||
created := am.GetCreatedTime().AsTime()
|
||||
gotUpdateTime := got.GetItem().GetUpdatedTime().AsTime()
|
||||
// Verify it is a auth_method updated after it was created
|
||||
assert.True(gotUpdateTime.After(created), "Updated auth_method should have been updated after it's creation. Was updated %v, which is after %v", gotUpdateTime, created)
|
||||
|
||||
// Ignore all values which are hard to compare against.
|
||||
cmpOptions = append(cmpOptions, protocmp.IgnoreFields(&pb.AuthMethod{}, "updated_time"))
|
||||
|
||||
assert.EqualValues(2, got.Item.Version)
|
||||
tc.res.Item.Version = 2
|
||||
}
|
||||
assert.Empty(cmp.Diff(got, tc.res, cmpOptions...), "UpdateAuthMethod(%q) got response %q, wanted %q", tc.req, got, tc.res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate_Password(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.TestRepo(t, conn, wrapper), nil
|
||||
}
|
||||
oidcRepoFn := func() (*oidc.Repository, error) {
|
||||
return oidc.NewRepository(ctx, rw, rw, kms)
|
||||
}
|
||||
pwRepoFn := func() (*password.Repository, error) {
|
||||
return password.NewRepository(rw, rw, kms)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
|
||||
|
||||
iam.TestSetPrimaryAuthMethod(t, iam.TestRepo(t, conn, wrapper), o, am.PublicId)
|
||||
|
||||
acct, err := password.NewAccount(am.GetPublicId(), password.WithLoginName(testLoginName))
|
||||
require.NoError(t, err)
|
||||
|
||||
pwRepo, err := pwRepoFn()
|
||||
require.NoError(t, err)
|
||||
acct, err = pwRepo.CreateAccount(context.Background(), o.GetPublicId(), acct, password.WithPassword(testPassword))
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, acct)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
request *pbs.AuthenticateRequest
|
||||
wantType string
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "basic",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "token",
|
||||
Attrs: &pbs.AuthenticateRequest_PasswordLoginAttributes{
|
||||
PasswordLoginAttributes: &pbs.PasswordLoginAttributes{
|
||||
LoginName: testLoginName,
|
||||
Password: testPassword,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantType: "token",
|
||||
},
|
||||
{
|
||||
name: "cookie-type",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "cookie",
|
||||
Attrs: &pbs.AuthenticateRequest_PasswordLoginAttributes{
|
||||
PasswordLoginAttributes: &pbs.PasswordLoginAttributes{
|
||||
LoginName: testLoginName,
|
||||
Password: testPassword,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantType: "cookie",
|
||||
},
|
||||
{
|
||||
name: "no-token-type",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Attrs: &pbs.AuthenticateRequest_PasswordLoginAttributes{
|
||||
PasswordLoginAttributes: &pbs.PasswordLoginAttributes{
|
||||
LoginName: testLoginName,
|
||||
Password: testPassword,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bad-token-type",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "email",
|
||||
Attrs: &pbs.AuthenticateRequest_PasswordLoginAttributes{
|
||||
PasswordLoginAttributes: &pbs.PasswordLoginAttributes{
|
||||
LoginName: testLoginName,
|
||||
Password: testPassword,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "no-authmethod",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
Attrs: &pbs.AuthenticateRequest_PasswordLoginAttributes{
|
||||
PasswordLoginAttributes: &pbs.PasswordLoginAttributes{
|
||||
LoginName: testLoginName,
|
||||
Password: testPassword,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "wrong-password",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "token",
|
||||
Attrs: &pbs.AuthenticateRequest_PasswordLoginAttributes{
|
||||
PasswordLoginAttributes: &pbs.PasswordLoginAttributes{
|
||||
LoginName: testLoginName,
|
||||
Password: "wrong",
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.Unauthenticated),
|
||||
},
|
||||
{
|
||||
name: "wrong-login-name",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "token",
|
||||
Attrs: &pbs.AuthenticateRequest_PasswordLoginAttributes{
|
||||
PasswordLoginAttributes: &pbs.PasswordLoginAttributes{
|
||||
LoginName: "wrong",
|
||||
Password: testPassword,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.Unauthenticated),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
s, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
|
||||
require.NoError(err)
|
||||
|
||||
resp, err := s.Authenticate(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.request)
|
||||
if tc.wantErr != nil {
|
||||
assert.Error(err)
|
||||
assert.Truef(errors.Is(err, tc.wantErr), "Got %#v, wanted %#v", err, tc.wantErr)
|
||||
return
|
||||
}
|
||||
require.NoError(err)
|
||||
|
||||
aToken := resp.GetAuthTokenResponse()
|
||||
assert.NotEmpty(aToken.GetId())
|
||||
assert.NotEmpty(aToken.GetToken())
|
||||
assert.True(strings.HasPrefix(aToken.GetToken(), aToken.GetId()))
|
||||
assert.Equal(am.GetPublicId(), aToken.GetAuthMethodId())
|
||||
assert.Equal(aToken.GetCreatedTime(), aToken.GetUpdatedTime())
|
||||
assert.Equal(aToken.GetCreatedTime(), aToken.GetApproximateLastUsedTime())
|
||||
assert.Equal(acct.GetPublicId(), aToken.GetAccountId())
|
||||
assert.Equal(am.GetPublicId(), aToken.GetAuthMethodId())
|
||||
assert.Equal(tc.wantType, resp.GetType())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate_AuthAccountConnectedToIamUser_Password(t *testing.T) {
|
||||
ctx := context.TODO()
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.TestRepo(t, conn, wrapper), nil
|
||||
}
|
||||
oidcRepoFn := func() (*oidc.Repository, error) {
|
||||
return oidc.NewRepository(ctx, rw, rw, kms)
|
||||
}
|
||||
pwRepoFn := func() (*password.Repository, error) {
|
||||
return password.NewRepository(rw, rw, kms)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
|
||||
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
|
||||
acct, err := password.NewAccount(am.GetPublicId(), password.WithLoginName(testLoginName))
|
||||
require.NoError(err)
|
||||
|
||||
pwRepo, err := pwRepoFn()
|
||||
require.NoError(err)
|
||||
acct, err = pwRepo.CreateAccount(context.Background(), o.GetPublicId(), acct, password.WithPassword(testPassword))
|
||||
require.NoError(err)
|
||||
|
||||
// connected to an account.
|
||||
iamRepo, err := iamRepoFn()
|
||||
require.NoError(err)
|
||||
iam.TestUser(t, iamRepo, am.ScopeId, iam.WithAccountIds(acct.PublicId))
|
||||
iamUser, err := iamRepo.LookupUserWithLogin(context.Background(), acct.GetPublicId())
|
||||
require.NoError(err)
|
||||
|
||||
s, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
|
||||
require.NoError(err)
|
||||
resp, err := s.Authenticate(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Attrs: &pbs.AuthenticateRequest_PasswordLoginAttributes{
|
||||
PasswordLoginAttributes: &pbs.PasswordLoginAttributes{
|
||||
LoginName: testLoginName,
|
||||
Password: testPassword,
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(err)
|
||||
|
||||
aToken := resp.GetAuthTokenResponse()
|
||||
assert.Equal(iamUser.GetPublicId(), aToken.GetUserId())
|
||||
assert.Equal(am.GetPublicId(), aToken.GetAuthMethodId())
|
||||
assert.Equal(acct.GetPublicId(), aToken.GetAccountId())
|
||||
|
||||
assert.NotEmpty(aToken.GetId())
|
||||
assert.NotEmpty(aToken.GetToken())
|
||||
assert.True(strings.HasPrefix(aToken.GetToken(), aToken.GetId()))
|
||||
}
|
||||
Reference in new issue
Block a user