Skip to content
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

Fix Per-session MFA for leaf apps #51394

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
91 changes: 91 additions & 0 deletions integration/helpers/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import (
"github.com/gravitational/roundtrip"
"github.com/stretchr/testify/require"

"github.com/gravitational/teleport/lib/auth/mocku2f"
"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/web"
websession "github.com/gravitational/teleport/lib/web/session"
Expand Down Expand Up @@ -109,6 +110,96 @@ func LoginWebClient(t *testing.T, host, username, password string) *WebClientPac
return webClient
}

// LoginMFAWebClient receives the host url and a passwordless
// device to carry out login and return a WebClientPack.
func LoginMFAWebClient(t *testing.T, host string, passwordlessDevice *mocku2f.Key) *WebClientPack {
// Begin login
loginReq, err := json.Marshal(client.MFAChallengeRequest{
Passwordless: true,
})
require.NoError(t, err)

u := url.URL{
Scheme: "https",
Host: host,
Path: "/v1/webapi/mfa/login/begin",
}
beginLoginReq, err := http.NewRequest(http.MethodPost, u.String(), bytes.NewBuffer(loginReq))
require.NoError(t, err)

beginLoginReq.Header.Set("Content-Type", "application/json; charset=utf-8")

clt := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
beginLoginResp, err := clt.Do(beginLoginReq)
require.NoError(t, err)
defer beginLoginResp.Body.Close()
require.Equal(t, http.StatusOK, beginLoginResp.StatusCode)

// Read mfa challenge from response and pass it to the passwordless device.
var mfaChallenge *client.MFAAuthenticateChallenge
err = json.NewDecoder(beginLoginResp.Body).Decode(&mfaChallenge)
require.NoError(t, err)

origin := fmt.Sprintf("https://%v", host)
webauthnResponse, err := passwordlessDevice.SignAssertion(origin, mfaChallenge.WebauthnChallenge)
require.NoError(t, err)

// Finish login and get a web session.
finishReq, err := json.Marshal(client.AuthenticateWebUserRequest{
WebauthnAssertionResponse: webauthnResponse,
})
require.NoError(t, err)

u = url.URL{
Scheme: "https",
Host: host,
Path: "/v1/webapi/mfa/login/finishsession",
}
finishLoginReq, err := http.NewRequest(http.MethodPost, u.String(), bytes.NewBuffer(finishReq))
require.NoError(t, err)

finishLoginReq.Header.Set("Content-Type", "application/json; charset=utf-8")

// Issue request.
finishLoginResp, err := clt.Do(finishLoginReq)
require.NoError(t, err)
defer finishLoginResp.Body.Close()
require.Equal(t, http.StatusOK, finishLoginResp.StatusCode)

// Read in response.
var csResp *web.CreateSessionResponse
err = json.NewDecoder(finishLoginResp.Body).Decode(&csResp)
require.NoError(t, err)

// Extract session cookie and bearer token.
require.Len(t, finishLoginResp.Cookies(), 1)
cookie := finishLoginResp.Cookies()[0]
require.Equal(t, websession.CookieName, cookie.Name)

webClient := &WebClientPack{
clt: clt,
host: host,
webCookie: cookie.Value,
bearerToken: csResp.Token,
}

respStatusCode, bs := webClient.DoRequest(t, http.MethodGet, "sites", nil)
require.Equal(t, http.StatusOK, respStatusCode, string(bs))

var clusters []ui.Cluster
require.NoError(t, json.Unmarshal(bs, &clusters), string(bs))
require.NotEmpty(t, clusters)

webClient.clusterName = clusters[0].Name
return webClient
}

// DoRequest receives a method, endpoint and payload and sends an HTTP Request to the Teleport API.
// The endpoint must not contain the host neither the base path ('/v1/webapi/').
// Status Code and Body are returned.
Expand Down
214 changes: 214 additions & 0 deletions integration/web/web_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
/*
* Teleport
* Copyright (C) 2025 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package web

import (
"context"
"encoding/json"
"net/http"
"net/url"
"testing"

"github.com/stretchr/testify/require"

mfav1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/mfa/v1"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/utils"
"github.com/gravitational/teleport/integration/helpers"
"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/service/servicecfg"
"github.com/gravitational/teleport/lib/web"
testserver "github.com/gravitational/teleport/tool/teleport/testenv"
)

func TestMFAAuthenticateChallenge_IsMFARequiredApp(t *testing.T) {
ctx := context.Background()

appAccessRole, err := types.NewRole("app-access", types.RoleSpecV6{
Allow: types.RoleConditions{
AppLabels: types.Labels(map[string]utils.Strings{
"name": []string{"root-app", "leaf-app"},
}),
},
})
require.NoError(t, err)

appAccessMfaRole, err := types.NewRole("app-access-mfa", types.RoleSpecV6{
Allow: types.RoleConditions{
AppLabels: types.Labels(map[string]utils.Strings{
"name": []string{"root-app-mfa", "leaf-app-mfa"},
}),
},
Options: types.RoleOptions{
RequireMFAType: types.RequireMFAType_SESSION,
},
})
require.NoError(t, err)

user, err := types.NewUser("app-user")
require.NoError(t, err)
user.SetRoles([]string{"app-access", "app-access-mfa"})

// Create root and leaf cluster.
rootServer := testserver.MakeTestServer(t,
testserver.WithBootstrap(appAccessRole, appAccessMfaRole, user),
testserver.WithClusterName(t, "root"),
testserver.WithTestApp(t, "root-app"),
testserver.WithTestApp(t, "root-app-mfa"),
testserver.WithConfig(func(cfg *servicecfg.Config) {
cfg.SSH.Enabled = false
cfg.Auth.Preference = &types.AuthPreferenceV2{
Metadata: types.Metadata{
Labels: map[string]string{types.OriginLabel: types.OriginConfigFile},
},
Spec: types.AuthPreferenceSpecV2{
AllowPasswordless: types.NewBoolOption(true),
SecondFactors: []types.SecondFactorType{types.SecondFactorType_SECOND_FACTOR_TYPE_WEBAUTHN},
Webauthn: &types.Webauthn{
RPID: "127.0.0.1",
},
},
}
}),
)
rootProxyAddr, err := rootServer.ProxyWebAddr()
require.NoError(t, err)

leafServer := testserver.MakeTestServer(t,
testserver.WithBootstrap(appAccessRole, appAccessMfaRole),
testserver.WithClusterName(t, "leaf"),
testserver.WithTestApp(t, "leaf-app"),
testserver.WithTestApp(t, "leaf-app-mfa"),
testserver.WithConfig(func(cfg *servicecfg.Config) {
cfg.SSH.Enabled = false
}),
)
leafAuth := leafServer.GetAuthServer()

testserver.SetupTrustedCluster(ctx, t, rootServer, leafServer,
types.RoleMapping{
Remote: "app-access",
Local: []string{"app-access"},
},
types.RoleMapping{
Remote: "app-access-mfa",
Local: []string{"app-access-mfa"},
},
)

// Require Session MFA in the leaf only.
leafAccess, err := leafAuth.GetRole(ctx, "access")
require.NoError(t, err)
o := leafAccess.GetOptions()
o.RequireMFAType = types.RequireMFAType_SESSION
leafAccess.SetOptions(o)
_, err = leafAuth.UpsertRole(ctx, leafAccess)
require.NoError(t, err)

// Setup user for login, then login.
device := testserver.RegisterPasswordlessDeviceForUser(t, rootServer, user.GetName())
webPack := helpers.LoginMFAWebClient(t, rootProxyAddr.String(), device)

endpoint, err := url.JoinPath("mfa", "authenticatechallenge")
require.NoError(t, err)

for _, tt := range []struct {
name string
resolveAppParams web.ResolveAppParams
expectMFARequired bool
}{
{
name: "root-app",
resolveAppParams: web.ResolveAppParams{
AppName: "root-app",
ClusterName: "root",
PublicAddr: "root-app.root",
FQDNHint: "root-app.root",
},
expectMFARequired: false,
}, {
name: "root-app-mfa",
resolveAppParams: web.ResolveAppParams{
AppName: "root-app-mfa",
ClusterName: "root",
PublicAddr: "root-app-mfa.root",
FQDNHint: "root-app-mfa.root",
},
expectMFARequired: true,
}, {
name: "leaf-app",
resolveAppParams: web.ResolveAppParams{
AppName: "leaf-app",
ClusterName: "leaf",
PublicAddr: "leaf-app.leaf",
FQDNHint: "leaf-app.root",
},
expectMFARequired: false,
}, {
name: "leaf-app-mfa",
resolveAppParams: web.ResolveAppParams{
AppName: "leaf-app-mfa",
ClusterName: "leaf",
PublicAddr: "leaf-app-mfa.leaf",
FQDNHint: "leaf-app-mfa.root",
},
expectMFARequired: true,
},
} {
t.Run(tt.name, func(t *testing.T) {
// Check each different way to resolve the app.
for variant, resolveParams := range map[string]web.ResolveAppParams{
"name": {
AppName: tt.resolveAppParams.AppName,
ClusterName: tt.resolveAppParams.ClusterName,
},
"publicAddr": {
ClusterName: tt.resolveAppParams.ClusterName,
PublicAddr: tt.resolveAppParams.PublicAddr,
},
"fqdn": {
FQDNHint: tt.resolveAppParams.FQDNHint,
},
} {
t.Run(variant, func(t *testing.T) {
req := web.CreateAuthenticateChallengeRequest{
ChallengeScope: int(mfav1.ChallengeScope_CHALLENGE_SCOPE_USER_SESSION),
IsMFARequiredRequest: &web.IsMFARequiredRequest{
App: &web.IsMFARequiredApp{
ResolveAppParams: resolveParams,
},
},
}

respStatusCode, respBody := webPack.DoRequest(t, http.MethodPost, endpoint, req)
require.Equal(t, http.StatusOK, respStatusCode, string(respBody))

var resp client.MFAAuthenticateChallenge
require.NoError(t, json.Unmarshal(respBody, &resp))

if tt.expectMFARequired {
require.NotEmpty(t, resp.WebauthnChallenge)
} else {
require.Empty(t, resp.WebauthnChallenge)
}
})
}
})
}
}
18 changes: 9 additions & 9 deletions lib/web/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -4562,15 +4562,6 @@ func (h *Handler) authenticateRequestWithCluster(w http.ResponseWriter, r *http.
// remote trusted cluster) as specified by the ":site" url parameter.
func (h *Handler) getSiteByParams(ctx context.Context, sctx *SessionContext, p httprouter.Params) (reversetunnelclient.RemoteSite, error) {
clusterName := p.ByName("site")
if clusterName == currentSiteShortcut {
res, err := h.cfg.ProxyClient.GetClusterName()
if err != nil {
h.logger.WarnContext(ctx, "Failed to query cluster name", "error", err)
return nil, trace.Wrap(err)
}
clusterName = res.GetClusterName()
}

site, err := h.getSiteByClusterName(ctx, sctx, clusterName)
if err != nil {
return nil, trace.Wrap(err)
Expand All @@ -4580,6 +4571,15 @@ func (h *Handler) getSiteByParams(ctx context.Context, sctx *SessionContext, p h
}

func (h *Handler) getSiteByClusterName(ctx context.Context, sctx *SessionContext, clusterName string) (reversetunnelclient.RemoteSite, error) {
if clusterName == currentSiteShortcut {
res, err := h.cfg.ProxyClient.GetClusterName()
if err != nil {
h.logger.WarnContext(ctx, "Failed to query cluster name", "error", err)
return nil, trace.Wrap(err)
}
clusterName = res.GetClusterName()
}

proxy, err := h.ProxyWithRoles(ctx, sctx)
if err != nil {
h.logger.WarnContext(ctx, "Failed to get proxy with roles", "error", err)
Expand Down
Loading
Loading