From 2c8b29e8dfb7cc56fd28ed33e99910ba83ba2d86 Mon Sep 17 00:00:00 2001 From: 00055624 Date: Tue, 29 Sep 2026 14:55:42 +0800 Subject: [PATCH] T-34 feat: enterprise LDAP developer login (JNDI, reuses external-identity flow) - LdapClient: JNDI bind + search, RFC4515 filter escaping, injectable Connect for tests - LdapConfig + DeveloperAuthType.LDAP + PortalSettingConfig.ldap - LdapService/LdapServiceImpl: resolve DN (pattern or admin-search), bind verify, find-or-create developer via existing external-identity flow, issue token - DeveloperController POST /developers/ldap/login - LdapServiceImplTest: 5 cases green (existing/new developer, bind fail, unconfigured, search mode) --- .../support/enums/DeveloperAuthType.java | 5 + .../himarket/support/portal/LdapConfig.java | 68 +++++++ .../support/portal/PortalSettingConfig.java | 5 + .../controller/DeveloperController.java | 14 ++ .../himarket/core/ldap/LdapClient.java | 171 ++++++++++++++++ .../alibaba/himarket/service/LdapService.java | 44 +++++ .../service/impl/LdapServiceImpl.java | 176 +++++++++++++++++ .../service/impl/LdapServiceImplTest.java | 183 ++++++++++++++++++ 8 files changed, 666 insertions(+) create mode 100644 himarket-dal/src/main/java/com/alibaba/himarket/support/portal/LdapConfig.java create mode 100644 himarket-server/src/main/java/com/alibaba/himarket/core/ldap/LdapClient.java create mode 100644 himarket-server/src/main/java/com/alibaba/himarket/service/LdapService.java create mode 100644 himarket-server/src/main/java/com/alibaba/himarket/service/impl/LdapServiceImpl.java create mode 100644 himarket-server/src/test/java/com/alibaba/himarket/service/impl/LdapServiceImplTest.java diff --git a/himarket-dal/src/main/java/com/alibaba/himarket/support/enums/DeveloperAuthType.java b/himarket-dal/src/main/java/com/alibaba/himarket/support/enums/DeveloperAuthType.java index d3bfc0662..1c106b2aa 100644 --- a/himarket-dal/src/main/java/com/alibaba/himarket/support/enums/DeveloperAuthType.java +++ b/himarket-dal/src/main/java/com/alibaba/himarket/support/enums/DeveloperAuthType.java @@ -31,6 +31,11 @@ public enum DeveloperAuthType { OIDC, OAUTH2, + + /** + * Enterprise LDAP bind authentication (T-34). + */ + LDAP, ; public boolean isBuiltIn() { diff --git a/himarket-dal/src/main/java/com/alibaba/himarket/support/portal/LdapConfig.java b/himarket-dal/src/main/java/com/alibaba/himarket/support/portal/LdapConfig.java new file mode 100644 index 000000000..c95e83e51 --- /dev/null +++ b/himarket-dal/src/main/java/com/alibaba/himarket/support/portal/LdapConfig.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.alibaba.himarket.support.portal; + +import lombok.Data; + +/** + * Portal-level LDAP authentication configuration (T-34). Stored inside + * PortalSettingConfig; absent/empty ldap.url disables the LDAP login path. + */ +@Data +public class LdapConfig { + + /** e.g. ldap://10.2.7.31:389 */ + private String url; + + /** Admin/bind DN used for the user search, e.g. cn=root */ + private String bindDn; + + /** Admin/bind password (encrypted at rest by the existing portal config cipher). */ + private String bindPassword; + + /** + * Search base for locating users, e.g. dc=lyf,dc=intl. When empty, userDnPattern + * is used directly and no search is performed. + */ + private String userSearchBase; + + /** LDAP filter with {0} placeholder for the login username, e.g. (uid={0}). */ + private String userSearchFilter; + + /** + * Direct DN pattern with {0} placeholder, e.g. uid={0},ou=people,dc=lyf,dc=intl. + * Used when userSearchBase is empty (skips the admin search round-trip). + */ + private String userDnPattern; + + /** Attribute mapped to the developer display name (optional). */ + private String displayNameAttribute; + + /** enabled reports whether LDAP login is configured. */ + public boolean enabled() { + return url != null + && !url.isBlank() + && ((userDnPattern != null && !userDnPattern.isBlank()) + || (userSearchBase != null + && !userSearchBase.isBlank() + && userSearchFilter != null + && !userSearchFilter.isBlank())); + } +} diff --git a/himarket-dal/src/main/java/com/alibaba/himarket/support/portal/PortalSettingConfig.java b/himarket-dal/src/main/java/com/alibaba/himarket/support/portal/PortalSettingConfig.java index fd5cae24f..2cb457c26 100644 --- a/himarket-dal/src/main/java/com/alibaba/himarket/support/portal/PortalSettingConfig.java +++ b/himarket-dal/src/main/java/com/alibaba/himarket/support/portal/PortalSettingConfig.java @@ -49,4 +49,9 @@ public class PortalSettingConfig { * OAuth2 configurations */ private List oauth2Configs; + + /** + * LDAP authentication configuration (T-34) + */ + private LdapConfig ldap; } diff --git a/himarket-server/src/main/java/com/alibaba/himarket/controller/DeveloperController.java b/himarket-server/src/main/java/com/alibaba/himarket/controller/DeveloperController.java index 31eceeb9d..1ddd3a99e 100644 --- a/himarket-server/src/main/java/com/alibaba/himarket/controller/DeveloperController.java +++ b/himarket-server/src/main/java/com/alibaba/himarket/controller/DeveloperController.java @@ -32,6 +32,7 @@ import com.alibaba.himarket.dto.result.common.PageResult; import com.alibaba.himarket.dto.result.developer.DeveloperResult; import com.alibaba.himarket.service.DeveloperService; +import com.alibaba.himarket.service.LdapService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; @@ -58,6 +59,8 @@ public class DeveloperController { private final DeveloperService developerService; + private final LdapService ldapService; + @Operation(summary = "Register developer", description = "Register a new developer account") @PostMapping public AuthResult register(@Valid @RequestBody CreateDeveloperParam param) { @@ -77,6 +80,17 @@ public void logout(HttpServletRequest request) { developerService.logout(request); } + @Operation( + summary = "Log in with enterprise LDAP", + description = + "Authenticate with enterprise LDAP credentials when the portal has LDAP" + + " enabled") + @PostMapping("/ldap/login") + @PublicAccess + public AuthResult ldapLogin(@Valid @RequestBody LoginParam param) { + return ldapService.login(param.getUsername(), param.getPassword()); + } + @Operation( summary = "List portal developers", description = "Administrator API for listing developers in the current portal") diff --git a/himarket-server/src/main/java/com/alibaba/himarket/core/ldap/LdapClient.java b/himarket-server/src/main/java/com/alibaba/himarket/core/ldap/LdapClient.java new file mode 100644 index 000000000..5d1f6be84 --- /dev/null +++ b/himarket-server/src/main/java/com/alibaba/himarket/core/ldap/LdapClient.java @@ -0,0 +1,171 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.alibaba.himarket.core.ldap; + +import java.util.Hashtable; +import javax.naming.Context; +import javax.naming.NamingEnumeration; +import javax.naming.directory.Attributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.InitialDirContext; +import javax.naming.directory.SearchControls; +import javax.naming.directory.SearchResult; + +/** + * Thin JNDI LDAP client (zero external dependencies). The {@code connect} field is a + * function so unit tests can substitute a fake DirContext without a real LDAP server. + */ +public class LdapClient { + + public interface Connect { + DirContext open(String url, String principalDn, String credentials) throws Exception; + } + + private final Connect connect; + + public LdapClient() { + this( + (url, dn, pwd) -> { + Hashtable env = new Hashtable<>(); + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + env.put(Context.PROVIDER_URL, url); + env.put(Context.SECURITY_AUTHENTICATION, "simple"); + env.put(Context.SECURITY_PRINCIPAL, dn); + env.put(Context.SECURITY_CREDENTIALS, pwd); + return new InitialDirContext(env); + }); + } + + /** Test constructor. */ + public LdapClient(Connect connect) { + this.connect = connect; + } + + /** + * Authenticates by binding as the resolved user DN. Returns true when bind succeeds. + */ + public boolean bind(String url, String userDn, String password) { + if (userDn == null || userDn.isEmpty() || password == null || password.isEmpty()) { + return false; + } + DirContext ctx = null; + try { + ctx = connect.open(url, userDn, password); + return true; + } catch (Exception e) { + return false; + } finally { + close(ctx); + } + } + + /** + * Binds as the admin account, searches for the login user, and returns the matching + * entry (DN + attributes), or null when not found / search fails. + */ + public LdapEntry search( + String url, + String adminDn, + String adminPassword, + String base, + String filter, + String username) { + String resolvedFilter = filter.replace("{0}", escapeFilterValue(username)); + DirContext ctx = null; + try { + ctx = connect.open(url, adminDn, adminPassword); + SearchControls controls = new SearchControls(); + controls.setSearchScope(SearchControls.SUBTREE_SCOPE); + controls.setCountLimit(1); + NamingEnumeration results = ctx.search(base, resolvedFilter, controls); + if (!results.hasMore()) { + return null; + } + SearchResult result = results.next(); + return new LdapEntry(result.getNameInNamespace(), result.getAttributes()); + } catch (Exception e) { + return null; + } finally { + close(ctx); + } + } + + /** + * A resolved LDAP entry: its full DN plus attributes. Decoupled from JNDI so the search + * result can be unit-tested without a real directory server. + */ + public static final class LdapEntry { + private final String dn; + private final Attributes attributes; + + public LdapEntry(String dn, Attributes attributes) { + this.dn = dn; + this.attributes = attributes; + } + + public String getDn() { + return dn; + } + + public Attributes getAttributes() { + return attributes; + } + } + + /** + * RFC 4515 filter value escaping to prevent LDAP injection via the login name. + */ + static String escapeFilterValue(String value) { + StringBuilder escaped = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char ch = value.charAt(i); + switch (ch) { + case '*': + escaped.append("\\2a"); + break; + case '(': + escaped.append("\\28"); + break; + case ')': + escaped.append("\\29"); + break; + case '\\': + escaped.append("\\5c"); + break; + case 0: + escaped.append("\\00"); + break; + default: + escaped.append(ch); + } + } + return escaped.toString(); + } + + private void close(DirContext ctx) { + if (ctx != null) { + try { + ctx.close(); + } catch (Exception ignore) { + // noop + } + } + } +} diff --git a/himarket-server/src/main/java/com/alibaba/himarket/service/LdapService.java b/himarket-server/src/main/java/com/alibaba/himarket/service/LdapService.java new file mode 100644 index 000000000..68f3e6596 --- /dev/null +++ b/himarket-server/src/main/java/com/alibaba/himarket/service/LdapService.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.alibaba.himarket.service; + +import com.alibaba.himarket.dto.result.common.AuthResult; + +/** + * Enterprise LDAP authentication (T-34). + */ +public interface LdapService { + + /** + * Authenticates the developer against the portal LDAP and returns an access token. + * + * @param username LDAP login name (e.g. uid / employee number) + * @param password LDAP password + * @return authentication result with access token + */ + AuthResult login(String username, String password); + + /** + * Whether the current portal has LDAP login configured. + * + * @return true when LDAP is enabled for the current portal + */ + boolean isConfigured(); +} diff --git a/himarket-server/src/main/java/com/alibaba/himarket/service/impl/LdapServiceImpl.java b/himarket-server/src/main/java/com/alibaba/himarket/service/impl/LdapServiceImpl.java new file mode 100644 index 000000000..d54c450a7 --- /dev/null +++ b/himarket-server/src/main/java/com/alibaba/himarket/service/impl/LdapServiceImpl.java @@ -0,0 +1,176 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.alibaba.himarket.service.impl; + +import com.alibaba.himarket.core.exception.BusinessException; +import com.alibaba.himarket.core.exception.ErrorCode; +import com.alibaba.himarket.core.ldap.LdapClient; +import com.alibaba.himarket.core.security.ContextHolder; +import com.alibaba.himarket.dto.params.developer.CreateExternalDeveloperParam; +import com.alibaba.himarket.dto.result.common.AuthResult; +import com.alibaba.himarket.dto.result.developer.DeveloperResult; +import com.alibaba.himarket.dto.result.portal.PortalResult; +import com.alibaba.himarket.service.DeveloperService; +import com.alibaba.himarket.service.LdapService; +import com.alibaba.himarket.service.PortalService; +import com.alibaba.himarket.service.TokenService; +import com.alibaba.himarket.support.common.Strings; +import com.alibaba.himarket.support.enums.DeveloperAuthType; +import com.alibaba.himarket.support.portal.LdapConfig; +import java.util.Objects; +import javax.naming.NamingException; +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +/** + * Enterprise LDAP login (T-34). Reuses the existing external-identity flow: a successful bind + * links (or creates) a {@code DeveloperExternalIdentity} with provider="ldap" and issues a + * normal developer token. No browser redirect / state is involved. + */ +@Service +@RequiredArgsConstructor +public class LdapServiceImpl implements LdapService { + + private static final String PROVIDER = "ldap"; + + private final PortalService portalService; + + private final TokenService tokenService; + + private final DeveloperService developerService; + + private final ContextHolder contextHolder; + + private final LdapClient ldapClient; + + @Override + public AuthResult login(String username, String password) { + LdapConfig ldap = resolveConfig(); + ResolvedUser user = resolveUserDn(ldap, username); + + if (!ldapClient.bind(ldap.getUrl(), user.getDn(), password)) { + throw new BusinessException(ErrorCode.UNAUTHORIZED, "LDAP authentication failed"); + } + + String developerId = findOrCreateDeveloper(username, user.getDisplayName()); + String token = tokenService.generateDeveloperToken(developerId); + return AuthResult.of(token, tokenService.getTokenExpiresIn()); + } + + @Override + public boolean isConfigured() { + PortalResult portal = portalService.getPortal(contextHolder.getPortal()); + if (portal == null || portal.getPortalSettingConfig() == null) { + return false; + } + LdapConfig ldap = portal.getPortalSettingConfig().getLdap(); + return ldap != null && ldap.enabled(); + } + + private LdapConfig resolveConfig() { + PortalResult portal = portalService.getPortal(contextHolder.getPortal()); + if (portal == null + || portal.getPortalSettingConfig() == null + || portal.getPortalSettingConfig().getLdap() == null + || !portal.getPortalSettingConfig().getLdap().enabled()) { + throw new BusinessException(ErrorCode.INVALID_REQUEST, "LDAP login is not configured"); + } + return portal.getPortalSettingConfig().getLdap(); + } + + private ResolvedUser resolveUserDn(LdapConfig ldap, String username) { + if (Strings.isNotBlank(ldap.getUserDnPattern())) { + String dn = ldap.getUserDnPattern().replace("{0}", username); + return new ResolvedUser(dn, username); + } + if (Strings.isNotBlank(ldap.getUserSearchBase()) + && Strings.isNotBlank(ldap.getUserSearchFilter())) { + LdapClient.LdapEntry entry = + ldapClient.search( + ldap.getUrl(), + ldap.getBindDn(), + ldap.getBindPassword(), + ldap.getUserSearchBase(), + ldap.getUserSearchFilter(), + username); + if (entry == null) { + throw new BusinessException(ErrorCode.UNAUTHORIZED, "LDAP user not found"); + } + return new ResolvedUser( + entry.getDn(), + readAttribute(entry.getAttributes(), ldap.getDisplayNameAttribute(), username)); + } + throw new BusinessException(ErrorCode.INTERNAL_ERROR, "Invalid LDAP configuration"); + } + + private String readAttribute(Attributes attributes, String attributeName, String fallback) { + if (Strings.isBlank(attributeName)) { + return fallback; + } + try { + if (attributes == null) { + return fallback; + } + Attribute attribute = attributes.get(attributeName); + if (attribute == null) { + return fallback; + } + return Objects.toString(attribute.get(), fallback); + } catch (NamingException e) { + return fallback; + } + } + + private String findOrCreateDeveloper(String subject, String displayName) { + DeveloperResult existing = developerService.getExternalDeveloper(PROVIDER, subject); + if (existing != null) { + return existing.getDeveloperId(); + } + return developerService + .createExternalDeveloper( + CreateExternalDeveloperParam.builder() + .provider(PROVIDER) + .subject(subject) + .displayName(displayName) + .authType(DeveloperAuthType.LDAP) + .build()) + .getDeveloperId(); + } + + private static final class ResolvedUser { + private final String dn; + private final String displayName; + + ResolvedUser(String dn, String displayName) { + this.dn = dn; + this.displayName = displayName; + } + + String getDn() { + return dn; + } + + String getDisplayName() { + return displayName; + } + } +} diff --git a/himarket-server/src/test/java/com/alibaba/himarket/service/impl/LdapServiceImplTest.java b/himarket-server/src/test/java/com/alibaba/himarket/service/impl/LdapServiceImplTest.java new file mode 100644 index 000000000..46c1752e7 --- /dev/null +++ b/himarket-server/src/test/java/com/alibaba/himarket/service/impl/LdapServiceImplTest.java @@ -0,0 +1,183 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.alibaba.himarket.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.alibaba.himarket.core.exception.BusinessException; +import com.alibaba.himarket.core.ldap.LdapClient; +import com.alibaba.himarket.core.ldap.LdapClient.LdapEntry; +import com.alibaba.himarket.core.security.ContextHolder; +import com.alibaba.himarket.dto.result.common.AuthResult; +import com.alibaba.himarket.dto.result.developer.DeveloperResult; +import com.alibaba.himarket.dto.result.portal.PortalResult; +import com.alibaba.himarket.service.DeveloperService; +import com.alibaba.himarket.service.PortalService; +import com.alibaba.himarket.service.TokenService; +import com.alibaba.himarket.support.portal.LdapConfig; +import com.alibaba.himarket.support.portal.PortalSettingConfig; +import javax.naming.directory.Attributes; +import javax.naming.directory.BasicAttribute; +import javax.naming.directory.BasicAttributes; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class LdapServiceImplTest { + + @Mock private PortalService portalService; + @Mock private TokenService tokenService; + @Mock private DeveloperService developerService; + @Mock private ContextHolder contextHolder; + @Mock private LdapClient ldapClient; + + private LdapServiceImpl service; + + @BeforeEach + void setUp() { + service = + new LdapServiceImpl( + portalService, tokenService, developerService, contextHolder, ldapClient); + when(contextHolder.getPortal()).thenReturn("portal-1"); + lenient().when(tokenService.generateDeveloperToken("dev-1")).thenReturn("tok-123"); + lenient().when(tokenService.getTokenExpiresIn()).thenReturn(3600L); + } + + private PortalResult portalWith(LdapConfig ldap) { + PortalSettingConfig cfg = new PortalSettingConfig(); + cfg.setLdap(ldap); + PortalResult portal = new PortalResult(); + portal.setPortalSettingConfig(cfg); + return portal; + } + + private LdapConfig patternConfig() { + LdapConfig c = new LdapConfig(); + c.setUrl("ldap://10.2.7.31:389"); + c.setUserDnPattern("uid={0},ou=people,dc=lyf,dc=intl"); + return c; + } + + @Test + @DisplayName("pattern mode: existing developer reuses account and returns token") + void existingDeveloperReturnsToken() { + when(portalService.getPortal("portal-1")).thenReturn(portalWith(patternConfig())); + when(ldapClient.bind( + "ldap://10.2.7.31:389", "uid=zhangsan,ou=people,dc=lyf,dc=intl", "secret")) + .thenReturn(true); + + DeveloperResult existing = new DeveloperResult(); + existing.setDeveloperId("dev-1"); + when(developerService.getExternalDeveloper("ldap", "zhangsan")).thenReturn(existing); + + AuthResult result = service.login("zhangsan", "secret"); + + assertThat(result.getAccessToken()).isEqualTo("tok-123"); + verify(developerService, never()).createExternalDeveloper(any()); + verify(developerService).getExternalDeveloper("ldap", "zhangsan"); + } + + @Test + @DisplayName("pattern mode: unknown developer is auto-created") + void unknownDeveloperIsCreated() { + when(portalService.getPortal("portal-1")).thenReturn(portalWith(patternConfig())); + when(ldapClient.bind(any(), any(), any())).thenReturn(true); + when(developerService.getExternalDeveloper("ldap", "lisi")).thenReturn(null); + + DeveloperResult created = new DeveloperResult(); + created.setDeveloperId("dev-1"); + when(developerService.createExternalDeveloper(any())).thenReturn(created); + + AuthResult result = service.login("lisi", "secret"); + + assertThat(result.getAccessToken()).isEqualTo("tok-123"); + verify(developerService).createExternalDeveloper(any()); + } + + @Test + @DisplayName("bind failure throws BusinessException (UNAUTHORIZED)") + void bindFailureThrows() { + when(portalService.getPortal("portal-1")).thenReturn(portalWith(patternConfig())); + when(ldapClient.bind(any(), any(), any())).thenReturn(false); + + assertThrows(BusinessException.class, () -> service.login("zhangsan", "wrong")); + } + + @Test + @DisplayName("LDAP not configured throws BusinessException (INVALID_REQUEST)") + void notConfiguredThrows() { + PortalResult portal = new PortalResult(); + portal.setPortalSettingConfig(new PortalSettingConfig()); + when(portalService.getPortal("portal-1")).thenReturn(portal); + + assertThrows(BusinessException.class, () -> service.login("zhangsan", "x")); + } + + @Test + @DisplayName("search mode resolves DN and display name from LDAP attributes") + void searchModeResolvesDn() { + LdapConfig c = new LdapConfig(); + c.setUrl("ldap://10.2.7.31:389"); + c.setBindDn("cn=admin"); + c.setBindPassword("adminpw"); + c.setUserSearchBase("ou=people,dc=lyf,dc=intl"); + c.setUserSearchFilter("(uid={0})"); + c.setDisplayNameAttribute("cn"); + + when(portalService.getPortal("portal-1")).thenReturn(portalWith(c)); + + Attributes attrs = new BasicAttributes(); + attrs.put(new BasicAttribute("cn", "Zhang San")); + LdapEntry entry = new LdapEntry("uid=zhangsan,ou=people,dc=lyf,dc=intl", attrs); + when(ldapClient.search( + eq("ldap://10.2.7.31:389"), + eq("cn=admin"), + eq("adminpw"), + eq("ou=people,dc=lyf,dc=intl"), + eq("(uid={0})"), + eq("zhangsan"))) + .thenReturn(entry); + when(ldapClient.bind( + eq("ldap://10.2.7.31:389"), + eq("uid=zhangsan,ou=people,dc=lyf,dc=intl"), + eq("secret"))) + .thenReturn(true); + + DeveloperResult existing = new DeveloperResult(); + existing.setDeveloperId("dev-1"); + when(developerService.getExternalDeveloper("ldap", "zhangsan")).thenReturn(existing); + + AuthResult result = service.login("zhangsan", "secret"); + + assertThat(result.getAccessToken()).isEqualTo("tok-123"); + verify(developerService, never()).createExternalDeveloper(any()); + } +}