Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(system-features): derive nullable SSO protocol (#40063)

yyh5e036e548932
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 4b43a89366a..232ec62e765 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -21383,6 +21383,12 @@ Whitelist scopes accepted by RBAC app and dataset access config APIs.
| instruction | string | Structured output generation instruction | Yes |
| model_config | [ModelConfig](#modelconfig) | Model configuration | Yes |
+#### SSOProtocol
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| SSOProtocol | string | | |
+
#### SandboxFileEntryResponse
| Name | Type | Description | Required |
@@ -22159,7 +22165,7 @@ Non-sensitive bootstrap snapshot exposed before Console or Web authentication.
| plugin_installation_permission | [PluginInstallationPermissionModel](#plugininstallationpermissionmodel) | | Yes |
| rbac_enabled | boolean | | Yes |
| sso_enforced_for_signin | boolean | | Yes |
-| sso_enforced_for_signin_protocol | string | | Yes |
+| sso_enforced_for_signin_protocol | [SSOProtocol](#ssoprotocol) | | Yes |
| webapp_auth | [WebAppAuthModel](#webappauthmodel) | | Yes |
#### SystemParameters
@@ -23125,7 +23131,7 @@ in form definition, or a variable while the workflow is running.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
-| protocol | string | | Yes |
+| protocol | [SSOProtocol](#ssoprotocol) | | Yes |
#### WebhookTriggerResponse
diff --git a/api/openapi/markdown/web-openapi.md b/api/openapi/markdown/web-openapi.md
index c5fe79b60e5..36f2f7a084a 100644
--- a/api/openapi/markdown/web-openapi.md
+++ b/api/openapi/markdown/web-openapi.md
@@ -1448,6 +1448,12 @@ Form input definition.
| summary | string | | No |
| word_count | integer | | No |
+#### SSOProtocol
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| SSOProtocol | string | | |
+
#### SavedMessageCreatePayload
| Name | Type | Description | Required |
@@ -1570,7 +1576,7 @@ Non-sensitive bootstrap snapshot exposed before Console or Web authentication.
| plugin_installation_permission | [PluginInstallationPermissionModel](#plugininstallationpermissionmodel) | | Yes |
| rbac_enabled | boolean | | Yes |
| sso_enforced_for_signin | boolean | | Yes |
-| sso_enforced_for_signin_protocol | string | | Yes |
+| sso_enforced_for_signin_protocol | [SSOProtocol](#ssoprotocol) | | Yes |
| webapp_auth | [WebAppAuthModel](#webappauthmodel) | | Yes |
#### SystemParameters
@@ -1634,7 +1640,7 @@ in form definition, or a variable while the workflow is running.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
-| protocol | string | | Yes |
+| protocol | [SSOProtocol](#ssoprotocol) | | Yes |
#### WebAppCustomConfigResponse
diff --git a/api/services/feature_service.py b/api/services/feature_service.py
index b900fde62f0..e6108e3f503 100644
--- a/api/services/feature_service.py
+++ b/api/services/feature_service.py
@@ -106,14 +106,20 @@ class BrandingModel(FeatureResponseModel):
favicon: str = ""
+class SSOProtocol(StrEnum):
+ SAML = "saml"
+ OIDC = "oidc"
+ OAUTH2 = "oauth2"
+
+
class WebAppAuthSSOModel(FeatureResponseModel):
- protocol: str = ""
+ protocol: SSOProtocol | None = None
class WebAppAuthModel(FeatureResponseModel):
enabled: bool = False
allow_sso: bool = False
- sso_config: WebAppAuthSSOModel = WebAppAuthSSOModel()
+ sso_config: WebAppAuthSSOModel = Field(default_factory=WebAppAuthSSOModel)
allow_email_code_login: bool = False
allow_email_password_login: bool = False
allow_public_access: bool = True
@@ -186,7 +192,7 @@ class SystemFeatureModel(FeatureResponseModel):
deployment_edition: DeploymentEdition
enable_app_deploy: bool = False
sso_enforced_for_signin: bool = False
- sso_enforced_for_signin_protocol: str = ""
+ sso_enforced_for_signin_protocol: SSOProtocol | None = None
enable_marketplace: bool = False
enable_email_code_login: bool = False
enable_email_password_login: bool = True
@@ -196,7 +202,7 @@ class SystemFeatureModel(FeatureResponseModel):
is_email_setup: bool = False
license: LicenseStatusModel = LicenseStatusModel()
branding: BrandingModel = BrandingModel()
- webapp_auth: WebAppAuthModel = WebAppAuthModel()
+ webapp_auth: WebAppAuthModel = Field(default_factory=WebAppAuthModel)
plugin_installation_permission: PluginInstallationPermissionModel = PluginInstallationPermissionModel()
enable_change_email: bool = True
enable_creators_platform: bool = False
@@ -526,6 +532,23 @@ class FeatureService:
restrict_to_marketplace_only=permission.restrict_to_marketplace_only,
)
+ @staticmethod
+ def _resolve_sso_protocol(value: object, *, field_name: str) -> SSOProtocol | None:
+ if value is None or (isinstance(value, str) and not value.strip()):
+ return None
+
+ if not isinstance(value, str):
+ logger.error("Invalid Enterprise SSO protocol for %s; disabling the protocol", field_name)
+ return None
+
+ try:
+ return SSOProtocol(value)
+ except ValueError:
+ logger.error( # noqa: TRY400
+ "Invalid Enterprise SSO protocol for %s; disabling the protocol", field_name
+ )
+ return None
+
@classmethod
def _fulfill_params_from_enterprise(cls, features: SystemFeatureModel):
enterprise_info = EnterpriseService.get_info()
@@ -533,8 +556,10 @@ class FeatureService:
if "SSOEnforcedForSignin" in enterprise_info:
features.sso_enforced_for_signin = enterprise_info["SSOEnforcedForSignin"]
- if "SSOEnforcedForSigninProtocol" in enterprise_info:
- features.sso_enforced_for_signin_protocol = enterprise_info["SSOEnforcedForSigninProtocol"]
+ features.sso_enforced_for_signin_protocol = cls._resolve_sso_protocol(
+ enterprise_info.get("SSOEnforcedForSigninProtocol"),
+ field_name="SSOEnforcedForSigninProtocol",
+ )
if "EnableEmailCodeLogin" in enterprise_info:
features.enable_email_code_login = enterprise_info["EnableEmailCodeLogin"]
@@ -562,7 +587,10 @@ class FeatureService:
features.webapp_auth.allow_email_password_login = enterprise_info["WebAppAuth"].get(
"allowEmailPasswordLogin", False
)
- features.webapp_auth.sso_config.protocol = enterprise_info.get("SSOEnforcedForWebProtocol", "")
+ features.webapp_auth.sso_config.protocol = cls._resolve_sso_protocol(
+ enterprise_info.get("SSOEnforcedForWebProtocol"),
+ field_name="SSOEnforcedForWebProtocol",
+ )
# SECURITY NOTE: system-features is unauthenticated, so it exposes only license
# *status* — enough for the login page to detect an expired/inactive license after
diff --git a/api/tests/test_containers_integration_tests/services/test_feature_service.py b/api/tests/test_containers_integration_tests/services/test_feature_service.py
index 7a86af9f410..3e404062e11 100644
--- a/api/tests/test_containers_integration_tests/services/test_feature_service.py
+++ b/api/tests/test_containers_integration_tests/services/test_feature_service.py
@@ -12,6 +12,7 @@ from services.feature_service import (
KnowledgeRateLimitModel,
LicenseModel,
LicenseStatus,
+ SSOProtocol,
SystemFeatureModel,
)
@@ -301,7 +302,7 @@ class TestFeatureService:
# Verify SSO configuration
assert result.sso_enforced_for_signin is True
- assert result.sso_enforced_for_signin_protocol == "saml"
+ assert result.sso_enforced_for_signin_protocol is SSOProtocol.SAML
# Verify authentication settings
assert result.enable_email_code_login is True
@@ -383,7 +384,7 @@ class TestFeatureService:
# SSO settings should be visible for login page rendering
assert result.sso_enforced_for_signin is True
- assert result.sso_enforced_for_signin_protocol == "saml"
+ assert result.sso_enforced_for_signin_protocol is SSOProtocol.SAML
# General auth settings should be visible
assert result.enable_email_code_login is True
@@ -900,7 +901,7 @@ class TestFeatureService:
assert result.webapp_auth.allow_sso is False
assert result.webapp_auth.allow_email_code_login is True
assert result.webapp_auth.allow_email_password_login is False
- assert result.webapp_auth.sso_config.protocol == ""
+ assert result.webapp_auth.sso_config.protocol is None
# Verify enterprise features
assert result.branding.enabled is True
@@ -909,7 +910,7 @@ class TestFeatureService:
# Verify default values for missing enterprise info
assert result.sso_enforced_for_signin is False
- assert result.sso_enforced_for_signin_protocol == ""
+ assert result.sso_enforced_for_signin_protocol is None
assert result.enable_email_code_login is False
assert result.enable_email_password_login is True
assert result.is_allow_register is False
@@ -1218,7 +1219,7 @@ class TestFeatureService:
# Verify SSO configuration
assert result.sso_enforced_for_signin is True
- assert result.sso_enforced_for_signin_protocol == ""
+ assert result.sso_enforced_for_signin_protocol is None
# Verify branding configuration (partial)
assert result.branding.application_title == "Partial Enterprise"
@@ -1230,7 +1231,7 @@ class TestFeatureService:
assert result.webapp_auth.allow_sso is False
assert result.webapp_auth.allow_email_code_login is False
assert result.webapp_auth.allow_email_password_login is False
- assert result.webapp_auth.sso_config.protocol == ""
+ assert result.webapp_auth.sso_config.protocol is None
# Verify default license status
assert result.license.status == "none"
@@ -1342,8 +1343,8 @@ class TestFeatureService:
assert isinstance(result, SystemFeatureModel)
# Verify edge case protocols
- assert result.sso_enforced_for_signin_protocol == ""
- assert result.webapp_auth.sso_config.protocol == " "
+ assert result.sso_enforced_for_signin_protocol is None
+ assert result.webapp_auth.sso_config.protocol is None
# Verify webapp auth configuration
assert result.webapp_auth.allow_sso is True
@@ -1657,7 +1658,7 @@ class TestFeatureService:
# Verify default values for missing enterprise info
assert result.sso_enforced_for_signin is False
- assert result.sso_enforced_for_signin_protocol == ""
+ assert result.sso_enforced_for_signin_protocol is None
assert result.enable_email_code_login is False
assert result.enable_email_password_login is True
assert result.is_allow_register is False
@@ -1835,7 +1836,7 @@ class TestFeatureService:
# Verify default values for missing enterprise info
assert result.sso_enforced_for_signin is False
- assert result.sso_enforced_for_signin_protocol == ""
+ assert result.sso_enforced_for_signin_protocol is None
assert result.enable_email_code_login is False
assert result.enable_email_password_login is True
assert result.is_allow_register is False
diff --git a/api/tests/unit_tests/controllers/console/test_feature.py b/api/tests/unit_tests/controllers/console/test_feature.py
index 952f2610161..2682dec674a 100644
--- a/api/tests/unit_tests/controllers/console/test_feature.py
+++ b/api/tests/unit_tests/controllers/console/test_feature.py
@@ -124,6 +124,8 @@ class TestSystemFeatureApi:
assert result["is_allow_register"] is True
assert result["enable_learn_app"] is True
assert result["license"] == {"status": LicenseStatus.NONE}
+ assert result["sso_enforced_for_signin_protocol"] is None
+ assert result["webapp_auth"]["sso_config"]["protocol"] is None
get_system_features.assert_called_once_with()
diff --git a/api/tests/unit_tests/controllers/web/test_feature.py b/api/tests/unit_tests/controllers/web/test_feature.py
index c4701119eff..681546aafe9 100644
--- a/api/tests/unit_tests/controllers/web/test_feature.py
+++ b/api/tests/unit_tests/controllers/web/test_feature.py
@@ -21,6 +21,8 @@ class TestSystemFeatureApi:
result = SystemFeatureApi().get()
assert result == system_features.model_dump()
+ assert result["sso_enforced_for_signin_protocol"] is None
+ assert result["webapp_auth"]["sso_config"]["protocol"] is None
mock_features.assert_called_once()
@patch("controllers.web.feature.FeatureService.get_system_features")
diff --git a/api/tests/unit_tests/services/test_feature_service_sso_protocol.py b/api/tests/unit_tests/services/test_feature_service_sso_protocol.py
new file mode 100644
index 00000000000..5740fa5f724
--- /dev/null
+++ b/api/tests/unit_tests/services/test_feature_service_sso_protocol.py
@@ -0,0 +1,87 @@
+import logging
+
+import pytest
+
+from enums.deployment_edition import DeploymentEdition
+from services import feature_service as feature_service_module
+from services.feature_service import FeatureService, SSOProtocol, SystemFeatureModel
+
+
+def test_system_features_exposes_valid_enterprise_sso_protocols(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ feature_service_module.EnterpriseService,
+ "get_info",
+ staticmethod(
+ lambda: {
+ "SSOEnforcedForSigninProtocol": "saml",
+ "WebAppAuth": {},
+ "SSOEnforcedForWebProtocol": "oidc",
+ }
+ ),
+ )
+ features = SystemFeatureModel(deployment_edition=DeploymentEdition.ENTERPRISE)
+
+ FeatureService._fulfill_params_from_enterprise(features)
+
+ assert features.sso_enforced_for_signin_protocol is SSOProtocol.SAML
+ assert features.webapp_auth.sso_config.protocol is SSOProtocol.OIDC
+
+
[email protected]("empty_protocol", [None, "", " "])
+def test_system_features_normalizes_empty_enterprise_sso_protocols_to_none(
+ monkeypatch: pytest.MonkeyPatch,
+ empty_protocol: object,
+) -> None:
+ monkeypatch.setattr(
+ feature_service_module.EnterpriseService,
+ "get_info",
+ staticmethod(
+ lambda: {
+ "SSOEnforcedForSigninProtocol": empty_protocol,
+ "WebAppAuth": {},
+ "SSOEnforcedForWebProtocol": empty_protocol,
+ }
+ ),
+ )
+ features = SystemFeatureModel(deployment_edition=DeploymentEdition.ENTERPRISE)
+
+ FeatureService._fulfill_params_from_enterprise(features)
+
+ assert features.sso_enforced_for_signin_protocol is None
+ assert features.webapp_auth.sso_config.protocol is None
+
+
[email protected]("invalid_protocol", ["unknown", 42])
+def test_system_features_rejects_invalid_enterprise_sso_protocols(
+ caplog: pytest.LogCaptureFixture,
+ monkeypatch: pytest.MonkeyPatch,
+ invalid_protocol: object,
+) -> None:
+ monkeypatch.setattr(
+ feature_service_module.EnterpriseService,
+ "get_info",
+ staticmethod(
+ lambda: {
+ "SSOEnforcedForSigninProtocol": invalid_protocol,
+ "WebAppAuth": {},
+ "SSOEnforcedForWebProtocol": invalid_protocol,
+ }
+ ),
+ )
+ features = SystemFeatureModel(deployment_edition=DeploymentEdition.ENTERPRISE)
+
+ with caplog.at_level(logging.ERROR, logger="services.feature_service"):
+ FeatureService._fulfill_params_from_enterprise(features)
+
+ assert features.sso_enforced_for_signin_protocol is None
+ assert features.webapp_auth.sso_config.protocol is None
+ assert caplog.text.count("Invalid Enterprise SSO protocol") == 2
+
+
+def test_system_features_defaults_sso_protocols_to_none() -> None:
+ features = SystemFeatureModel(deployment_edition=DeploymentEdition.COMMUNITY)
+
+ assert features.sso_enforced_for_signin_protocol is None
+ assert features.webapp_auth.sso_config.protocol is None
diff --git a/packages/contracts/generated/api/console/system-features/types.gen.ts b/packages/contracts/generated/api/console/system-features/types.gen.ts
index 46ccea0793b..47bc300d800 100644
--- a/packages/contracts/generated/api/console/system-features/types.gen.ts
+++ b/packages/contracts/generated/api/console/system-features/types.gen.ts
@@ -25,7 +25,7 @@ export type SystemFeatureModel = {
plugin_installation_permission: PluginInstallationPermissionModel
rbac_enabled: boolean
sso_enforced_for_signin: boolean
- sso_enforced_for_signin_protocol: string
+ sso_enforced_for_signin_protocol: SsoProtocol | null
webapp_auth: WebAppAuthModel
}
@@ -55,6 +55,8 @@ export type PluginInstallationPermissionModel = {
restrict_to_marketplace_only: boolean
}
+export type SsoProtocol = 'oauth2' | 'oidc' | 'saml'
+
export type WebAppAuthModel = {
allow_email_code_login: boolean
allow_email_password_login: boolean
@@ -79,7 +81,7 @@ export type PluginInstallationScope =
| 'official_only'
export type WebAppAuthSsoModel = {
- protocol: string
+ protocol: SsoProtocol | null
}
export type GetSystemFeaturesData = {
diff --git a/packages/contracts/generated/api/console/system-features/zod.gen.ts b/packages/contracts/generated/api/console/system-features/zod.gen.ts
index 7c2d20f47db..bfbc6d53d1b 100644
--- a/packages/contracts/generated/api/console/system-features/zod.gen.ts
+++ b/packages/contracts/generated/api/console/system-features/zod.gen.ts
@@ -20,6 +20,11 @@ export const zBrandingModel = z.object({
*/
export const zDeploymentEdition = z.enum(['CLOUD', 'COMMUNITY', 'ENTERPRISE'])
+/**
+ * SSOProtocol
+ */
+export const zSsoProtocol = z.enum(['oauth2', 'oidc', 'saml'])
+
/**
* LicenseLimitationModel
*
@@ -85,7 +90,7 @@ export const zPluginInstallationPermissionModel = z.object({
* WebAppAuthSSOModel
*/
export const zWebAppAuthSsoModel = z.object({
- protocol: z.string().default(''),
+ protocol: zSsoProtocol.nullable(),
})
/**
@@ -97,7 +102,7 @@ export const zWebAppAuthModel = z.object({
allow_public_access: z.boolean().default(true),
allow_sso: z.boolean().default(false),
enabled: z.boolean().default(false),
- sso_config: zWebAppAuthSsoModel.default({ protocol: '' }),
+ sso_config: zWebAppAuthSsoModel,
})
/**
@@ -135,15 +140,8 @@ export const zSystemFeatureModel = z.object({
}),
rbac_enabled: z.boolean().default(false),
sso_enforced_for_signin: z.boolean().default(false),
- sso_enforced_for_signin_protocol: z.string().default(''),
- webapp_auth: zWebAppAuthModel.default({
- allow_email_code_login: false,
- allow_email_password_login: false,
- allow_public_access: true,
- allow_sso: false,
- enabled: false,
- sso_config: { protocol: '' },
- }),
+ sso_enforced_for_signin_protocol: zSsoProtocol.nullable(),
+ webapp_auth: zWebAppAuthModel,
})
/**
diff --git a/packages/contracts/generated/api/web/types.gen.ts b/packages/contracts/generated/api/web/types.gen.ts
index 8812b164b9e..f95ed066bb5 100644
--- a/packages/contracts/generated/api/web/types.gen.ts
+++ b/packages/contracts/generated/api/web/types.gen.ts
@@ -433,6 +433,8 @@ export type RetrieverResource = {
word_count?: number | null
}
+export type SsoProtocol = 'oauth2' | 'oidc' | 'saml'
+
export type SavedMessageCreatePayload = {
message_id: string
}
@@ -528,7 +530,7 @@ export type SystemFeatureModel = {
plugin_installation_permission: PluginInstallationPermissionModel
rbac_enabled: boolean
sso_enforced_for_signin: boolean
- sso_enforced_for_signin_protocol: string
+ sso_enforced_for_signin_protocol: SsoProtocol | null
webapp_auth: WebAppAuthModel
}
@@ -571,7 +573,7 @@ export type WebAppAuthModel = {
}
export type WebAppAuthSsoModel = {
- protocol: string
+ protocol: SsoProtocol | null
}
export type WebAppCustomConfigResponse = {
diff --git a/packages/contracts/generated/api/web/zod.gen.ts b/packages/contracts/generated/api/web/zod.gen.ts
index 59eed414d4b..36ebdd700fc 100644
--- a/packages/contracts/generated/api/web/zod.gen.ts
+++ b/packages/contracts/generated/api/web/zod.gen.ts
@@ -513,6 +513,11 @@ export const zRetrieverResource = z.object({
word_count: z.int().nullish(),
})
+/**
+ * SSOProtocol
+ */
+export const zSsoProtocol = z.enum(['oauth2', 'oidc', 'saml'])
+
/**
* SavedMessageCreatePayload
*/
@@ -746,7 +751,7 @@ export const zVerificationTokenResponse = z.object({
* WebAppAuthSSOModel
*/
export const zWebAppAuthSsoModel = z.object({
- protocol: z.string().default(''),
+ protocol: zSsoProtocol.nullable(),
})
/**
@@ -758,7 +763,7 @@ export const zWebAppAuthModel = z.object({
allow_public_access: z.boolean().default(true),
allow_sso: z.boolean().default(false),
enabled: z.boolean().default(false),
- sso_config: zWebAppAuthSsoModel.default({ protocol: '' }),
+ sso_config: zWebAppAuthSsoModel,
})
/**
@@ -796,15 +801,8 @@ export const zSystemFeatureModel = z.object({
}),
rbac_enabled: z.boolean().default(false),
sso_enforced_for_signin: z.boolean().default(false),
- sso_enforced_for_signin_protocol: z.string().default(''),
- webapp_auth: zWebAppAuthModel.default({
- allow_email_code_login: false,
- allow_email_password_login: false,
- allow_public_access: true,
- allow_sso: false,
- enabled: false,
- sso_config: { protocol: '' },
- }),
+ sso_enforced_for_signin_protocol: zSsoProtocol.nullable(),
+ webapp_auth: zWebAppAuthModel,
})
/**
diff --git a/web/app/(shareLayout)/webapp-signin/components/__tests__/external-member-sso-auth.spec.tsx b/web/app/(shareLayout)/webapp-signin/components/__tests__/external-member-sso-auth.spec.tsx
index 8d35179829f..ae72faecbb0 100644
--- a/web/app/(shareLayout)/webapp-signin/components/__tests__/external-member-sso-auth.spec.tsx
+++ b/web/app/(shareLayout)/webapp-signin/components/__tests__/external-member-sso-auth.spec.tsx
@@ -1,5 +1,5 @@
-import { waitFor } from '@testing-library/react'
-import { SSOProtocol } from '@/features/system-features/constants'
+import { zSsoProtocol } from '@dify/contracts/api/console/system-features/zod.gen'
+import { screen, waitFor } from '@testing-library/react'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import ExternalMemberSSOAuth from '../external-member-sso-auth'
@@ -33,10 +33,21 @@ describe('ExternalMemberSSOAuth redirect security', () => {
})
})
+ it('should show unavailable without starting SSO when the protocol is not configured', () => {
+ renderWithConsoleQuery(<ExternalMemberSSOAuth />, {
+ systemFeatures: { webapp_auth: { sso_config: { protocol: null } } },
+ })
+
+ expect(screen.getByText('sso protocol is invalid.')).toBeInTheDocument()
+ expect(serviceMocks.fetchWebSAMLSSOUrl).not.toHaveBeenCalled()
+ expect(serviceMocks.fetchWebOIDCSSOUrl).not.toHaveBeenCalled()
+ expect(serviceMocks.fetchWebOAuth2SSOUrl).not.toHaveBeenCalled()
+ })
+
it('should use the login fallback without calling SSO when the redirect target is external', async () => {
renderWithConsoleQuery(<ExternalMemberSSOAuth />, {
systemFeatures: {
- webapp_auth: { sso_config: { protocol: SSOProtocol.SAML } },
+ webapp_auth: { sso_config: { protocol: zSsoProtocol.enum.saml } },
},
})
@@ -49,9 +60,9 @@ describe('ExternalMemberSSOAuth redirect security', () => {
})
it.each([
- [SSOProtocol.SAML, serviceMocks.fetchWebSAMLSSOUrl],
- [SSOProtocol.OIDC, serviceMocks.fetchWebOIDCSSOUrl],
- [SSOProtocol.OAuth2, serviceMocks.fetchWebOAuth2SSOUrl],
+ [zSsoProtocol.enum.saml, serviceMocks.fetchWebSAMLSSOUrl],
+ [zSsoProtocol.enum.oidc, serviceMocks.fetchWebOIDCSSOUrl],
+ [zSsoProtocol.enum.oauth2, serviceMocks.fetchWebOAuth2SSOUrl],
])('should send the sanitized redirect target to %s SSO', async (protocol, serviceMock) => {
navigationMocks.searchParams = new URLSearchParams({
redirect_url: encodeURIComponent('/chatbot/share-app?foo=bar'),
diff --git a/web/app/(shareLayout)/webapp-signin/components/__tests__/sso-auth.spec.tsx b/web/app/(shareLayout)/webapp-signin/components/__tests__/sso-auth.spec.tsx
index d9f8d43376e..7b74c2d23e5 100644
--- a/web/app/(shareLayout)/webapp-signin/components/__tests__/sso-auth.spec.tsx
+++ b/web/app/(shareLayout)/webapp-signin/components/__tests__/sso-auth.spec.tsx
@@ -1,5 +1,5 @@
+import { zSsoProtocol } from '@dify/contracts/api/console/system-features/zod.gen'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
-import { SSOProtocol } from '@/features/system-features/constants'
import SSOAuth from '../sso-auth'
const navigationMocks = vi.hoisted(() => ({
@@ -33,7 +33,7 @@ describe('SSOAuth redirect security', () => {
})
it('should use the login fallback without calling SSO when the redirect target is external', async () => {
- render(<SSOAuth protocol={SSOProtocol.SAML} />)
+ render(<SSOAuth protocol={zSsoProtocol.enum.saml} />)
fireEvent.click(screen.getByRole('button', { name: 'login.withSSO' }))
@@ -46,9 +46,9 @@ describe('SSOAuth redirect security', () => {
})
it.each([
- [SSOProtocol.SAML, serviceMocks.fetchMembersSAMLSSOUrl],
- [SSOProtocol.OIDC, serviceMocks.fetchMembersOIDCSSOUrl],
- [SSOProtocol.OAuth2, serviceMocks.fetchMembersOAuth2SSOUrl],
+ [zSsoProtocol.enum.saml, serviceMocks.fetchMembersSAMLSSOUrl],
+ [zSsoProtocol.enum.oidc, serviceMocks.fetchMembersOIDCSSOUrl],
+ [zSsoProtocol.enum.oauth2, serviceMocks.fetchMembersOAuth2SSOUrl],
])('should send the sanitized redirect target to %s SSO', async (protocol, serviceMock) => {
navigationMocks.searchParams = new URLSearchParams({
redirect_url: encodeURIComponent('/chatbot/share-app?foo=bar'),
diff --git a/web/app/(shareLayout)/webapp-signin/components/external-member-sso-auth.tsx b/web/app/(shareLayout)/webapp-signin/components/external-member-sso-auth.tsx
index c05e471a8d0..49b2d932f0f 100644
--- a/web/app/(shareLayout)/webapp-signin/components/external-member-sso-auth.tsx
+++ b/web/app/(shareLayout)/webapp-signin/components/external-member-sso-auth.tsx
@@ -1,4 +1,5 @@
'use client'
+import { zSsoProtocol } from '@dify/contracts/api/console/system-features/zod.gen'
import { toast } from '@langgenius/dify-ui/toast'
import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
@@ -7,7 +8,6 @@ import { resolveWebAppLoginRedirect } from '@/app/(shareLayout)/webapp-signin/lo
import AppUnavailable from '@/app/components/base/app-unavailable'
import Loading from '@/app/components/base/loading'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
-import { SSOProtocol } from '@/features/system-features/constants'
import { useRouter, useSearchParams } from '@/next/navigation'
import { fetchWebOAuth2SSOUrl, fetchWebOIDCSSOUrl, fetchWebSAMLSSOUrl } from '@/service/share'
import { getClientLoginFallback } from '@/utils/login-redirect'
@@ -20,30 +20,29 @@ const ExternalMemberSSOAuth = () => {
const router = useRouter()
const redirectUrl = searchParams.get('redirect_url')
-
- const showErrorToast = (message: string) => {
- toast.error(message)
- }
+ const protocol = systemFeatures.webapp_auth.sso_config.protocol
const handleSSOLogin = useCallback(async () => {
+ if (protocol === null) return
+
const loginRedirect = resolveWebAppLoginRedirect(redirectUrl, window.location.origin)
if (!loginRedirect) {
replaceLoginRedirect(getClientLoginFallback(), router.replace, basePath)
return
}
- switch (systemFeatures.webapp_auth.sso_config.protocol) {
- case SSOProtocol.SAML: {
+ switch (protocol) {
+ case zSsoProtocol.enum.saml: {
const samlRes = await fetchWebSAMLSSOUrl(loginRedirect.appCode, loginRedirect.target.href)
router.push(samlRes.url)
break
}
- case SSOProtocol.OIDC: {
+ case zSsoProtocol.enum.oidc: {
const oidcRes = await fetchWebOIDCSSOUrl(loginRedirect.appCode, loginRedirect.target.href)
router.push(oidcRes.url)
break
}
- case SSOProtocol.OAuth2: {
+ case zSsoProtocol.enum.oauth2: {
const oauth2Res = await fetchWebOAuth2SSOUrl(
loginRedirect.appCode,
loginRedirect.target.href,
@@ -51,18 +50,16 @@ const ExternalMemberSSOAuth = () => {
router.push(oauth2Res.url)
break
}
- case '':
- break
default:
- showErrorToast('SSO protocol is not supported.')
+ toast.error('SSO protocol is not supported.')
}
- }, [redirectUrl, router, systemFeatures.webapp_auth.sso_config.protocol])
+ }, [protocol, redirectUrl, router])
useEffect(() => {
handleSSOLogin()
}, [handleSSOLogin])
- if (!systemFeatures.webapp_auth.sso_config.protocol) {
+ if (protocol === null) {
return (
<div className="flex h-full items-center justify-center">
<AppUnavailable code={403} unknownReason="sso protocol is invalid." />
diff --git a/web/app/(shareLayout)/webapp-signin/components/sso-auth.tsx b/web/app/(shareLayout)/webapp-signin/components/sso-auth.tsx
index 6411d59e6c3..73cdffa360f 100644
--- a/web/app/(shareLayout)/webapp-signin/components/sso-auth.tsx
+++ b/web/app/(shareLayout)/webapp-signin/components/sso-auth.tsx
@@ -1,11 +1,12 @@
'use client'
+import type { SsoProtocol } from '@dify/contracts/api/console/system-features/types.gen'
+import { zSsoProtocol } from '@dify/contracts/api/console/system-features/zod.gen'
import { Button } from '@langgenius/dify-ui/button'
import { toast } from '@langgenius/dify-ui/toast'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { resolveWebAppLoginRedirect } from '@/app/(shareLayout)/webapp-signin/login-redirect'
import { Lock01 } from '@/app/components/base/icons/src/vender/solid/security'
-import { SSOProtocol } from '@/features/system-features/constants'
import { useRouter, useSearchParams } from '@/next/navigation'
import {
fetchMembersOAuth2SSOUrl,
@@ -17,7 +18,7 @@ import { replaceLoginRedirect } from '@/utils/login-redirect.client'
import { basePath } from '@/utils/var'
type SSOAuthProps = {
- protocol: string
+ protocol: SsoProtocol
}
function SSOAuth({ protocol }: SSOAuthProps) {
@@ -41,7 +42,7 @@ function SSOAuth({ protocol }: SSOAuthProps) {
return
}
setIsLoading(true)
- if (protocol === SSOProtocol.SAML) {
+ if (protocol === zSsoProtocol.enum.saml) {
fetchMembersSAMLSSOUrl(loginRedirect.appCode, loginRedirect.target.href)
.then((res) => {
router.push(res.url)
@@ -49,7 +50,7 @@ function SSOAuth({ protocol }: SSOAuthProps) {
.finally(() => {
setIsLoading(false)
})
- } else if (protocol === SSOProtocol.OIDC) {
+ } else if (protocol === zSsoProtocol.enum.oidc) {
fetchMembersOIDCSSOUrl(loginRedirect.appCode, loginRedirect.target.href)
.then((res) => {
router.push(res.url)
@@ -57,7 +58,7 @@ function SSOAuth({ protocol }: SSOAuthProps) {
.finally(() => {
setIsLoading(false)
})
- } else if (protocol === SSOProtocol.OAuth2) {
+ } else if (protocol === zSsoProtocol.enum.oauth2) {
fetchMembersOAuth2SSOUrl(loginRedirect.appCode, loginRedirect.target.href)
.then((res) => {
router.push(res.url)
diff --git a/web/app/(shareLayout)/webapp-signin/normalForm.tsx b/web/app/(shareLayout)/webapp-signin/normalForm.tsx
index bfefe3ef074..8e4f085670c 100644
--- a/web/app/(shareLayout)/webapp-signin/normalForm.tsx
+++ b/web/app/(shareLayout)/webapp-signin/normalForm.tsx
@@ -21,6 +21,8 @@ const NormalForm = () => {
const isNonCloudEdition =
systemFeatures.deployment_edition === 'COMMUNITY' ||
systemFeatures.deployment_edition === 'ENTERPRISE'
+ const ssoProtocol = systemFeatures.sso_enforced_for_signin_protocol
+ const hasSsoLogin = systemFeatures.sso_enforced_for_signin && ssoProtocol !== null
const [authType, updateAuthType] = useState<'code' | 'password'>('password')
const [showORLine, setShowORLine] = useState(false)
const [allMethodsAreDisabled, setAllMethodsAreDisabled] = useState(false)
@@ -31,10 +33,10 @@ const NormalForm = () => {
!systemFeatures.enable_social_oauth_login &&
!systemFeatures.enable_email_code_login &&
!systemFeatures.enable_email_password_login &&
- !systemFeatures.sso_enforced_for_signin,
+ !hasSsoLogin,
)
setShowORLine(
- (systemFeatures.enable_social_oauth_login || systemFeatures.sso_enforced_for_signin) &&
+ (systemFeatures.enable_social_oauth_login || hasSsoLogin) &&
(systemFeatures.enable_email_code_login || systemFeatures.enable_email_password_login),
)
updateAuthType(systemFeatures.enable_email_password_login ? 'password' : 'code')
@@ -44,7 +46,7 @@ const NormalForm = () => {
} finally {
setIsLoading(false)
}
- }, [systemFeatures])
+ }, [hasSsoLogin, systemFeatures])
useEffect(() => {
init()
}, [init])
@@ -133,9 +135,9 @@ const NormalForm = () => {
</div>
<div className="relative">
<div className="mt-6 flex flex-col gap-3">
- {systemFeatures.sso_enforced_for_signin && (
+ {hasSsoLogin && (
<div className="w-full">
- <SSOAuth protocol={systemFeatures.sso_enforced_for_signin_protocol} />
+ <SSOAuth protocol={ssoProtocol} />
</div>
)}
</div>
diff --git a/web/app/components/tools/mcp/__tests__/modal.spec.tsx b/web/app/components/tools/mcp/__tests__/modal.spec.tsx
index 1fc627308b7..2ef9347e320 100644
--- a/web/app/components/tools/mcp/__tests__/modal.spec.tsx
+++ b/web/app/components/tools/mcp/__tests__/modal.spec.tsx
@@ -1,4 +1,6 @@
+import type { SsoProtocol } from '@dify/contracts/api/console/system-features/types.gen'
import type { ToolWithProvider } from '@/app/components/workflow/types'
+import { zSsoProtocol } from '@dify/contracts/api/console/system-features/zod.gen'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
@@ -22,7 +24,7 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
// toggle stays hidden even when sso_enforced_for_signin is true.
const mockSystemFeatures = vi.hoisted(() => ({
sso_enforced_for_signin: false,
- sso_enforced_for_signin_protocol: '' as 'oidc' | 'oauth2' | 'saml' | '',
+ sso_enforced_for_signin_protocol: null as SsoProtocol | null,
}))
describe('MCPModal', () => {
beforeEach(() => {
@@ -744,14 +746,14 @@ describe('MCPModal', () => {
describe('Forward-user-identity toggle', () => {
beforeEach(() => {
mockSystemFeatures.sso_enforced_for_signin = false
- mockSystemFeatures.sso_enforced_for_signin_protocol = ''
+ mockSystemFeatures.sso_enforced_for_signin_protocol = null
})
// Helper: turn SSO on with a refresh-capable protocol so the toggle is
// visible. Use this for any test that needs the field rendered.
const enableRefreshCapableSSO = () => {
mockSystemFeatures.sso_enforced_for_signin = true
- mockSystemFeatures.sso_enforced_for_signin_protocol = 'oidc'
+ mockSystemFeatures.sso_enforced_for_signin_protocol = zSsoProtocol.enum.oidc
}
const fillRequiredFields = () => {
@@ -781,14 +783,14 @@ describe('MCPModal', () => {
it('does not render the toggle when SSO protocol is SAML (no refresh model)', () => {
mockSystemFeatures.sso_enforced_for_signin = true
- mockSystemFeatures.sso_enforced_for_signin_protocol = 'saml'
+ mockSystemFeatures.sso_enforced_for_signin_protocol = zSsoProtocol.enum.saml
render(<MCPModal {...defaultProps} />, { wrapper: createWrapper() })
expect(screen.queryByText('tools.mcp.modal.forwardUserIdentity')).not.toBeInTheDocument()
})
it('renders the toggle when SSO protocol is OAuth2', () => {
mockSystemFeatures.sso_enforced_for_signin = true
- mockSystemFeatures.sso_enforced_for_signin_protocol = 'oauth2'
+ mockSystemFeatures.sso_enforced_for_signin_protocol = zSsoProtocol.enum.oauth2
render(<MCPModal {...defaultProps} />, { wrapper: createWrapper() })
expect(screen.getByText('tools.mcp.modal.forwardUserIdentity')).toBeInTheDocument()
})
diff --git a/web/app/components/tools/mcp/modal.tsx b/web/app/components/tools/mcp/modal.tsx
index 8400446102f..f6e289aa046 100644
--- a/web/app/components/tools/mcp/modal.tsx
+++ b/web/app/components/tools/mcp/modal.tsx
@@ -3,6 +3,7 @@ import type { FC } from 'react'
import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import type { AppIconType } from '@/types/app'
+import { zSsoProtocol } from '@dify/contracts/api/console/system-features/zod.gen'
import { Button } from '@langgenius/dify-ui/button'
import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { Input } from '@langgenius/dify-ui/input'
@@ -26,9 +27,6 @@ import HeadersSection from './sections/headers-section'
// therefore can back MCP per-user identity forwarding. SAML cannot — it has
// no refresh model and no token endpoint, so the enterprise side returns the
// disabled stub for it.
-const MCP_FORWARDING_CAPABLE_PROTOCOLS = ['oidc', 'oauth2'] as const
-type MCPForwardingCapableProtocol = (typeof MCP_FORWARDING_CAPABLE_PROTOCOLS)[number]
-
type MCPModalConfirmPayload = {
name: string
server_url: string
@@ -73,10 +71,10 @@ const MCPModalContent: FC<MCPModalContentProps> = ({ data, onConfirm, onHide })
// SAML has no refresh_token model, so the enterprise side can't mint
// per-call MCP tokens. Only OIDC and OAuth2 can — gate the toggle on
// both "SSO enforced" AND "protocol is refresh-capable".
- const ssoProtocol =
- systemFeatures.sso_enforced_for_signin_protocol as MCPForwardingCapableProtocol
+ const ssoProtocol = systemFeatures.sso_enforced_for_signin_protocol
const isForwardIdentitySupported =
- systemFeatures.sso_enforced_for_signin && MCP_FORWARDING_CAPABLE_PROTOCOLS.includes(ssoProtocol)
+ systemFeatures.sso_enforced_for_signin &&
+ (ssoProtocol === zSsoProtocol.enum.oidc || ssoProtocol === zSsoProtocol.enum.oauth2)
const isHovering = useHover(appIconRef)
diff --git a/web/app/device/page.tsx b/web/app/device/page.tsx
index c597dc01262..c8a211dd6e8 100644
--- a/web/app/device/page.tsx
+++ b/web/app/device/page.tsx
@@ -66,7 +66,7 @@ export default function DevicePage() {
const ssoAvailable =
sys.webapp_auth.enabled &&
sys.webapp_auth.allow_sso &&
- sys.webapp_auth.sso_config.protocol !== ''
+ sys.webapp_auth.sso_config.protocol !== null
// URL-driven view transitions. Only advances while the user is still on
// the entry/chooser screens — never clobbers terminal views (success /
diff --git a/web/app/signin/__tests__/normal-form.spec.tsx b/web/app/signin/__tests__/normal-form.spec.tsx
index fffae8ecc1c..7272be8617b 100644
--- a/web/app/signin/__tests__/normal-form.spec.tsx
+++ b/web/app/signin/__tests__/normal-form.spec.tsx
@@ -224,4 +224,20 @@ describe('NormalForm', () => {
)
expect(screen.getByLabelText('login.password')).toHaveAttribute('type', 'text')
})
+
+ it('should not expose SSO when it is enforced without a configured protocol', () => {
+ mockQueryResults(
+ nonInviteQueryResult as unknown as ReturnType<typeof useQuery>,
+ nonInviteQueryResult as unknown as ReturnType<typeof useQuery>,
+ )
+
+ render(<NormalForm />, {
+ systemFeatures: {
+ sso_enforced_for_signin: true,
+ sso_enforced_for_signin_protocol: null,
+ },
+ })
+
+ expect(screen.queryByRole('button', { name: 'login.withSSO' })).not.toBeInTheDocument()
+ })
})
diff --git a/web/app/signin/components/sso-auth.tsx b/web/app/signin/components/sso-auth.tsx
index f6da2122e00..0f08b4e55d4 100644
--- a/web/app/signin/components/sso-auth.tsx
+++ b/web/app/signin/components/sso-auth.tsx
@@ -1,16 +1,17 @@
'use client'
+import type { SsoProtocol } from '@dify/contracts/api/console/system-features/types.gen'
import type { FC } from 'react'
+import { zSsoProtocol } from '@dify/contracts/api/console/system-features/zod.gen'
import { Button } from '@langgenius/dify-ui/button'
import { toast } from '@langgenius/dify-ui/toast'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Lock01 } from '@/app/components/base/icons/src/vender/solid/security'
-import { SSOProtocol } from '@/features/system-features/constants'
import { useRouter, useSearchParams } from '@/next/navigation'
import { getUserOAuth2SSOUrl, getUserOIDCSSOUrl, getUserSAMLSSOUrl } from '@/service/sso'
type SSOAuthProps = {
- protocol: string
+ protocol: SsoProtocol
}
const SSOAuth: FC<SSOAuthProps> = ({ protocol }) => {
@@ -23,7 +24,7 @@ const SSOAuth: FC<SSOAuthProps> = ({ protocol }) => {
const handleSSOLogin = () => {
setIsLoading(true)
- if (protocol === SSOProtocol.SAML) {
+ if (protocol === zSsoProtocol.enum.saml) {
getUserSAMLSSOUrl(invite_token)
.then((res) => {
router.push(res.url)
@@ -31,7 +32,7 @@ const SSOAuth: FC<SSOAuthProps> = ({ protocol }) => {
.finally(() => {
setIsLoading(false)
})
- } else if (protocol === SSOProtocol.OIDC) {
+ } else if (protocol === zSsoProtocol.enum.oidc) {
getUserOIDCSSOUrl(invite_token)
.then((res) => {
document.cookie = `user-oidc-state=${res.state};Path=/`
@@ -40,7 +41,7 @@ const SSOAuth: FC<SSOAuthProps> = ({ protocol }) => {
.finally(() => {
setIsLoading(false)
})
- } else if (protocol === SSOProtocol.OAuth2) {
+ } else if (protocol === zSsoProtocol.enum.oauth2) {
getUserOAuth2SSOUrl(invite_token)
.then((res) => {
document.cookie = `user-oauth2-state=${res.state};Path=/`
diff --git a/web/app/signin/normal-form.tsx b/web/app/signin/normal-form.tsx
index 216b8027ee6..9bc55d0121c 100644
--- a/web/app/signin/normal-form.tsx
+++ b/web/app/signin/normal-form.tsx
@@ -75,7 +75,8 @@ function NormalForm() {
userResp?.profile.email,
)
const hasSocialLogin = systemFeatures.enable_social_oauth_login
- const hasSsoLogin = Boolean(systemFeatures.sso_enforced_for_signin)
+ const ssoProtocol = systemFeatures.sso_enforced_for_signin_protocol
+ const hasSsoLogin = systemFeatures.sso_enforced_for_signin && ssoProtocol !== null
const hasEmailCodeLogin = systemFeatures.enable_email_code_login
const hasEmailPasswordLogin = systemFeatures.enable_email_password_login
const hasEmailLogin = hasEmailCodeLogin || hasEmailPasswordLogin
@@ -214,7 +215,7 @@ function NormalForm() {
{hasSocialLogin && <SocialAuth />}
{hasSsoLogin && (
<div className="w-full">
- <SSOAuth protocol={systemFeatures.sso_enforced_for_signin_protocol} />
+ <SSOAuth protocol={ssoProtocol} />
</div>
)}
</div>
diff --git a/web/features/system-features/constants.ts b/web/features/system-features/constants.ts
deleted file mode 100644
index 3338bce8ef8..00000000000
--- a/web/features/system-features/constants.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export const SSOProtocol = {
- SAML: 'saml',
- OIDC: 'oidc',
- OAuth2: 'oauth2',
-} as const
diff --git a/web/test/console/system-features.ts b/web/test/console/system-features.ts
index 04cb4bb6edc..e3d779d9fb7 100644
--- a/web/test/console/system-features.ts
+++ b/web/test/console/system-features.ts
@@ -18,7 +18,7 @@ const baseSystemFeatures = {
deployment_edition: 'COMMUNITY',
enable_app_deploy: false,
sso_enforced_for_signin: false,
- sso_enforced_for_signin_protocol: '',
+ sso_enforced_for_signin_protocol: null,
enable_marketplace: false,
enable_email_code_login: false,
enable_email_password_login: true,
@@ -41,7 +41,7 @@ const baseSystemFeatures = {
enabled: false,
allow_sso: false,
sso_config: {
- protocol: '',
+ protocol: null,
},
allow_email_code_login: false,
allow_email_password_login: false,