Fix various bad tenant isolation

Signed-off-by: Bryan Frimin <bryan@getprobo.com>
This commit is contained in:
Bryan Frimin
2025-10-30 15:39:38 +01:00
parent a42670d5bd
commit 29917578fc
30 changed files with 1259 additions and 1369 deletions

View File

@@ -36,13 +36,13 @@ type (
}
)
func AcceptInvitationHandler(authSvc *authsvc.Service, authzSvc *authz.Service, authCfg RoutesConfig) http.HandlerFunc {
func AcceptInvitationHandler(authSvc *authsvc.Service, authzSvc *authz.Service, cookieName string, cookieSecret string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
sessionAuthCfg := session.AuthConfig{
CookieName: authCfg.CookieName,
CookieSecret: authCfg.CookieSecret,
CookieName: cookieName,
CookieSecret: cookieSecret,
}
errorHandler := session.ErrorHandler{

View File

@@ -23,20 +23,18 @@ import (
"github.com/getprobo/probo/pkg/filemanager"
"github.com/go-chi/chi/v5"
"go.gearno.de/kit/log"
"go.gearno.de/kit/pg"
)
type Config struct {
Auth *authsvc.Service
Authz *authz.Service
SAML *authsvc.SAMLService
CookieName string
CookieDomain string
SessionDuration time.Duration
CookieSecret string
FileManager *filemanager.Service
PGClient *pg.Client
Logger *log.Logger
Auth *authsvc.Service
Authz *authz.Service
SAML *authsvc.SAMLService
CookieName string
CookieDomain string
SessionDuration time.Duration
CookieSecret string
FileManager *filemanager.Service
Logger *log.Logger
}
type Server struct {
@@ -46,21 +44,21 @@ type Server struct {
func NewServer(cfg Config) (*Server, error) {
router := chi.NewRouter()
MountRoutes(
router,
cfg.Auth,
cfg.Authz,
cfg.SAML,
RoutesConfig{
CookieName: cfg.CookieName,
CookieDomain: cfg.CookieDomain,
SessionDuration: cfg.SessionDuration,
CookieSecret: cfg.CookieSecret,
FileManager: cfg.FileManager,
PGClient: cfg.PGClient,
},
cfg.Logger,
)
router.Post("/register", SignUpHandler(cfg.Auth, cfg.CookieName, cfg.CookieSecret))
router.Post("/login", SignInHandler(cfg.Auth, cfg.CookieName, cfg.CookieSecret))
router.Delete("/logout", SignOutHandler(cfg.Auth, cfg.CookieName, cfg.CookieSecret))
router.Post("/signup-from-invitation", SignupFromInvitationHandler(cfg.Auth, cfg.CookieName, cfg.CookieSecret))
router.Post("/forget-password", ForgetPasswordHandler(cfg.Auth))
router.Post("/reset-password", ResetPasswordHandler(cfg.Auth))
router.Post("/check-sso", SAMLCheckSSOHandler(cfg.Auth, cfg.Logger))
router.Get("/organizations", RequireAuth(cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret, ListOrganizationsHandler(cfg.Auth, cfg.Authz)))
router.Get("/organizations/{organizationID}/logo", RequireAuth(cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret, OrganizationLogoHandler(cfg.Auth, cfg.FileManager)))
router.Get("/invitations", RequireAuth(cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret, ListInvitationsHandler(cfg.Authz)))
router.Post("/invitations/accept", AcceptInvitationHandler(cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret))
router.Get("/saml/login/{samlConfigID}", SAMLLoginHandler(cfg.SAML, cfg.Auth, cfg.Logger))
router.Post("/saml/consume", SAMLACSHandler(cfg.SAML, cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret, cfg.SessionDuration, cfg.Logger))
router.Get("/saml/metadata", SAMLMetadataHandler(cfg.SAML))
return &Server{
router: router,

View File

@@ -0,0 +1,93 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.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 auth
import (
"context"
"fmt"
"net/http"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/authz"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/server/session"
"go.gearno.de/kit/httpserver"
)
type ctxKey struct{ name string }
var (
sessionContextKey = &ctxKey{name: "session"}
userContextKey = &ctxKey{name: "user"}
)
func RequireAuth(
authSvc *authsvc.Service,
authzSvc *authz.Service,
cookieName string,
cookieSecret string,
next http.HandlerFunc,
) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
sessionAuthCfg := session.AuthConfig{
CookieName: cookieName,
CookieSecret: cookieSecret,
}
errorHandler := session.ErrorHandler{
OnCookieError: func(err error) {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnParseError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnSessionError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("session expired"))
},
OnUserError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("user not found"))
},
OnTenantError: func(err error) {
panic(fmt.Errorf("cannot list tenants for user: %w", err))
},
}
authResult := session.TryAuth(ctx, w, r, authSvc, authzSvc, sessionAuthCfg, errorHandler)
if authResult == nil {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("authentication required"))
return
}
ctx = context.WithValue(ctx, sessionContextKey, authResult.Session)
ctx = context.WithValue(ctx, userContextKey, authResult.User)
next(w, r.WithContext(ctx))
}
}
func SessionFromContext(ctx context.Context) *coredata.Session {
session, _ := ctx.Value(sessionContextKey).(*coredata.Session)
return session
}
func UserFromContext(ctx context.Context) *coredata.User {
user, _ := ctx.Value(userContextKey).(*coredata.User)
return user
}

View File

@@ -33,7 +33,7 @@ type (
}
)
func ForgetPasswordHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
func ForgetPasswordHandler(authSvc *authsvc.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req ForgetPasswordRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {

View File

@@ -15,18 +15,12 @@
package auth
import (
"context"
"fmt"
"net/http"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/authz"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/getprobo/probo/pkg/server/session"
"go.gearno.de/kit/httpserver"
"go.gearno.de/kit/pg"
)
type (
@@ -35,167 +29,56 @@ type (
}
InvitationResponse struct {
ID gid.GID `json:"id"`
Email string `json:"email"`
FullName string `json:"fullName"`
Role string `json:"role"`
ExpiresAt string `json:"expiresAt"`
AcceptedAt *string `json:"acceptedAt,omitempty"`
CreatedAt string `json:"createdAt"`
Organization OrganizationSummary `json:"organization"`
ID gid.GID `json:"id"`
Email string `json:"email"`
FullName string `json:"fullName"`
Role string `json:"role"`
ExpiresAt string `json:"expiresAt"`
AcceptedAt *string `json:"acceptedAt,omitempty"`
CreatedAt string `json:"createdAt"`
Organization OrganizationResponseSummary `json:"organization"`
}
OrganizationSummary struct {
OrganizationResponseSummary struct {
ID gid.GID `json:"id"`
Name string `json:"name"`
}
)
// loadOrganizationByID loads an organization by ID without tenant scope
func loadOrganizationByID(
ctx context.Context,
conn pg.Conn,
orgID gid.GID,
) (*coredata.Organization, error) {
query := `
SELECT
id,
tenant_id,
name,
logo_file_id,
horizontal_logo_file_id,
description,
website_url,
email,
headquarter_address,
custom_domain_id,
created_at,
updated_at
FROM
authz_organizations
WHERE
id = $1
`
row := conn.QueryRow(ctx, query, orgID)
var org coredata.Organization
err := row.Scan(
&org.ID,
&org.TenantID,
&org.Name,
&org.LogoFileID,
&org.HorizontalLogoFileID,
&org.Description,
&org.WebsiteURL,
&org.Email,
&org.HeadquarterAddress,
&org.CustomDomainID,
&org.CreatedAt,
&org.UpdatedAt,
)
if err != nil {
return nil, fmt.Errorf("cannot load organization: %w", err)
}
return &org, nil
}
func ListInvitationsHandler(authSvc *authsvc.Service, authzSvc *authz.Service, authCfg RoutesConfig) http.HandlerFunc {
func ListInvitationsHandler(authzSvc *authz.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := UserFromContext(ctx)
sessionAuthCfg := session.AuthConfig{
CookieName: authCfg.CookieName,
CookieSecret: authCfg.CookieSecret,
}
errorHandler := session.ErrorHandler{
OnCookieError: func(err error) {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnParseError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnSessionError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("session expired"))
},
OnUserError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("user not found"))
},
OnTenantError: func(err error) {
panic(fmt.Errorf("cannot list tenants for user: %w", err))
},
}
authResult := session.TryAuth(ctx, w, r, authSvc, authzSvc, sessionAuthCfg, errorHandler)
if authResult == nil {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("authentication required"))
return
}
// Get pending invitations for the user
cursor := page.NewCursor(
1000,
nil,
page.Head,
page.OrderBy[coredata.InvitationOrderField]{
Field: coredata.InvitationOrderFieldCreatedAt,
Direction: page.OrderDirectionDesc,
},
)
invitationFilter := coredata.NewInvitationFilter([]coredata.InvitationStatus{coredata.InvitationStatusPending})
invitationsPage, err := authzSvc.GetUserInvitations(ctx, authResult.User.EmailAddress, cursor, invitationFilter)
invitations, err := authzSvc.GetUserPendingInvitations(ctx, user.EmailAddress)
if err != nil {
panic(fmt.Errorf("cannot list invitations for user: %w", err))
}
// Build response
response := ListInvitationsResponse{
Invitations: make([]InvitationResponse, 0, len(invitationsPage.Data)),
Invitations: make([]InvitationResponse, 0, len(invitations)),
}
// Load organization data for each invitation
err = authCfg.PGClient.WithConn(ctx, func(conn pg.Conn) error {
for _, invitation := range invitationsPage.Data {
invitationResp := InvitationResponse{
ID: invitation.ID,
Email: invitation.Email,
FullName: invitation.FullName,
Role: invitation.Role,
ExpiresAt: invitation.ExpiresAt.Format("2006-01-02T15:04:05Z07:00"),
CreatedAt: invitation.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
}
if invitation.AcceptedAt != nil {
acceptedAtStr := invitation.AcceptedAt.Format("2006-01-02T15:04:05Z07:00")
invitationResp.AcceptedAt = &acceptedAtStr
}
// Load organization details
org, err := loadOrganizationByID(ctx, conn, invitation.OrganizationID)
if err != nil {
// Log error but continue - organization might have been deleted
return nil
}
invitationResp.Organization = OrganizationSummary{
ID: org.ID,
Name: org.Name,
}
response.Invitations = append(response.Invitations, invitationResp)
for _, invitation := range invitations {
invitationResp := InvitationResponse{
ID: invitation.ID,
Email: invitation.Email,
FullName: invitation.FullName,
Role: invitation.Role,
ExpiresAt: invitation.ExpiresAt.Format("2006-01-02T15:04:05Z07:00"),
CreatedAt: invitation.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
Organization: OrganizationResponseSummary{
ID: invitation.Organization.ID,
Name: invitation.Organization.Name,
},
}
return nil
})
if err != nil {
panic(fmt.Errorf("cannot load organization details: %w", err))
if invitation.AcceptedAt != nil {
acceptedAtStr := invitation.AcceptedAt.Format("2006-01-02T15:04:05Z07:00")
invitationResp.AcceptedAt = &acceptedAtStr
}
response.Invitations = append(response.Invitations, invitationResp)
}
httpserver.RenderJSON(w, http.StatusOK, response)

View File

@@ -15,20 +15,14 @@
package auth
import (
"context"
"errors"
"fmt"
"net/http"
"time"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/authz"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/filemanager"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/server/session"
"go.gearno.de/kit/httpserver"
"go.gearno.de/kit/pg"
)
type (
@@ -54,145 +48,84 @@ const (
AuthStatusExpired AuthenticationStatus = "expired"
)
// generateLogoURL generates a presigned URL for an organization's logo
func generateLogoURL(
ctx context.Context,
fileManager *filemanager.Service,
conn pg.Conn,
logoFileID *gid.GID,
) (*string, error) {
if logoFileID == nil {
return nil, nil
func buildOrganizationResponse(
org *coredata.Organization,
accessResult authsvc.AccessResult,
sessionData coredata.SessionData,
) OrganizationResponse {
// Generate logo URL path if organization has a logo
var logoURL *string
if org.LogoFileID != nil {
url := fmt.Sprintf("/auth/organizations/%s/logo", org.ID)
logoURL = &url
}
var file coredata.File
// Load file without scope since we're in auth context (cross-tenant)
q := `SELECT bucket_name, file_key, file_name, mime_type, file_size FROM files WHERE id = $1`
err := conn.QueryRow(ctx, q, logoFileID).Scan(
&file.BucketName,
&file.FileKey,
&file.FileName,
&file.MimeType,
&file.FileSize,
)
if err != nil {
return nil, fmt.Errorf("cannot load file: %w", err)
orgResponse := OrganizationResponse{
ID: org.ID,
Name: org.Name,
LogoURL: logoURL,
}
presignedURL, err := fileManager.GenerateFileUrl(ctx, &file, 1*time.Hour)
if err != nil {
return nil, fmt.Errorf("cannot generate file URL: %w", err)
// User does not have required authentication
if !accessResult.Allowed {
orgResponse.AuthStatus = AuthStatusUnauthenticated
switch accessResult.MissingAuth {
case authsvc.AuthMethodSAML, authsvc.AuthMethodAny:
orgResponse.AuthenticationMethod = "saml"
if accessResult.SAMLConfig != nil {
orgResponse.LoginURL = fmt.Sprintf("/auth/saml/login/%s", accessResult.SAMLConfig.ID)
}
case authsvc.AuthMethodPassword:
orgResponse.AuthenticationMethod = "password"
orgResponse.LoginURL = "/authentication/login?method=password"
}
return orgResponse
}
return &presignedURL, nil
// User has required authentication
orgResponse.AuthStatus = AuthStatusAuthenticated
if sessionData.PasswordAuthenticated {
orgResponse.AuthenticationMethod = "password"
orgResponse.LoginURL = "/authentication/login?method=password"
} else if samlInfo, ok := sessionData.SAMLAuthenticatedOrgs[org.ID.String()]; ok {
orgResponse.AuthenticationMethod = "saml"
orgResponse.LoginURL = fmt.Sprintf("/auth/saml/login/%s", samlInfo.SAMLConfigID)
} else {
orgResponse.AuthenticationMethod = "any"
orgResponse.LoginURL = "/authentication/login?method=password"
}
return orgResponse
}
func ListOrganizationsHandler(authSvc *authsvc.Service, authzSvc *authz.Service, authCfg RoutesConfig) http.HandlerFunc {
func ListOrganizationsHandler(authSvc *authsvc.Service, authzSvc *authz.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := UserFromContext(ctx)
sess := SessionFromContext(ctx)
sessionAuthCfg := session.AuthConfig{
CookieName: authCfg.CookieName,
CookieSecret: authCfg.CookieSecret,
}
errorHandler := session.ErrorHandler{
OnCookieError: func(err error) {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnParseError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnSessionError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("session expired"))
},
OnUserError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("user not found"))
},
OnTenantError: func(err error) {
panic(fmt.Errorf("cannot list tenants for user: %w", err))
},
}
authResult := session.TryAuth(ctx, w, r, authSvc, authzSvc, sessionAuthCfg, errorHandler)
if authResult == nil {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("authentication required"))
return
}
// Get all organizations for the user (without filtering by authentication state)
organizations, err := authzSvc.GetAllUserOrganizations(ctx, authResult.User.ID)
organizations, err := authzSvc.GetAllUserOrganizations(ctx, user.ID)
if err != nil {
panic(fmt.Errorf("cannot list organizations for user: %w", err))
}
// Build response with authentication requirements for each organization
orgIDs := make([]gid.GID, len(organizations))
for i, org := range organizations {
orgIDs[i] = org.ID
}
accessResults, err := authSvc.CheckOrganizationAccess(ctx, user, orgIDs, sess)
if err != nil {
panic(fmt.Errorf("cannot check organization access: %w", err))
}
response := ListOrganizationsResponse{
Organizations: make([]OrganizationResponse, 0, len(organizations)),
}
for _, org := range organizations {
orgResponse := OrganizationResponse{
ID: org.ID,
Name: org.Name,
}
// Generate logo URL if available
if authCfg.FileManager != nil && authCfg.PGClient != nil {
err := authCfg.PGClient.WithConn(ctx, func(conn pg.Conn) error {
logoURL, err := generateLogoURL(ctx, authCfg.FileManager, conn, org.LogoFileID)
if err != nil {
// Log error but don't fail the request
return nil
}
orgResponse.LogoURL = logoURL
return nil
})
if err != nil {
// Log error but continue
}
}
// Check authentication requirements for this organization
err := authSvc.CheckOrganizationAccess(ctx, authResult.User, org.ID, authResult.Session)
if err != nil {
// User needs additional authentication
var errSAMLRequired authsvc.ErrSAMLAuthRequired
if errors.As(err, &errSAMLRequired) {
orgResponse.AuthenticationMethod = "saml"
orgResponse.AuthStatus = AuthStatusUnauthenticated
orgResponse.LoginURL = fmt.Sprintf("/auth/saml/login/%s", errSAMLRequired.ConfigID)
} else {
orgResponse.AuthenticationMethod = "password"
orgResponse.AuthStatus = AuthStatusUnauthenticated
orgResponse.LoginURL = "/authentication/login?method=password"
}
} else {
// User has proper authentication
orgResponse.AuthStatus = AuthStatusAuthenticated
// Determine which auth method they used
if authResult.Session.Data.PasswordAuthenticated {
orgResponse.AuthenticationMethod = "password"
orgResponse.LoginURL = "/authentication/login?method=password"
} else if len(authResult.Session.Data.SAMLAuthenticatedOrgs) > 0 {
// Find SAML config for this org
orgResponse.AuthenticationMethod = "saml"
// Try to find the SAML config ID for login URL
if samlInfo, ok := authResult.Session.Data.SAMLAuthenticatedOrgs[org.ID.String()]; ok {
orgResponse.LoginURL = fmt.Sprintf("/auth/saml/login/%s", samlInfo.SAMLConfigID)
} else {
orgResponse.LoginURL = "/authentication/login?method=password"
}
} else {
orgResponse.AuthenticationMethod = "any"
orgResponse.LoginURL = "/authentication/login?method=password"
}
}
accessResult := accessResults[org.ID]
orgResponse := buildOrganizationResponse(org, accessResult, sess.Data)
response.Organizations = append(response.Organizations, orgResponse)
}

View File

@@ -0,0 +1,58 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.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 auth
import (
"context"
"fmt"
"net/http"
"time"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/gid"
"github.com/go-chi/chi/v5"
)
func OrganizationLogoHandler(authSvc *authsvc.Service, fileManager interface {
GenerateFileUrl(ctx context.Context, file *coredata.File, duration time.Duration) (string, error)
}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := UserFromContext(ctx)
session := SessionFromContext(ctx)
organizationIDStr := chi.URLParam(r, "organizationID")
organizationID, err := gid.ParseGID(organizationIDStr)
if err != nil {
http.Error(w, "Invalid organization ID", http.StatusBadRequest)
return
}
logoFile, err := authSvc.GetOrganizationLogoFile(ctx, user, organizationID, session)
if err != nil {
panic(fmt.Errorf("cannot get organization logo: %w", err))
}
presignedURL, err := fileManager.GenerateFileUrl(ctx, logoFile, 1*time.Hour)
if err != nil {
panic(fmt.Errorf("cannot generate presigned URL: %w", err))
}
w.Header().Set("Cache-Control", "public, max-age=3600")
http.Redirect(w, r, presignedURL, http.StatusFound)
}
}

View File

@@ -36,7 +36,7 @@ type (
}
)
func ResetPasswordHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
func ResetPasswordHandler(authSvc *authsvc.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req ResetPasswordRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {

View File

@@ -1,60 +0,0 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.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 auth
import (
"time"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/authz"
"github.com/getprobo/probo/pkg/filemanager"
"github.com/go-chi/chi/v5"
"go.gearno.de/kit/log"
"go.gearno.de/kit/pg"
)
type RoutesConfig struct {
CookieName string
CookieDomain string
SessionDuration time.Duration
CookieSecret string
FileManager *filemanager.Service
PGClient *pg.Client
}
func MountRoutes(
r chi.Router,
authSvc *authsvc.Service,
authzSvc *authz.Service,
samlSvc *authsvc.SAMLService,
authCfg RoutesConfig,
logger *log.Logger,
) {
r.Post("/register", SignUpHandler(authSvc, authCfg))
r.Post("/login", SignInHandler(authSvc, authCfg))
r.Delete("/logout", SignOutHandler(authSvc, authCfg))
r.Post("/signup-from-invitation", SignupFromInvitationHandler(authSvc, authCfg))
r.Post("/forget-password", ForgetPasswordHandler(authSvc, authCfg))
r.Post("/reset-password", ResetPasswordHandler(authSvc, authCfg))
r.Post("/check-sso", SAMLCheckSSOHandler(authSvc, logger))
r.Get("/organizations", ListOrganizationsHandler(authSvc, authzSvc, authCfg))
r.Get("/invitations", ListInvitationsHandler(authSvc, authzSvc, authCfg))
r.Post("/invitations/accept", AcceptInvitationHandler(authSvc, authzSvc, authCfg))
// SAML routes
r.Get("/saml/login/{samlConfigID}", SAMLLoginHandler(samlSvc, authSvc, logger))
r.Post("/saml/consume", SAMLACSHandler(samlSvc, authSvc, authzSvc, authCfg, logger))
r.Get("/saml/metadata", SAMLMetadataHandler(samlSvc))
}

View File

@@ -15,6 +15,7 @@
package auth
import (
"errors"
"fmt"
"net/http"
"time"
@@ -27,11 +28,14 @@ import (
"go.gearno.de/kit/log"
)
func getSessionIDFromCookie(r *http.Request, authCfg RoutesConfig) (gid.GID, error) {
cookieValue, err := securecookie.Get(r, securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
))
func getSessionIDFromCookie(r *http.Request, cookieName string, cookieSecret string) (gid.GID, error) {
cookieValue, err := securecookie.Get(
r,
securecookie.DefaultConfig(
cookieName,
cookieSecret,
),
)
if err != nil {
return gid.GID{}, err
}
@@ -39,7 +43,7 @@ func getSessionIDFromCookie(r *http.Request, authCfg RoutesConfig) (gid.GID, err
return gid.ParseGID(cookieValue)
}
func SAMLACSHandler(samlSvc *authsvc.SAMLService, authSvc *authsvc.Service, authzSvc *authz.Service, authCfg RoutesConfig, logger *log.Logger) http.HandlerFunc {
func SAMLACSHandler(samlSvc *authsvc.SAMLService, authSvc *authsvc.Service, authzSvc *authz.Service, cookieName string, cookieSecret string, sessionDuration time.Duration, logger *log.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
@@ -68,10 +72,32 @@ func SAMLACSHandler(samlSvc *authsvc.SAMLService, authSvc *authsvc.Service, auth
return
}
user, err := authSvc.CreateOrGetSAMLUser(ctx, userInfo.Email, userInfo.FullName, userInfo.SAMLSubject)
var existingSession *coredata.Session
if existingSessionID, err := getSessionIDFromCookie(r, cookieName, cookieSecret); err == nil {
if session, err := authSvc.GetSession(ctx, existingSessionID); err == nil {
existingSession = session
}
}
session, user, err := authSvc.ProvisionSAMLUser(
ctx,
userInfo.SAMLConfigID,
userInfo.OrganizationID,
userInfo.Email,
userInfo.FullName,
userInfo.SAMLSubject,
existingSession,
sessionDuration,
)
if err != nil {
logger.ErrorCtx(ctx, "cannot create or get SAML user", log.Error(err))
http.Error(w, "cannot create user", http.StatusInternalServerError)
var autoSignupDisabledErr *authsvc.ErrSAMLAutoSignupDisabled
if errors.As(err, &autoSignupDisabledErr) {
logger.WarnCtx(ctx, "SAML auto-signup is disabled")
http.Error(w, "User does not exist and auto-signup is disabled for this organization", http.StatusForbidden)
return
}
logger.ErrorCtx(ctx, "cannot provision SAML user", log.Error(err))
http.Error(w, "cannot provision user", http.StatusInternalServerError)
return
}
@@ -83,43 +109,11 @@ func SAMLACSHandler(samlSvc *authsvc.SAMLService, authSvc *authsvc.Service, auth
return
}
var session *coredata.Session
if existingSessionID, err := getSessionIDFromCookie(r, authCfg); err == nil {
if existingSession, err := authSvc.GetSession(ctx, existingSessionID); err == nil && existingSession.UserID == user.ID {
session = existingSession
}
}
if session == nil {
session, err = authSvc.CreateSessionForUser(ctx, user.ID, authCfg.SessionDuration)
if err != nil {
logger.ErrorCtx(ctx, "cannot create session", log.Error(err), log.String("user_id", user.ID.String()))
http.Error(w, "cannot create session", http.StatusInternalServerError)
return
}
}
if session.Data.SAMLAuthenticatedOrgs == nil {
session.Data.SAMLAuthenticatedOrgs = make(map[string]coredata.SAMLAuthInfo)
}
session.Data.SAMLAuthenticatedOrgs[userInfo.OrganizationID.String()] = coredata.SAMLAuthInfo{
AuthenticatedAt: time.Now(),
SAMLConfigID: userInfo.SAMLConfigID,
SAMLSubject: userInfo.SAMLSubject,
}
err = authSvc.UpdateSessionData(ctx, session.ID, session.Data)
if err != nil {
logger.ErrorCtx(ctx, "cannot update session data", log.Error(err), log.String("session_id", session.ID.String()))
http.Error(w, "cannot update session", http.StatusInternalServerError)
return
}
securecookie.Set(
w,
securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
cookieName,
cookieSecret,
),
session.ID.String(),
)

View File

@@ -47,7 +47,7 @@ type (
}
)
func SignInHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
func SignInHandler(authSvc *authsvc.Service, cookieName string, cookieSecret string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req SignInRequest
@@ -57,13 +57,13 @@ func SignInHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerF
}
var existingSession *coredata.Session
if existingSessionID, err := getSessionIDFromCookie(r, authCfg); err == nil {
if existingSessionID, err := getSessionIDFromCookie(r, cookieName, cookieSecret); err == nil {
if session, err := authSvc.GetSession(r.Context(), existingSessionID); err == nil {
existingSession = session
}
}
session, user, err := authSvc.SignInWithExistingSession(r.Context(), req.Email, req.Password, existingSession)
session, user, err := authSvc.SignIn(r.Context(), req.Email, req.Password, existingSession)
if err != nil {
var ErrInvalidCredentials *authsvc.ErrInvalidCredentials
if errors.As(err, &ErrInvalidCredentials) {
@@ -77,8 +77,8 @@ func SignInHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerF
securecookie.Set(
w,
securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
cookieName,
cookieSecret,
),
session.ID.String(),
)

View File

@@ -24,12 +24,12 @@ import (
"go.gearno.de/kit/httpserver"
)
func SignOutHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
func SignOutHandler(authSvc *authsvc.Service, cookieName string, cookieSecret string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
sessionID, err := securecookie.Get(r, securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
cookieName,
cookieSecret,
))
if err != nil {
httpserver.RenderError(w, http.StatusBadRequest, err)
@@ -48,8 +48,8 @@ func SignOutHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.Handler
}
securecookie.Clear(w, securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
cookieName,
cookieSecret,
))
w.Header().Set("Clear-Site-Data", "*")

View File

@@ -37,7 +37,7 @@ type (
}
)
func SignUpHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
func SignUpHandler(authSvc *authsvc.Service, cookieName string, cookieSecret string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req SignUpRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -70,8 +70,8 @@ func SignUpHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerF
securecookie.Set(
w,
securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
cookieName,
cookieSecret,
),
session.ID.String(),
)

View File

@@ -35,7 +35,7 @@ type (
}
)
func SignupFromInvitationHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
func SignupFromInvitationHandler(authSvc *authsvc.Service, cookieName string, cookieSecret string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req SignupFromInvitationRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -52,8 +52,8 @@ func SignupFromInvitationHandler(authSvc *authsvc.Service, authCfg RoutesConfig)
securecookie.Set(
w,
securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
cookieName,
cookieSecret,
),
session.ID.String(),
)