Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Harden outbound SSO fetch boundaries

rcourtman4564742c183d
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 7b7001bfc5..f1994216af 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -135,6 +135,7 @@ management, and fleet control surfaces.
host-agent runtime boundary instead of leaving monitoring to guess.
4. Keep shared `internal/api/` helper edits isolated from agent lifecycle semantics: Patrol-specific status transport or alert-trigger wiring changes in shared handlers must not bleed into auto-register, installer, or fleet-control behavior unless this contract moves in the same slice.
The same isolation rule applies to AI settings payload work in `internal/api/ai_handlers.go`: provider auth fields, masked-secret echoes, and provider-test model selection remain AI/runtime plus API-contract ownership and must not be reinterpreted as lifecycle setup or registration semantics just because they share backend helper layers.
+ The same shared-helper rule now covers SSO outbound discovery and metadata fetches plus credential-file loads in `internal/api/sso_outbound.go`, `internal/api/saml_service.go`, and `internal/api/oidc_service.go`: lifecycle-adjacent setup or auth work may depend on that shared trust boundary, but it must not fork a second HTTP client, redirect policy, or file-read rule inside lifecycle-local flows.
4. Keep legacy Unified Agent compatibility names explicitly secondary when touching shared `internal/api/` runtime helpers: the legacy host-route family and `host-agent:*` scope names may remain as ingress or migration aliases, but they must not retake primary ownership in router state, live runtime scope checks, handler commentary, or operator-facing guidance.
5. Add or change installer flags, persisted service arguments, or upgrade-safe re-entry behavior through `scripts/install.sh` and `scripts/install.ps1`.
6. Add or change profile management, the extracted agent profiles runtime owner, the pure unified-agent inventory/install model, the API-backed platform connections workspace shell, route model, reporting summary owner, shared install/inventory/dialog section owners, the split infrastructure install/reporting state owners, the split direct-node/discovery infrastructure settings owners plus their shared model, shared frontend install-command assembly, Proxmox setup/install API transport, TrueNAS platform-connection management, VMware platform-connection management, setup-completion install handoff transport, deploy-fallback manual install transport, and fleet-control presentation through `frontend-modern/src/api/agentProfiles.ts`, `frontend-modern/src/api/nodes.ts`, `frontend-modern/src/components/Settings/AgentProfilesPanel.tsx`, `frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`, `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx`, `frontend-modern/src/components/Settings/InfrastructureReportingPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInventorySection.tsx`, `frontend-modern/src/components/Settings/InfrastructureActiveRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureIgnoredRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureStopMonitoringDialog.tsx`, `frontend-modern/src/components/Settings/InfrastructurePlatformConnectionsSummaryCard.tsx`, `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx`, `frontend-modern/src/components/Settings/infrastructureWorkspaceModel.ts`, `frontend-modern/src/components/Settings/PlatformConnectionsWorkspace.tsx`, `frontend-modern/src/components/Settings/platformConnectionsModel.ts`, `frontend-modern/src/components/Settings/TrueNASSettingsPanel.tsx`, `frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts`, `frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx`, `frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts`, `frontend-modern/src/components/Settings/ProxmoxSettingsPanel.tsx`, `frontend-modern/src/components/Settings/proxmoxSettingsModel.ts`, `frontend-modern/src/components/Settings/ProxmoxDirectWorkspace.tsx`, `frontend-modern/src/components/Settings/ProxmoxConfiguredNodesTable.tsx`, `frontend-modern/src/components/Settings/ProxmoxDirectConnectionsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDiscoveryResultsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDeleteNodeDialog.tsx`, `frontend-modern/src/components/Settings/ProxmoxNodeModalStack.tsx`, `frontend-modern/src/components/Settings/ConfiguredNodeTables.tsx`, `frontend-modern/src/components/Settings/SettingsSectionNav.tsx`, `frontend-modern/src/components/Settings/infrastructureSettingsModel.ts`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts`, `frontend-modern/src/components/Settings/useProxmoxDirectWorkspaceState.ts`, `frontend-modern/src/components/Settings/NodeModal.tsx`, `frontend-modern/src/components/Settings/nodeModalModel.ts`, `frontend-modern/src/components/Settings/useNodeModalState.ts`, `frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx`, and `frontend-modern/src/utils/agentInstallCommand.ts`.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 2c502fd472..bf532a5d58 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -335,7 +335,10 @@ URL handling. SAML test/preview metadata fetches and OIDC issuer discovery
must normalize absolute HTTP(S) inputs through shared helpers, reject
userinfo-bearing URLs before any outbound request, and append the OIDC
well-known path relative to the issuer base instead of resetting discovery to
-the origin root.
+the origin root. Runtime SAML metadata refresh, runtime OIDC discovery, and
+admin-side SSO test/preview fetches must all use that same restricted outbound
+transport policy, including same-origin redirect validation and checked
+regular-file loads for any configured SSO credential or CA-bundle path.
That same SSO boundary also owns manual SAML endpoint validation payloads.
`internal/api/identity_sso_handlers.go`, `internal/api/saml_service.go`, and
`internal/api/contract_test.go` must preserve both `idpSsoUrl` and optional
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index be39b1d651..32cf4a4f90 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -67,6 +67,7 @@ querying, and the operator-facing storage health presentation layer.
provider-backed recovery: storage and recovery must treat `truenas_disabled`
as an explicit platform opt-out, not as the baseline onboarding state for a
supported platform.
+ That same adjacent API boundary now also owns SSO outbound discovery and metadata fetch trust: storage- and recovery-adjacent surfaces may share `internal/api/sso_outbound.go`, `internal/api/saml_service.go`, and `internal/api/oidc_service.go`, but they must not fork separate metadata/discovery HTTP clients, redirect policies, or credential-file read rules when they depend on shared backend auth helpers.
5. Route canonical storage/recovery resource selection through `frontend-modern/src/hooks/useUnifiedResources.ts` and the owning `unified-resources` contract
That shared hook now also projects resource `clusterId` through the shared cluster-name helper, so storage and recovery links keep the same cluster-context label as other unified-resource consumers instead of rebuilding a local fallback chain.
6. Preserve API-owned node identity continuity in shared `internal/api/` helpers so storage and recovery transport attachments do not fork by hostname-versus-IP drift across the same runtime.
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 3e4238dfe1..15c6e46723 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -1280,6 +1280,117 @@ func TestContract_SSOTestOIDCDiscoveryKeepsIssuerBasePath(t *testing.T) {
}
}
+func TestContract_SSOTestRejectsCrossOriginSAMLMetadataRedirect(t *testing.T) {
+ targetCalled := make(chan struct{}, 1)
+ target := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case targetCalled <- struct{}{}:
+ default:
+ }
+ w.Header().Set("Content-Type", "application/xml")
+ w.Write([]byte(testSAMLMetadata))
+ }))
+ defer target.Close()
+
+ origin := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, target.URL+r.URL.Path, http.StatusFound)
+ }))
+ defer origin.Close()
+
+ reqBody := SSOTestRequest{
+ Type: "saml",
+ SAML: &SAMLTestConfig{
+ IDPMetadataURL: origin.URL + "/metadata",
+ },
+ }
+ body, err := json.Marshal(reqBody)
+ if err != nil {
+ t.Fatalf("marshal request: %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/test", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleTestSSOProvider(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusBadRequest, rec.Body.String())
+ }
+
+ select {
+ case <-targetCalled:
+ t.Fatal("expected cross-origin SAML redirect to be rejected before fetching the target origin")
+ default:
+ }
+}
+
+func TestContract_SSOTestRejectsCrossOriginOIDCDiscoveryRedirect(t *testing.T) {
+ targetCalled := make(chan struct{}, 1)
+ var targetURL string
+ target := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/.well-known/openid-configuration" {
+ http.NotFound(w, r)
+ return
+ }
+ select {
+ case targetCalled <- struct{}{}:
+ default:
+ }
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprintf(w, `{
+ "issuer": %q,
+ "authorization_endpoint": %q,
+ "token_endpoint": %q,
+ "userinfo_endpoint": %q,
+ "jwks_uri": %q,
+ "scopes_supported": ["openid", "profile", "email"]
+ }`, targetURL, targetURL+"/auth", targetURL+"/token", targetURL+"/userinfo", targetURL+"/jwks")
+ }))
+ defer target.Close()
+ targetURL = target.URL
+
+ origin := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/.well-known/openid-configuration" {
+ http.NotFound(w, r)
+ return
+ }
+ http.Redirect(w, r, target.URL+r.URL.Path, http.StatusFound)
+ }))
+ defer origin.Close()
+
+ reqBody := SSOTestRequest{
+ Type: "oidc",
+ OIDC: &OIDCTestConfig{
+ IssuerURL: origin.URL,
+ },
+ }
+ body, err := json.Marshal(reqBody)
+ if err != nil {
+ t.Fatalf("marshal request: %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/test", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleTestSSOProvider(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusBadRequest, rec.Body.String())
+ }
+
+ select {
+ case <-targetCalled:
+ t.Fatal("expected cross-origin OIDC redirect to be rejected before fetching the target origin")
+ default:
+ }
+}
+
func TestContract_SSOLocalRedirectTargetsStayCanonical(t *testing.T) {
if got := buildLocalRedirectTarget("https://evil.example.com/pwn", map[string]string{
"oidc": "error",
diff --git a/internal/api/identity_sso_handlers.go b/internal/api/identity_sso_handlers.go
index 6d3102cc04..c4b6df2731 100644
--- a/internal/api/identity_sso_handlers.go
+++ b/internal/api/identity_sso_handlers.go
@@ -2,7 +2,6 @@ package api
import (
"context"
- "crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
@@ -1216,18 +1215,11 @@ func (r *Router) handleMetadataPreview(w http.ResponseWriter, req *http.Request)
// ============================================================================
func newTestHTTPClient() *http.Client {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.TLSClientConfig = &tls.Config{
- MinVersion: tls.VersionTLS12,
- }
- return &http.Client{
- Transport: transport,
- Timeout: testConnectionTimeout,
- }
+ return newSSOHTTPClient(testConnectionTimeout, nil)
}
func fetchSAMLMetadataFromURL(ctx context.Context, client *http.Client, metadataURL string) ([]byte, *saml.EntityDescriptor, error) {
- targetURL, err := securityutil.NormalizeAbsoluteHTTPURL(metadataURL)
+ targetURL, err := validateSSOFetchURL(ctx, metadataURL)
if err != nil {
return nil, nil, err
}
diff --git a/internal/api/main_test.go b/internal/api/main_test.go
index 2dbd781a61..8e71cb2e56 100644
--- a/internal/api/main_test.go
+++ b/internal/api/main_test.go
@@ -11,5 +11,6 @@ import (
func TestMain(m *testing.M) {
_ = os.Setenv("PULSE_TEST_BCRYPT_COST", strconv.Itoa(bcrypt.MinCost))
_ = os.Setenv("PULSE_UPDATE_SERVER", "http://127.0.0.1:1")
+ allowLoopbackSSOFetch = true
os.Exit(m.Run())
}
diff --git a/internal/api/oidc_service.go b/internal/api/oidc_service.go
index 05f296baa9..eb7fa9fcae 100644
--- a/internal/api/oidc_service.go
+++ b/internal/api/oidc_service.go
@@ -17,6 +17,7 @@ import (
"github.com/coreos/go-oidc/v3/oidc"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
"github.com/rs/zerolog/log"
"golang.org/x/oauth2"
)
@@ -348,20 +349,11 @@ func (s *OIDCService) RefreshToken(ctx context.Context, refreshToken string) (*O
}
func newOIDCHTTPClient(caBundle string) (*http.Client, string, error) {
- transport, ok := http.DefaultTransport.(*http.Transport)
- var clone *http.Transport
- if ok && transport != nil {
- clone = transport.Clone()
- } else {
- clone = &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- }
- }
if strings.TrimSpace(caBundle) == "" {
- return &http.Client{Transport: clone}, "", nil
+ return newSSOHTTPClient(0, nil), "", nil
}
- caData, err := os.ReadFile(caBundle)
+ caData, err := readSSORegularFile(caBundle)
if err != nil {
return nil, "", fmt.Errorf("failed to read OIDC CA bundle: %w", err)
}
@@ -375,16 +367,14 @@ func newOIDCHTTPClient(caBundle string) (*http.Client, string, error) {
return nil, "", fmt.Errorf("OIDC CA bundle does not contain any certificates")
}
- if clone.TLSClientConfig == nil {
- clone.TLSClientConfig = &tls.Config{}
+ tlsConfig := &tls.Config{
+ RootCAs: pool,
}
- clone.TLSClientConfig.MinVersion = tls.VersionTLS12
- clone.TLSClientConfig.RootCAs = pool
sum := sha256.Sum256(caData)
caHash := fmt.Sprintf("%x", sum[:])
- return &http.Client{Transport: clone}, caHash, nil
+ return securityutil.NewRestrictedOutboundHTTPClient(0, ssoOutboundHTTPOptions(tlsConfig)), caHash, nil
}
func hashCABundle(path string) (string, error) {
diff --git a/internal/api/oidc_service_test.go b/internal/api/oidc_service_test.go
index 7fd5ccae6d..01d48c8de7 100644
--- a/internal/api/oidc_service_test.go
+++ b/internal/api/oidc_service_test.go
@@ -5,6 +5,7 @@ import (
"encoding/pem"
"errors"
"net/http"
+ "net/http/httptest"
"os"
"strings"
"testing"
@@ -93,4 +94,30 @@ func TestNewOIDCHTTPClient_InvalidPEMData(t *testing.T) {
}
}
+func TestNewOIDCHTTPClient_BlocksCrossOriginRedirects(t *testing.T) {
+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer target.Close()
+
+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, target.URL+r.URL.Path, http.StatusFound)
+ }))
+ defer origin.Close()
+
+ client, _, err := newOIDCHTTPClient("")
+ if err != nil {
+ t.Fatalf("newOIDCHTTPClient() error = %v", err)
+ }
+ client.Timeout = testHTTPTimeout
+
+ resp, err := client.Get(origin.URL)
+ if resp != nil {
+ resp.Body.Close()
+ }
+ if err == nil || !strings.Contains(err.Error(), "same origin") {
+ t.Fatalf("expected same-origin redirect rejection, got %v", err)
+ }
+}
+
const testHTTPTimeout = 2 * time.Second
diff --git a/internal/api/saml_service.go b/internal/api/saml_service.go
index c7082268b7..1585904d31 100644
--- a/internal/api/saml_service.go
+++ b/internal/api/saml_service.go
@@ -3,7 +3,6 @@ package api
import (
"context"
"crypto/rsa"
- "crypto/tls"
"crypto/x509"
"encoding/pem"
"encoding/xml"
@@ -12,7 +11,6 @@ import (
"io"
"net/http"
"net/url"
- "os"
"strings"
"sync"
"time"
@@ -74,14 +72,7 @@ func NewSAMLService(ctx context.Context, providerID string, cfg *config.SAMLProv
}
func newSAMLHTTPClient() *http.Client {
- transport := http.DefaultTransport.(*http.Transport).Clone()
- transport.TLSClientConfig = &tls.Config{
- MinVersion: tls.VersionTLS12,
- }
- return &http.Client{
- Transport: transport,
- Timeout: 30 * time.Second,
- }
+ return newSSOHTTPClient(30*time.Second, nil)
}
// loadIDPMetadata loads Identity Provider metadata from URL or XML
@@ -122,7 +113,7 @@ func (s *SAMLService) loadIDPMetadata(ctx context.Context) error {
}
func (s *SAMLService) fetchIDPMetadataFromURL(ctx context.Context, metadataURL string) (*saml.EntityDescriptor, error) {
- targetURL, err := securityutil.NormalizeAbsoluteHTTPURL(metadataURL)
+ targetURL, err := validateSSOFetchURL(ctx, metadataURL)
if err != nil {
return nil, err
}
@@ -234,7 +225,7 @@ func (s *SAMLService) addIDPCertificate(metadata *saml.EntityDescriptor) error {
var err error
if s.config.IDPCertFile != "" {
- certData, err = os.ReadFile(s.config.IDPCertFile)
+ certData, err = readSSORegularFile(s.config.IDPCertFile)
if err != nil {
return fmt.Errorf("failed to read idp certificate file: %w", err)
}
@@ -348,7 +339,7 @@ func (s *SAMLService) loadSPCredentials() (*x509.Certificate, *rsa.PrivateKey, e
// Load certificate
if s.config.SPCertFile != "" {
- certData, err = os.ReadFile(s.config.SPCertFile)
+ certData, err = readSSORegularFile(s.config.SPCertFile)
if err != nil {
return nil, nil, fmt.Errorf("failed to read sp certificate file: %w", err)
}
@@ -360,7 +351,7 @@ func (s *SAMLService) loadSPCredentials() (*x509.Certificate, *rsa.PrivateKey, e
// Load private key
if s.config.SPKeyFile != "" {
- keyData, err = os.ReadFile(s.config.SPKeyFile)
+ keyData, err = readSSORegularFile(s.config.SPKeyFile)
if err != nil {
return nil, nil, fmt.Errorf("failed to read sp private key file: %w", err)
}
diff --git a/internal/api/saml_service_additional_test.go b/internal/api/saml_service_additional_test.go
index 00c1aea53b..9c8a72f914 100644
--- a/internal/api/saml_service_additional_test.go
+++ b/internal/api/saml_service_additional_test.go
@@ -122,6 +122,24 @@ func TestFetchIDPMetadataFromURL_NonOK(t *testing.T) {
}
}
+func TestFetchIDPMetadataFromURL_RejectsCrossOriginRedirect(t *testing.T) {
+ target := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ w.Write([]byte(testSAMLMetadata))
+ }))
+ defer target.Close()
+
+ origin := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, target.URL+r.URL.Path, http.StatusFound)
+ }))
+ defer origin.Close()
+
+ service := &SAMLService{httpClient: newSAMLHTTPClient()}
+ if _, err := service.fetchIDPMetadataFromURL(context.Background(), origin.URL+"/metadata"); err == nil || !strings.Contains(err.Error(), "same origin") {
+ t.Fatalf("expected same-origin redirect rejection, got %v", err)
+ }
+}
+
func TestAddIDPCertificate_InvalidPEM(t *testing.T) {
service := &SAMLService{config: &config.SAMLProviderConfig{IDPCertificate: "not-pem"}}
metadata := &saml.EntityDescriptor{
diff --git a/internal/api/sso_handlers_test.go b/internal/api/sso_handlers_test.go
index 37d60e1538..02e2cbaf10 100644
--- a/internal/api/sso_handlers_test.go
+++ b/internal/api/sso_handlers_test.go
@@ -253,6 +253,47 @@ func TestHandleTestSSOProvider_OIDCSuccess(t *testing.T) {
}
}
+func TestHandleTestSSOProvider_OIDCRedirectRejected(t *testing.T) {
+ target := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/.well-known/openid-configuration" {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte(testOIDCDiscovery))
+ }))
+ defer target.Close()
+
+ origin := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/.well-known/openid-configuration" {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ http.Redirect(w, r, target.URL+r.URL.Path, http.StatusFound)
+ }))
+ defer origin.Close()
+
+ reqBody := SSOTestRequest{
+ Type: "oidc",
+ OIDC: &OIDCTestConfig{
+ IssuerURL: origin.URL,
+ },
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/test", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleTestSSOProvider(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d: %s", http.StatusBadRequest, rec.Code, rec.Body.String())
+ }
+}
+
func TestHandleTestSSOProvider_OIDCFetchError(t *testing.T) {
reqBody := SSOTestRequest{
Type: "oidc",
diff --git a/internal/api/sso_outbound.go b/internal/api/sso_outbound.go
new file mode 100644
index 0000000000..9d6c57d247
--- /dev/null
+++ b/internal/api/sso_outbound.go
@@ -0,0 +1,57 @@
+package api
+
+import (
+ "context"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
+)
+
+var allowLoopbackSSOFetch bool
+
+func ssoOutboundHTTPOptions(tlsConfig *tls.Config) securityutil.RestrictedOutboundHTTPOptions {
+ return securityutil.RestrictedOutboundHTTPOptions{
+ AllowedSchemes: []string{"http", "https"},
+ AllowPrivateIPs: true,
+ AllowLoopback: allowLoopbackSSOFetch,
+ TLSConfig: tlsConfig,
+ }
+}
+
+func validateSSOFetchURL(ctx context.Context, rawURL string) (*url.URL, error) {
+ return securityutil.ValidateOutboundFetchURL(ctx, rawURL, ssoOutboundHTTPOptions(nil))
+}
+
+func newSSOHTTPClient(timeout time.Duration, tlsConfig *tls.Config) *http.Client {
+ return securityutil.NewRestrictedOutboundHTTPClient(timeout, ssoOutboundHTTPOptions(tlsConfig))
+}
+
+func readSSORegularFile(rawPath string) ([]byte, error) {
+ cleaned := filepath.Clean(strings.TrimSpace(rawPath))
+ if cleaned == "" {
+ return nil, errors.New("SSO file path is empty")
+ }
+
+ absolute, err := filepath.Abs(cleaned)
+ if err != nil {
+ return nil, fmt.Errorf("resolve SSO file path: %w", err)
+ }
+
+ info, err := os.Stat(absolute)
+ if err != nil {
+ return nil, err
+ }
+ if !info.Mode().IsRegular() {
+ return nil, fmt.Errorf("SSO file must be a regular file")
+ }
+
+ return os.ReadFile(absolute)
+}
diff --git a/internal/securityutil/outbound_http.go b/internal/securityutil/outbound_http.go
new file mode 100644
index 0000000000..5e02fce37f
--- /dev/null
+++ b/internal/securityutil/outbound_http.go
@@ -0,0 +1,232 @@
+package securityutil
+
+import (
+ "context"
+ "crypto/tls"
+ "fmt"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+)
+
+const defaultRestrictedRedirectLimit = 10
+
+// RestrictedOutboundHTTPOptions controls outbound HTTP validation and transport policy.
+type RestrictedOutboundHTTPOptions struct {
+ AllowedSchemes []string
+ AllowPrivateIPs bool
+ AllowLoopback bool
+ TLSConfig *tls.Config
+}
+
+var resolveOutboundFetchIPs = net.DefaultResolver.LookupIPAddr
+
+func allowedOutboundSchemes(opts RestrictedOutboundHTTPOptions) []string {
+ if len(opts.AllowedSchemes) == 0 {
+ return []string{"http", "https"}
+ }
+ return opts.AllowedSchemes
+}
+
+func isAllowedOutboundScheme(scheme string, allowed []string) bool {
+ for _, candidate := range allowed {
+ if strings.EqualFold(strings.TrimSpace(candidate), scheme) {
+ return true
+ }
+ }
+ return false
+}
+
+func validateOutboundIP(ip net.IP, opts RestrictedOutboundHTTPOptions) error {
+ if ip == nil {
+ return fmt.Errorf("invalid IP address")
+ }
+ if ip.IsLoopback() && !opts.AllowLoopback {
+ return fmt.Errorf("loopback addresses are not allowed")
+ }
+ if ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
+ return fmt.Errorf("link-local addresses are not allowed")
+ }
+ if ip.IsMulticast() {
+ return fmt.Errorf("multicast addresses are not allowed")
+ }
+ if ip.IsUnspecified() {
+ return fmt.Errorf("unspecified addresses are not allowed")
+ }
+ if ip.Equal(net.ParseIP("169.254.169.254")) {
+ return fmt.Errorf("metadata service address is not allowed")
+ }
+ if !opts.AllowPrivateIPs && ip.IsPrivate() {
+ return fmt.Errorf("private addresses are not allowed")
+ }
+ return nil
+}
+
+func resolvePermittedOutboundIP(ctx context.Context, host string, opts RestrictedOutboundHTTPOptions) (net.IP, error) {
+ host = strings.TrimSpace(host)
+ if host == "" {
+ return nil, fmt.Errorf("URL hostname is required")
+ }
+
+ switch strings.ToLower(host) {
+ case "metadata.google.internal", "metadata.goog":
+ return nil, fmt.Errorf("metadata service host is not allowed")
+ }
+
+ if ip := net.ParseIP(host); ip != nil {
+ if err := validateOutboundIP(ip, opts); err != nil {
+ return nil, err
+ }
+ return ip, nil
+ }
+
+ baseCtx := ctx
+ if baseCtx == nil {
+ baseCtx = context.Background()
+ }
+ resolveCtx, cancel := context.WithTimeout(baseCtx, 5*time.Second)
+ defer cancel()
+
+ addrs, err := resolveOutboundFetchIPs(resolveCtx, host)
+ if err != nil {
+ return nil, fmt.Errorf("failed to resolve hostname %s: %w", host, err)
+ }
+ if len(addrs) == 0 {
+ return nil, fmt.Errorf("hostname %s did not resolve", host)
+ }
+
+ var blockedErr error
+ for _, addr := range addrs {
+ if err := validateOutboundIP(addr.IP, opts); err != nil {
+ blockedErr = err
+ continue
+ }
+ return addr.IP, nil
+ }
+
+ if blockedErr != nil {
+ return nil, fmt.Errorf("hostname %s resolves only to blocked addresses: %w", host, blockedErr)
+ }
+ return nil, fmt.Errorf("hostname %s did not resolve", host)
+}
+
+// ValidateOutboundFetchURL validates a fully-qualified HTTP(S) URL against the restricted outbound policy.
+func ValidateOutboundFetchURL(ctx context.Context, raw string, opts RestrictedOutboundHTTPOptions) (*url.URL, error) {
+ parsed, err := NormalizeAbsoluteHTTPURL(raw)
+ if err != nil {
+ return nil, err
+ }
+
+ allowedSchemes := allowedOutboundSchemes(opts)
+ if !isAllowedOutboundScheme(parsed.Scheme, allowedSchemes) {
+ return nil, fmt.Errorf("URL scheme must be one of: %s", strings.Join(allowedSchemes, ", "))
+ }
+ if parsed.Fragment != "" {
+ return nil, fmt.Errorf("URL fragments are not allowed")
+ }
+
+ if _, err := resolvePermittedOutboundIP(ctx, parsed.Hostname(), opts); err != nil {
+ return nil, err
+ }
+
+ return parsed, nil
+}
+
+func canonicalOriginHost(u *url.URL) string {
+ if u == nil {
+ return ""
+ }
+
+ host := strings.ToLower(u.Hostname())
+ port := u.Port()
+ if port == "" {
+ switch strings.ToLower(u.Scheme) {
+ case "http":
+ port = "80"
+ case "https":
+ port = "443"
+ }
+ }
+ if host == "" || port == "" {
+ return strings.ToLower(u.Host)
+ }
+ return net.JoinHostPort(host, port)
+}
+
+func sameOriginRedirectPolicy(opts RestrictedOutboundHTTPOptions) func(req *http.Request, via []*http.Request) error {
+ return func(req *http.Request, via []*http.Request) error {
+ if len(via) == 0 {
+ return nil
+ }
+ if len(via) >= defaultRestrictedRedirectLimit {
+ return fmt.Errorf("stopped after %d redirects", defaultRestrictedRedirectLimit)
+ }
+
+ validated, err := ValidateOutboundFetchURL(req.Context(), req.URL.String(), opts)
+ if err != nil {
+ return err
+ }
+
+ origin := via[0].URL
+ if !strings.EqualFold(validated.Scheme, origin.Scheme) || canonicalOriginHost(validated) != canonicalOriginHost(origin) {
+ return fmt.Errorf("redirects must stay on the same origin")
+ }
+ return nil
+ }
+}
+
+func cloneRestrictedTransport(tlsConfig *tls.Config) *http.Transport {
+ transport, ok := http.DefaultTransport.(*http.Transport)
+ var clone *http.Transport
+ if ok && transport != nil {
+ clone = transport.Clone()
+ } else {
+ clone = &http.Transport{Proxy: http.ProxyFromEnvironment}
+ }
+
+ switch {
+ case tlsConfig != nil:
+ clone.TLSClientConfig = tlsConfig.Clone()
+ case clone.TLSClientConfig != nil:
+ clone.TLSClientConfig = clone.TLSClientConfig.Clone()
+ default:
+ clone.TLSClientConfig = &tls.Config{}
+ }
+
+ if clone.TLSClientConfig.MinVersion < tls.VersionTLS12 {
+ clone.TLSClientConfig.MinVersion = tls.VersionTLS12
+ }
+
+ return clone
+}
+
+// NewRestrictedOutboundHTTPClient returns an HTTP client that validates redirects and pins direct outbound dials
+// to the first permitted resolved IP for the requested host.
+func NewRestrictedOutboundHTTPClient(timeout time.Duration, opts RestrictedOutboundHTTPOptions) *http.Client {
+ transport := cloneRestrictedTransport(opts.TLSConfig)
+ transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ host, port, err := net.SplitHostPort(addr)
+ if err != nil {
+ return nil, fmt.Errorf("parse outbound address %q: %w", addr, err)
+ }
+
+ permittedIP, err := resolvePermittedOutboundIP(ctx, host, opts)
+ if err != nil {
+ return nil, err
+ }
+
+ dialer := net.Dialer{Timeout: 10 * time.Second}
+ return dialer.DialContext(ctx, network, net.JoinHostPort(permittedIP.String(), port))
+ }
+
+ client := &http.Client{
+ Transport: transport,
+ CheckRedirect: sameOriginRedirectPolicy(opts),
+ }
+ if timeout > 0 {
+ client.Timeout = timeout
+ }
+ return client
+}
diff --git a/internal/securityutil/outbound_http_test.go b/internal/securityutil/outbound_http_test.go
new file mode 100644
index 0000000000..efeece7548
--- /dev/null
+++ b/internal/securityutil/outbound_http_test.go
@@ -0,0 +1,67 @@
+package securityutil
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestValidateOutboundFetchURLRejectsLoopbackByDefault(t *testing.T) {
+ if _, err := ValidateOutboundFetchURL(context.Background(), "http://127.0.0.1:8443/metadata", RestrictedOutboundHTTPOptions{
+ AllowedSchemes: []string{"http", "https"},
+ AllowPrivateIPs: true,
+ }); err == nil || !strings.Contains(err.Error(), "loopback") {
+ t.Fatalf("expected loopback rejection, got %v", err)
+ }
+}
+
+func TestValidateOutboundFetchURLAllowsLoopbackWhenRequested(t *testing.T) {
+ target, err := ValidateOutboundFetchURL(context.Background(), "http://127.0.0.1:8443/metadata", RestrictedOutboundHTTPOptions{
+ AllowedSchemes: []string{"http", "https"},
+ AllowPrivateIPs: true,
+ AllowLoopback: true,
+ })
+ if err != nil {
+ t.Fatalf("ValidateOutboundFetchURL() error = %v", err)
+ }
+ if target.Host != "127.0.0.1:8443" {
+ t.Fatalf("unexpected host %q", target.Host)
+ }
+}
+
+func TestValidateOutboundFetchURLRejectsFragment(t *testing.T) {
+ if _, err := ValidateOutboundFetchURL(context.Background(), "https://idp.example.com/metadata#fragment", RestrictedOutboundHTTPOptions{
+ AllowedSchemes: []string{"http", "https"},
+ AllowPrivateIPs: true,
+ }); err == nil || !strings.Contains(err.Error(), "fragments") {
+ t.Fatalf("expected fragment rejection, got %v", err)
+ }
+}
+
+func TestNewRestrictedOutboundHTTPClientBlocksCrossOriginRedirect(t *testing.T) {
+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer target.Close()
+
+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, target.URL+r.URL.Path, http.StatusFound)
+ }))
+ defer origin.Close()
+
+ client := NewRestrictedOutboundHTTPClient(0, RestrictedOutboundHTTPOptions{
+ AllowedSchemes: []string{"http", "https"},
+ AllowPrivateIPs: true,
+ AllowLoopback: true,
+ })
+
+ resp, err := client.Get(origin.URL + "/metadata")
+ if resp != nil {
+ resp.Body.Close()
+ }
+ if err == nil || !strings.Contains(err.Error(), "same origin") {
+ t.Fatalf("expected same-origin redirect rejection, got %v", err)
+ }
+}