Route connect OAuth through unified sign-in

Drop the portal-login redirect, accept continue URLs for magic links,
brand emails from the OAuth client when present, and update e2e coverage.

Signed-off-by: Bryan Frimin <bryan@probo.com>
This commit is contained in:
Bryan Frimin
2026-07-15 17:33:12 +02:00
parent d447fa295f
commit 5133b5feeb
10 changed files with 288 additions and 128 deletions

View File

@@ -592,13 +592,15 @@ func (c *Client) connectViaCIMD(email string) {
authorizeURL := c.redirectLocation(c.trustClient, initiateURL)
require.NotEmpty(c.T, authorizeURL, "oauth initiate must redirect to authorize")
portalLoginURL := c.redirectLocation(c.proboHTTPClient, authorizeURL)
require.Contains(c.T, portalLoginURL, "/auth/portal-login", "unauthenticated authorize must redirect to portal login")
loginURL := c.redirectLocation(c.proboHTTPClient, authorizeURL)
require.Contains(c.T, loginURL, "/auth/login", "unauthenticated authorize must redirect to login")
require.Contains(c.T, loginURL, "continue=", "login redirect must preserve continue URL")
authorizeParam := extractAuthorizeQueryParam(portalLoginURL)
require.NotEmpty(c.T, authorizeParam)
continueURL := extractContinueQueryParam(loginURL)
require.NotEmpty(c.T, continueURL)
require.Contains(c.T, continueURL, "/api/connect/v1/oauth2/authorize")
c.postConnectMagicLink(email, authorizeParam)
c.postConnectMagicLink(email, continueURL)
token := c.pollForLinkToken(fmt.Sprintf("to:%s", email))
verifyURL := c.baseURL + "/api/connect/v1/magic-link/verify?token=" + url.QueryEscape(token)
@@ -629,12 +631,12 @@ func (c *Client) connectViaCIMD(email string) {
)
}
func (c *Client) postConnectMagicLink(email, authorizeParam string) {
func (c *Client) postConnectMagicLink(email, continueURL string) {
c.T.Helper()
body := url.Values{}
body.Set("email", email)
body.Set("authorize", authorizeParam)
body.Set("continue", continueURL)
req, err := http.NewRequest(
"POST",
@@ -719,13 +721,13 @@ func resolveRedirectURL(baseURL, location string) string {
return base.ResolveReference(locURL).String()
}
func extractAuthorizeQueryParam(portalLoginURL string) string {
parsed, err := url.Parse(portalLoginURL)
func extractContinueQueryParam(loginURL string) string {
parsed, err := url.Parse(loginURL)
if err != nil {
return ""
}
return parsed.Query().Get("authorize")
return parsed.Query().Get("continue")
}
func (c *Client) GetEmail() string {

View File

@@ -62,13 +62,16 @@ type (
}
SendMagicLinkRequest struct {
Email mail.Addr
URLPath string
OrganizationID gid.GID
Continue *string
Email mail.Addr
URLPath string
Continue *string
// If users tries to connect to compliance page, we must brand the emails accordingly
CompliancePageID *gid.GID
MagicLinkBaseURL *string
// OrganizationID brands compliance portal magic-link emails.
OrganizationID *gid.GID
// OAuth2ClientIDRaw brands connect authorize magic-link emails.
OAuth2ClientIDRaw *string
MagicLinkBaseURL *string
}
PasswordResetData struct {
@@ -85,6 +88,8 @@ const (
TokenTypeOrganizationInvitation = "organization_invitation"
TokenTypePasswordReset = "password_reset"
TokenTypeMagicLink = "magic_link"
magicLinkDefaultSenderName = "Probo"
)
func NewAuthService(svc *Service) *AuthService {
@@ -595,7 +600,7 @@ func (s AuthService) SendMagicLink(ctx context.Context, req *SendMagicLinkReques
fullName := req.Email.Username()
identity := &coredata.Identity{}
organization := &coredata.Organization{}
senderName := magicLinkDefaultSenderName
if err := identity.LoadByEmail(ctx, tx, req.Email); err == nil {
if identity.FullName != "" {
@@ -607,8 +612,23 @@ func (s AuthService) SendMagicLink(ctx context.Context, req *SendMagicLinkReques
}
}
if err := organization.LoadByID(ctx, tx, coredata.NewNoScope(), req.OrganizationID); err != nil {
return fmt.Errorf("cannot load organization: %w", err)
if req.OAuth2ClientIDRaw != nil && *req.OAuth2ClientIDRaw != "" {
branding, err := s.OAuth2ServerService.ClientBranding(ctx, *req.OAuth2ClientIDRaw)
if err != nil {
return fmt.Errorf("cannot load oauth2 client branding: %w", err)
}
if branding != nil {
senderName = branding.Name
}
} else if req.OrganizationID != nil {
organization := &coredata.Organization{}
if err := organization.LoadByID(ctx, tx, coredata.NewNoScope(), *req.OrganizationID); err != nil {
return fmt.Errorf("cannot load organization: %w", err)
}
senderName = organization.Name
}
emailPresenterCfg := emails.DefaultPresenterConfig(s.baseURL)
@@ -633,7 +653,7 @@ func (s AuthService) SendMagicLink(ctx context.Context, req *SendMagicLinkReques
req.URLPath,
tokenString,
s.magicLinkTokenValidity,
organization.Name,
senderName,
)
if err != nil {
return fmt.Errorf("cannot render magic link email: %w", err)
@@ -642,7 +662,7 @@ func (s AuthService) SendMagicLink(ctx context.Context, req *SendMagicLinkReques
var emailOpts *coredata.EmailOptions
if req.CompliancePageID != nil {
emailOpts = &coredata.EmailOptions{
SenderName: new(organization.Name),
SenderName: &senderName,
}
}

View File

@@ -38,7 +38,7 @@ func (r *mutationResolver) SendMagicLink(ctx context.Context, input types.SendMa
req := &iam.SendMagicLinkRequest{
Email: input.Email,
CompliancePageID: &trustCenter.ID,
OrganizationID: trustCenter.OrganizationID,
OrganizationID: &trustCenter.OrganizationID,
URLPath: "verify-magic-link",
Continue: input.Continue,
}

View File

@@ -25,6 +25,7 @@ import (
"go.gearno.de/kit/log"
"go.probo.inc/probo/pkg/baseurl"
trust "go.probo.inc/probo/pkg/complianceportal/visitor"
"go.probo.inc/probo/pkg/filemanager"
"go.probo.inc/probo/pkg/iam"
"go.probo.inc/probo/pkg/securecookie"
@@ -36,13 +37,22 @@ import (
"go.probo.inc/probo/pkg/server/gqlutils/directives/session"
)
func NewGraphQLHandler(svc *iam.Service, logger *log.Logger, fileManagerSvc *filemanager.Service, baseURL *baseurl.BaseURL, cookieConfig securecookie.Config, limits gqlutils.Limits) http.Handler {
func NewGraphQLHandler(
svc *iam.Service,
trustSvc *trust.Service,
logger *log.Logger,
fileManagerSvc *filemanager.Service,
baseURL *baseurl.BaseURL,
cookieConfig securecookie.Config,
limits gqlutils.Limits,
) http.Handler {
config := schema.Config{
Resolvers: &Resolver{
authorize: authz.NewAuthorizeFunc(svc, logger),
batchAuthorize: authz.NewBatchAuthorizeFunc(svc, logger),
logger: logger,
iam: svc,
trust: trustSvc,
scopeRegistry: svc.OAuth2ScopeRegistry,
fileManager: fileManagerSvc,
baseURL: baseURL,

View File

@@ -0,0 +1,109 @@
// Copyright (c) 2026 Probo Inc <hello@probo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package connect_v1_test
import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"go.gearno.de/kit/log"
"go.probo.inc/probo/pkg/baseurl"
"go.probo.inc/probo/pkg/securecookie"
connect_v1 "go.probo.inc/probo/pkg/server/api/connect/v1"
)
func newTestMagicLinkHandler(t *testing.T) *connect_v1.MagicLinkHandler {
t.Helper()
return connect_v1.NewMagicLinkHandler(
nil,
baseurl.MustParse("https://auth.example.com"),
securecookie.Config{Secret: "01234567890123456789012345678901"},
log.NewLogger(log.WithOutput(io.Discard)),
nil,
)
}
func postMagicLinkForm(t *testing.T, handler http.HandlerFunc, values url.Values) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(
http.MethodPost,
"/api/connect/v1/magic-link/send",
strings.NewReader(values.Encode()),
)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
handler(rec, req)
return rec
}
func TestMagicLinkHandler_SendHandler_Validation(t *testing.T) {
t.Parallel()
handler := newTestMagicLinkHandler(t)
t.Run("rejects missing continue", func(t *testing.T) {
t.Parallel()
rec := postMagicLinkForm(
t,
handler.SendHandler,
url.Values{
"email": {"user@example.com"},
},
)
assert.Equal(t, http.StatusBadRequest, rec.Code)
})
t.Run("rejects invalid email", func(t *testing.T) {
t.Parallel()
rec := postMagicLinkForm(
t,
handler.SendHandler,
url.Values{
"email": {"not-an-email"},
"continue": {"/"},
},
)
assert.Equal(t, http.StatusBadRequest, rec.Code)
})
t.Run("rejects unsafe continue URL", func(t *testing.T) {
t.Parallel()
rec := postMagicLinkForm(
t,
handler.SendHandler,
url.Values{
"email": {"user@example.com"},
"continue": {"//evil.example.com"},
},
)
assert.Equal(t, http.StatusBadRequest, rec.Code)
})
}

View File

@@ -0,0 +1,36 @@
// Copyright (c) 2026 Probo Inc <hello@probo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package connect_v1
import (
"net/url"
)
const oauth2AuthorizeFullPath = "/api/connect/v1" + oauth2AuthorizePath
func oauth2ClientIDFromContinueURL(continueURL string) string {
parsed, err := url.Parse(continueURL)
if err != nil {
return ""
}
// Only read client_id from the real authorize endpoint. The continue URL
// itself is already validated by saferedirect before this runs.
if parsed.Path != oauth2AuthorizeFullPath {
return ""
}
return parsed.Query().Get("client_id")
}

View File

@@ -0,0 +1,65 @@
// Copyright (c) 2026 Probo Inc <hello@probo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package connect_v1
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestOauth2ClientIDFromContinueURL(t *testing.T) {
t.Parallel()
tests := []struct {
name string
continueURL string
want string
}{
{
name: "extracts client_id from authorize URL",
continueURL: "/api/connect/v1/oauth2/authorize?client_id=https%3A%2F%2Ftrust.example.com%2F.well-known%2Foauth-client-metadata&response_type=code",
want: "https://trust.example.com/.well-known/oauth-client-metadata",
},
{
name: "returns empty for non-authorize URL",
continueURL: "/overview",
want: "",
},
{
name: "returns empty for path suffix lookalike",
continueURL: "/evil/oauth2/authorize?client_id=phishing",
want: "",
},
{
name: "returns empty when client_id is missing",
continueURL: "/api/connect/v1/oauth2/authorize?response_type=code",
want: "",
},
{
name: "extracts client_id from absolute authorize URL",
continueURL: "https://auth.example.com/api/connect/v1/oauth2/authorize?client_id=gid%3A%2F%2Fprobo%2Foauth2_client%2Fabc",
want: "gid://probo/oauth2_client/abc",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
assert.Equal(t, tt.want, oauth2ClientIDFromContinueURL(tt.continueURL))
})
}
}

View File

@@ -32,7 +32,6 @@ import (
"go.gearno.de/kit/log"
"go.probo.inc/probo/pkg/baseurl"
"go.probo.inc/probo/pkg/bearertoken"
trust "go.probo.inc/probo/pkg/complianceportal/visitor"
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/iam"
"go.probo.inc/probo/pkg/iam/oauth2"
@@ -43,29 +42,23 @@ import (
)
type OAuth2Handler struct {
iam *iam.Service
trust *trust.Service
sessionCookie *authn.Cookie
baseURL *baseurl.BaseURL
portalLoginPath string
logger *log.Logger
iam *iam.Service
sessionCookie *authn.Cookie
baseURL *baseurl.BaseURL
logger *log.Logger
}
func NewOAuth2Handler(
svc *iam.Service,
trustSvc *trust.Service,
cookieConfig securecookie.Config,
baseURL *baseurl.BaseURL,
portalLoginPath string,
logger *log.Logger,
) *OAuth2Handler {
return &OAuth2Handler{
iam: svc,
trust: trustSvc,
sessionCookie: authn.NewCookie(&cookieConfig),
baseURL: baseURL,
portalLoginPath: portalLoginPath,
logger: logger.Named("oauth2"),
iam: svc,
sessionCookie: authn.NewCookie(&cookieConfig),
baseURL: baseURL,
logger: logger.Named("oauth2"),
}
}
@@ -150,16 +143,6 @@ func (h *OAuth2Handler) AuthorizeHandler(w http.ResponseWriter, r *http.Request)
return
}
clientID := r.URL.Query().Get("client_id")
if _, err := portalFromCIMDClientID(r.Context(), h.trust, clientID); err == nil {
q := url.Values{}
q.Set("authorize", r.URL.Query().Encode())
loginURL := h.baseURL.WithPath(h.portalLoginPath).WithQueryValues(q).MustString()
http.Redirect(w, r, loginURL, http.StatusFound)
return
}
loginURL := h.baseURL.WithPath("/auth/login").
WithQuery("continue", continueURL).
MustString()

View File

@@ -21,21 +21,17 @@
package connect_v1
import (
"context"
"errors"
"net/http"
"net/url"
"strings"
"github.com/go-chi/chi/v5"
"go.gearno.de/kit/httpserver"
"go.gearno.de/kit/log"
"go.probo.inc/probo/pkg/baseurl"
trust "go.probo.inc/probo/pkg/complianceportal/visitor"
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam"
"go.probo.inc/probo/pkg/iam/oauth2"
"go.probo.inc/probo/pkg/mail"
"go.probo.inc/probo/pkg/saferedirect"
"go.probo.inc/probo/pkg/securecookie"
@@ -221,7 +217,6 @@ func parseOIDCProvider(s string) (coredata.OIDCProvider, error) {
type MagicLinkHandler struct {
iam *iam.Service
trust *trust.Service
proboBaseURL *baseurl.BaseURL
sessionCookie *authn.Cookie
safeRedirect *saferedirect.SafeRedirect
@@ -230,17 +225,16 @@ type MagicLinkHandler struct {
func NewMagicLinkHandler(
iamSvc *iam.Service,
trustSvc *trust.Service,
proboBaseURL *baseurl.BaseURL,
cookieConfig securecookie.Config,
logger *log.Logger,
allowedHost saferedirect.AllowedHostFunc,
) *MagicLinkHandler {
return &MagicLinkHandler{
iam: iamSvc,
trust: trustSvc,
proboBaseURL: proboBaseURL,
sessionCookie: authn.NewCookie(&cookieConfig),
safeRedirect: saferedirect.New(nil),
safeRedirect: saferedirect.New(allowedHost),
logger: logger,
}
}
@@ -259,17 +253,15 @@ func (h *MagicLinkHandler) SendHandler(w http.ResponseWriter, r *http.Request) {
return
}
authorizeContinue := h.authorizeContinueURL(r.FormValue("authorize"))
if authorizeContinue == "" {
httpserver.RenderError(w, http.StatusBadRequest, errors.New("invalid authorize parameters"))
continueParam := r.FormValue("continue")
if continueParam == "" {
httpserver.RenderError(w, http.StatusBadRequest, errors.New("invalid magic link parameters"))
return
}
compliancePageID, organizationID, err := h.portalIDsFromAuthorize(ctx, r.FormValue("authorize"))
if err != nil {
h.logger.WarnCtx(ctx, "cannot resolve compliance portal from authorize params", log.Error(err))
httpserver.RenderError(w, http.StatusBadRequest, errors.New("invalid authorize parameters"))
safeContinue, ok := h.safeRedirect.Validate(ctx, continueParam)
if !ok {
httpserver.RenderError(w, http.StatusBadRequest, errors.New("invalid continue URL"))
return
}
@@ -277,11 +269,13 @@ func (h *MagicLinkHandler) SendHandler(w http.ResponseWriter, r *http.Request) {
req := &iam.SendMagicLinkRequest{
Email: emailAddr,
CompliancePageID: compliancePageID,
OrganizationID: organizationID,
URLPath: "/api/connect/v1/magic-link/verify",
Continue: &authorizeContinue,
MagicLinkBaseURL: &proboURL,
Continue: &safeContinue,
}
if clientID := oauth2ClientIDFromContinueURL(safeContinue); clientID != "" {
req.OAuth2ClientIDRaw = &clientID
}
if err := h.iam.AuthService.SendMagicLink(ctx, req); err != nil {
@@ -342,61 +336,3 @@ func (h *MagicLinkHandler) VerifyHandler(w http.ResponseWriter, r *http.Request)
http.Redirect(w, r, redirectURL, http.StatusFound)
}
func (h *MagicLinkHandler) authorizeContinueURL(encodedAuthorize string) string {
if encodedAuthorize == "" {
return ""
}
values, err := url.ParseQuery(encodedAuthorize)
if err != nil {
return ""
}
metadata := OAuth2ServerMetadata(
h.proboBaseURL,
h.iam.OAuth2ScopeRegistry.RegisteredScopes(),
)
continueURL, err := oauth2.AuthorizationURLWithQuery(metadata.AuthorizationEndpoint, values)
if err != nil {
return ""
}
return continueURL
}
func portalFromCIMDClientID(
ctx context.Context,
trustSvc *trust.Service,
clientID string,
) (*coredata.TrustCenter, error) {
host, ok := oauth2.CIMDClientIDHost(clientID)
if !ok {
return nil, errors.New("invalid cimd client_id")
}
portal, err := trustSvc.GetPortalByDomainName(ctx, host)
if err != nil {
return nil, err
}
return portal, nil
}
func (h *MagicLinkHandler) portalIDsFromAuthorize(
ctx context.Context,
encodedAuthorize string,
) (*gid.GID, gid.GID, error) {
values, err := url.ParseQuery(encodedAuthorize)
if err != nil {
return nil, gid.GID{}, err
}
portal, err := portalFromCIMDClientID(ctx, h.trust, values.Get("client_id"))
if err != nil {
return nil, gid.GID{}, err
}
return &portal.ID, portal.OrganizationID, nil
}

View File

@@ -68,6 +68,7 @@ type (
batchAuthorize authz.BatchAuthorizeFunc
logger *log.Logger
iam *iam.Service
trust *trust.Service
scopeRegistry *oauth2scope.Registry
fileManager *filemanager.Service
baseURL *baseurl.BaseURL
@@ -92,7 +93,7 @@ func NewMux(
apiKeyMiddleware := authn.NewAPIKeyMiddleware(svc, tokenSecret)
oauth2Middleware := authn.NewOAuth2AccessTokenMiddleware(svc)
identityPresenceMiddleware := authn.NewIdentityPresenceMiddleware(baseURL)
graphqlHandler := NewGraphQLHandler(svc, logger, fileManagerSvc, baseURL, cookieConfig, graphqlLimits)
graphqlHandler := NewGraphQLHandler(svc, trustSvc, logger, fileManagerSvc, baseURL, cookieConfig, graphqlLimits)
samlHandler := NewSAMLHandler(svc, cookieConfig, baseURL, logger)
scimHandler := NewSCIMHandler(svc, logger.Named("scim"))
@@ -106,18 +107,16 @@ func NewMux(
magicLinkHandler := NewMagicLinkHandler(
svc,
trustSvc,
baseURL,
cookieConfig,
logger,
allowedRedirectHost,
)
oauth2Handler := NewOAuth2Handler(
svc,
trustSvc,
cookieConfig,
baseURL,
"/auth/portal-login",
logger,
)