Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
feat(enterprise): add LDAP / Active Directory sign-in, limit Community to one OAuth provider
Jonas Kaninda75ce37c7df0a
diff --git a/cmd/posta/server.go b/cmd/posta/server.goindex 2e80762..a4ce59b 100644--- a/cmd/posta/server.go+++ b/cmd/posta/server.go@@ -232,11 +232,16 @@ func newEdition(db *gorm.DB, cfg *config.Config) enterprise.EE {if err != nil {logger.Error("failed to create the install id", "error", err)}+ ldapRepo := repositories.NewLDAPRepository(db)edition := enterprise.New(db, enterprise.Options{License: cfg.License,LicenseFile: cfg.LicenseFile,InstanceURL: cfg.AppWebURL,InstallID: installID,+ LDAPDirectories: func(_ context.Context) ([]models.LDAPConfig, error) {+ return ldapRepo.Enabled()+ },+ Decrypt: crypto.Decrypt,})models.SetPIIEncryptionGate(edition.Licensed)return editiondiff --git a/docs/docs/admin/ldap-directories.md b/docs/docs/admin/ldap-directories.mdnew file mode 100644index 0000000..efb4edf--- /dev/null+++ b/docs/docs/admin/ldap-directories.md@@ -0,0 +1,71 @@+---+sidebar_position: 7+title: LDAP Directories+description: Let people sign in with their LDAP or Active Directory account (Posta Enterprise)+---++# LDAP Directories++:::info Posta Enterprise+LDAP / Active Directory sign-in needs a Posta Enterprise license, installed under+**Admin → License**. Without one, the directories you configured stay stored but+are not used.+:::++People sign in on the usual Posta sign-in page with their **directory email and+password**. Posta asks a directory only when the password does not match a local+account, so local accounts and the bootstrap admin keep working if the directory+is down.++The first time someone signs in, Posta creates their account (verified, with no+local password). An existing Posta account with the same email is used as is.++## Adding a directory++Under **Admin → LDAP Directories → Add directory**:++| Setting | Notes |+|---|---|+| Host, port | Port defaults to 389, or 636 for LDAPS. |+| Encryption | **StartTLS** (default), **LDAPS**, or **None** for development only. Add a private CA certificate in PEM if the server's certificate is not publicly trusted. |+| Service account | The bind DN and password Posta searches for users with. Leave empty to search anonymously. The password is encrypted at rest when `POSTA_ENCRYPTION_KEY` is set, and never returned by the API. |+| Users | The base DN to search, and the filter. `%s` is the sign-in email, escaped. The default is `(mail=%s)`; for Active Directory, `(userPrincipalName=%s)` or `(|(mail=%s)(userPrincipalName=%s))` are common. |+| Attributes | `mail` and `displayName` by default. |+| Groups | Posta reads the user's `memberOf` by default. Set a group base DN or a filter such as `(member=%s)` (`%s` is the user's DN) to search for groups instead, and tick **nested groups** for Active Directory. |++Then press **Test connection**: Posta connects, binds as the service account and+reads the user base DN.++Posta tries enabled directories in the order they were added and uses the first+one that knows the email.++## Group mappings++A mapping gives the members of a directory group access in Posta, at every sign-in:++- **Platform admin**: members become platform admins.+- **Workspace and role**: members join the workspace as admin, editor or viewer.+ Ownership is never granted from a directory.++Write the group as a full DN (`cn=posta-admins,ou=groups,dc=example,dc=com`) or as+a bare CN (`posta-admins`); matching ignores case.++Mappings apply only to accounts the directory created, and only to the access they+govern: a workspace no mapping names, or the platform admin role when no mapping+grants it, is left as an admin set it. Posta never takes the admin role from the+last platform admin who can sign in.++## API++All routes need a platform admin and a Posta Enterprise license; changes need one+that has not expired.++| Method | Path | |+|---|---|---|+| `GET` | `/api/v1/admin/ldap` | List directories with their mappings |+| `POST` | `/api/v1/admin/ldap` | Add a directory |+| `PUT` | `/api/v1/admin/ldap/{id}` | Update one; an empty `bind_password` keeps the stored one |+| `DELETE` | `/api/v1/admin/ldap/{id}` | Delete one and its mappings |+| `POST` | `/api/v1/admin/ldap/{id}/test` | Test the connection |+| `POST` | `/api/v1/admin/ldap/{id}/mappings` | Map a group |+| `DELETE` | `/api/v1/admin/ldap/{id}/mappings/{mapping_id}` | Remove a mapping |diff --git a/docs/docs/admin/oauth-providers.md b/docs/docs/admin/oauth-providers.mdindex 29f794c..7740a5d 100644--- a/docs/docs/admin/oauth-providers.md+++ b/docs/docs/admin/oauth-providers.md@@ -12,6 +12,13 @@ Administrators can configure OAuth 2.0 / OpenID Connect providers to allow usersFor the full request/response schema, see the interactive API Reference at `/docs` on your Posta instance.:::+:::info Posta Enterprise+Posta Community signs in through **one** OAuth provider. Adding a second needs a+[Posta Enterprise](https://goposta.dev/enterprise) license; installations that already+had several keep them. For LDAP or Active Directory, see+[LDAP Directories](./ldap-directories.md).+:::+## Supported Provider Types| Type | Description |diff --git a/docs/docs/admin/plans.md b/docs/docs/admin/plans.mdindex 453100e..db6c6a7 100644--- a/docs/docs/admin/plans.md+++ b/docs/docs/admin/plans.md@@ -1,5 +1,5 @@----sidebar_position: 7+sidebar_position: 8title: Plans & Quotasdescription: Configure plans with rate limits and resource quotas---diff --git a/go.mod b/go.modindex 51bf0dd..fa56ad2 100644--- a/go.mod+++ b/go.mod@@ -9,6 +9,7 @@ require (github.com/coreos/go-oidc/v3 v3.21.0github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6github.com/emersion/go-smtp v0.25.0+ github.com/go-ldap/ldap/v3 v3.4.15github.com/golang-jwt/jwt/v5 v5.3.1github.com/google/uuid v1.6.0github.com/hibiken/asynq v0.26.0@@ -34,6 +35,7 @@ require (require (cloud.google.com/go/compute/metadata v0.10.0 // indirect+ github.com/Azure/go-ntlmssp v0.1.1 // indirectgithub.com/PuerkitoBio/goquery v1.13.0 // indirectgithub.com/andybalholm/cascadia v1.3.5 // indirectgithub.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 // indirect@@ -52,6 +54,7 @@ require (github.com/clipperhouse/uax29/v2 v2.7.0 // indirectgithub.com/fatih/color v1.19.0 // indirectgithub.com/getkin/kin-openapi v0.152.0 // indirect+ github.com/go-asn1-ber/asn1-ber v1.5.8 // indirectgithub.com/go-jose/go-jose/v4 v4.1.6 // indirectgithub.com/go-openapi/jsonpointer v1.0.2 // indirectgithub.com/goccy/go-json v0.11.2 // indirectdiff --git a/go.sum b/go.sumindex 75b04f8..1e5e81c 100644--- a/go.sum+++ b/go.sum@@ -1,7 +1,11 @@cloud.google.com/go/compute/metadata v0.10.0 h1:pyKMUQSwchgkIBBJGdILqQbs/BNJXqwSA7Ej6LAvvtY=cloud.google.com/go/compute/metadata v0.10.0/go.mod h1:rGFHRrIif570kSibjFTMbt6/4/tzgJWFGI/HVol4GIk=+github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw=+github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=github.com/PuerkitoBio/goquery v1.13.0 h1:mqHbjD7Jmnul4DTR24LKTjo1uUmHUh072kteGV+xpFM=github.com/PuerkitoBio/goquery v1.13.0/go.mod h1:Hip5mdBL8K2wEGKJdr27sRaNwIdDajmCwB/ExUPwW+g=+github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktpoUAgOJK3OTFc/xug0PCXYCqU0FgDKI=+github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=github.com/andybalholm/cascadia v1.3.5 h1:RLjq12WJy58dN6eCIQrz0bAGZkztHWsEPFxP53Y7Ms8=github.com/andybalholm/cascadia v1.3.5/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM=github.com/aws/aws-sdk-go-v2 v1.47.5 h1:5yA+A+BiXbDq1ZLbYwPViwhEGDMdR0MEhL8Jh2LnLS4=@@ -58,8 +62,12 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkgithub.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=github.com/getkin/kin-openapi v0.152.0 h1:XRVo77lMRyOGMHf1paMu9lxX3wzuQDZeprssZJnz/x8=github.com/getkin/kin-openapi v0.152.0/go.mod h1:1+BHDzstro+P5CKtPy1X4PfofnFgmRe6uvMy9+r9fKY=+github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ=+github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4=github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=+github.com/go-ldap/ldap/v3 v3.4.15 h1:eRB4f4Ecn1POL1mO86+uUDlecmyWsdiJwh60bAUS4UY=+github.com/go-ldap/ldap/v3 v3.4.15/go.mod h1:jeD0c98EdZQCKKKKe4kTWs5aCf6y+j8KuYsYLznZSQk=github.com/go-openapi/jsonpointer v1.0.2 h1:NbW7xT2b+l7x+JefiPGDsZWsrLk1ogrz4AHK1TTzMt8=github.com/go-openapi/jsonpointer v1.0.2/go.mod h1:N0rI4MbNKD7xAFTiHtB+5Nhrg2j/wwYg7m7Fmb4/jk8=github.com/go-openapi/testify/v2 v2.8.0 h1:19QDx5b57p8KjO2E4sgs/woL4Akp+FGLRlVm2xn0Rho=@@ -74,6 +82,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=+github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=+github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=github.com/hibiken/asynq v0.26.0 h1:1Zxr92MlDnb1Zt/QR5g2vSCqUS03i95lUfqx5X7/wrw=github.com/hibiken/asynq v0.26.0/go.mod h1:Qk4e57bTnWDoyJ67VkchuV6VzSM9IQW2nPvAGuDyw58=github.com/inbucket/html2text v1.0.0 h1:N5kza++4uBBDJ2Z3KUnTRyPNoBcW+YfOgNiNmNB+sgs=@@ -86,6 +96,18 @@ github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=+github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=+github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=+github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo=+github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM=+github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg=+github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo=+github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o=+github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg=+github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh687T8=+github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=+github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=+github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=diff --git a/internal/enterprise/ee.go b/internal/enterprise/ee.goindex 94a656a..0ec8102 100644--- a/internal/enterprise/ee.go+++ b/internal/enterprise/ee.go@@ -21,7 +21,10 @@ package enterpriseimport ("context"+ "errors""time"++ "github.com/goposta/posta/internal/models")// Product is the product name license tokens are issued for.@@ -102,8 +105,40 @@ type EE interface {Install(ctx context.Context, token, requestHost string) (Status, error)// Remove deletes the installed license, reverting to Community.Remove(ctx context.Context) error+ // LDAP returns the LDAP / Active Directory authenticator, or nil in the+ // Community build and without a license. Sign-in asks it only after the+ // local password check fails, so local accounts keep working when the+ // directory is down.+ LDAP() LDAPAuthenticator+}++// LDAPIdentity is a directory user whose password bound: the mapped email and+// name, the groups they belong to, and the directory that matched. It is plain+// data, so this package never touches users or sessions.+type LDAPIdentity struct {+ Email string+ Name string+ Groups []string // group DNs+ Directory string // the matched LDAPConfig name+}++// LDAPTestResult is the outcome of an admin's "Test connection".+type LDAPTestResult struct {+ OK bool `json:"ok"`+ Message string `json:"message,omitempty"`+ Error string `json:"error,omitempty"`+}++// LDAPAuthenticator binds sign-in credentials against the configured directories.+type LDAPAuthenticator interface {+ Authenticate(ctx context.Context, email, password string) (LDAPIdentity, error)+ TestConnection(ctx context.Context, cfg *models.LDAPConfig) LDAPTestResult}+// ErrLDAPNoMatch means no enabled directory knows the user, so sign-in keeps+// its local result. It is never shown to the client.+var ErrLDAPNoMatch = errors.New("no matching LDAP directory")+// Options configure New.type Options struct {// License is a license token to install at boot when none is stored@@ -116,6 +151,11 @@ type Options struct {InstanceURL string// InstallID is this deployment's Install ID, for the install-ID binding.InstallID string+ // LDAPDirectories lists the enabled directories, in the order sign-in+ // tries them, and Decrypt reads their stored service passwords. Passed in+ // so this package imports no repositories or crypto.+ LDAPDirectories func(ctx context.Context) ([]models.LDAPConfig, error)+ Decrypt func(stored string) (string, error)}// GateError is the error a gate returns. Code is the stable API error code@@ -158,6 +198,7 @@ func (community) Mutable() bool { return false }func (community) Require() error { return ErrLicenseRequired }func (community) RequireMutable() error { return ErrLicenseRequired }func (community) Remove(context.Context) error { return ErrCommunityEdition }+func (community) LDAP() LDAPAuthenticator { return nil }func (community) Install(context.Context, string, string) (Status, error) {return Status{}, ErrCommunityEdition}diff --git a/internal/enterprise/enterprise.go b/internal/enterprise/enterprise.goindex 275e712..5b94ab1 100644--- a/internal/enterprise/enterprise.go+++ b/internal/enterprise/enterprise.go@@ -21,6 +21,7 @@ import ("sync""time"+ eldap "github.com/goposta/posta/internal/enterprise/ldap""github.com/goposta/posta/internal/enterprise/license""github.com/goposta/posta/internal/models""github.com/jkaninda/logger"@@ -40,7 +41,7 @@ const reloadEvery = time.Minute// New returns the license-verifying EE. It loads the stored license, or// installs the one given in opts when none is stored.func New(db *gorm.DB, opts Options) EE {- e := &impl{db: db, opts: opts}+ e := &impl{db: db, opts: opts, ldap: eldap.New(opts.LDAPDirectories, opts.Decrypt)}if ring, err := license.ParseKeyring(embeddedKeyring); err != nil || ring.Product != Product {logger.Warn("enterprise: this build has no license keyring; running as Community")} else {@@ -62,6 +63,7 @@ type impl struct {db *gorm.DBring *license.Keyringopts Options+ ldap *eldap.Providermu sync.RWMutexloaded loadedLicense@@ -236,7 +238,36 @@ func (e *impl) Status() Status {return s}-func (e *impl) Licensed() bool { return e.Status().Licensed() }+func (e *impl) Licensed() bool { return e.Status().Licensed() }++// LDAP is on while licensed, degraded included: an expired license freezes+// settings but never locks people out.+func (e *impl) LDAP() LDAPAuthenticator {+ if !e.Licensed() {+ return nil+ }+ return ldapAdapter{e.ldap}+}++// ldapAdapter maps the ldap package's types, which do not import this+// package, onto LDAPAuthenticator.+type ldapAdapter struct{ p *eldap.Provider }++func (a ldapAdapter) Authenticate(ctx context.Context, email, password string) (LDAPIdentity, error) {+ id, err := a.p.Authenticate(ctx, email, password)+ if errors.Is(err, eldap.ErrNoMatch) {+ return LDAPIdentity{}, ErrLDAPNoMatch+ }+ if err != nil {+ return LDAPIdentity{}, err+ }+ return LDAPIdentity{Email: id.Email, Name: id.Name, Groups: id.Groups, Directory: id.Directory}, nil+}++func (a ldapAdapter) TestConnection(_ context.Context, cfg *models.LDAPConfig) LDAPTestResult {+ r := a.p.TestConnection(cfg)+ return LDAPTestResult{OK: r.OK, Message: r.Message, Error: r.Error}+}func (e *impl) Mutable() bool { return e.Status().Mutable() }func (e *impl) Require() error { return gate(e.Status()) }func (e *impl) RequireMutable() error { return gateMutable(e.Status()) }diff --git a/internal/enterprise/enterprisetest/enterprisetest.go b/internal/enterprise/enterprisetest/enterprisetest.goindex a469fab..bffe431 100644--- a/internal/enterprise/enterprisetest/enterprisetest.go+++ b/internal/enterprise/enterprisetest/enterprisetest.go@@ -61,3 +61,6 @@ func (s State) Install(context.Context, string, string) (enterprise.Status, erro}func (s State) Remove(context.Context) error { return nil }++// LDAP is nil: tests that need a directory fake one.+func (s State) LDAP() enterprise.LDAPAuthenticator { return nil }diff --git a/internal/enterprise/ldap/provider.go b/internal/enterprise/ldap/provider.gonew file mode 100644index 0000000..bc21205--- /dev/null+++ b/internal/enterprise/ldap/provider.go@@ -0,0 +1,323 @@+//go:build enterprise++// Copyright (c) 2026 Jonas Kaninda. All rights reserved.+//+// This file is part of Posta Enterprise Edition.+//+// This file is licensed under the Posta Enterprise License, not the GNU+// Affero General Public License. See internal/enterprise/LICENSE.md.+//+// SPDX-License-Identifier: LicenseRef-Posta-Enterprise++// Package ldap authenticates against LDAP and Active Directory with+// go-ldap/ldap/v3. It is compiled only into the Enterprise build and holds no+// user or session code: Authenticate returns a plain identity, and the core+// creates the account and maps groups.+package ldap++import (+ "context"+ "crypto/tls"+ "crypto/x509"+ "errors"+ "fmt"+ "net"+ "strconv"+ "strings"+ "time"++ ldapv3 "github.com/go-ldap/ldap/v3"+ "github.com/goposta/posta/internal/models"+ "github.com/jkaninda/logger"+)++// ErrNoMatch means no enabled directory knows the user.+var ErrNoMatch = errors.New("ldap: no matching directory")++// Identity is a directory user whose password bound.+type Identity struct {+ Email string+ Name string+ Groups []string+ Directory string+}++// Result is the outcome of TestConnection.+type Result struct {+ OK bool+ Message string+ Error string+}++// Provider binds credentials against the configured directories.+type Provider struct {+ directories func(ctx context.Context) ([]models.LDAPConfig, error)+ decrypt func(string) (string, error)+}++// New builds the provider. directories lists the enabled directories in the+// order sign-in tries them; decrypt reads their stored service passwords.+func New(directories func(ctx context.Context) ([]models.LDAPConfig, error), decrypt func(string) (string, error)) *Provider {+ if decrypt == nil {+ decrypt = func(s string) (string, error) { return s, nil }+ }+ return &Provider{directories: directories, decrypt: decrypt}+}++// Authenticate tries each enabled directory in order and returns the first+// whose search finds the user and whose bind accepts the password. An empty+// password is refused before any bind: most directories accept an empty bind+// as anonymous, the classic LDAP authentication bypass.+func (p *Provider) Authenticate(ctx context.Context, email, password string) (Identity, error) {+ email = strings.TrimSpace(email)+ if email == "" || password == "" || p.directories == nil {+ return Identity{}, ErrNoMatch+ }+ cfgs, err := p.directories(ctx)+ if err != nil {+ return Identity{}, fmt.Errorf("ldap: load directories: %w", err)+ }+ var lastErr error+ for i := range cfgs {+ ident, found, err := p.authOne(&cfgs[i], email, password)+ if err != nil {+ // A wrong password or an unreachable directory: try the others, and+ // report this only if none of them knows the user.+ lastErr = err+ logger.Warn("ldap: sign-in attempt failed", "directory", cfgs[i].Name, "error", err)+ continue+ }+ if found {+ return ident, nil+ }+ }+ if lastErr != nil {+ return Identity{}, lastErr+ }+ return Identity{}, ErrNoMatch+}++// authOne searches one directory for the user, then binds as them. found is+// false when the directory does not know the user; an error means it does+// but the bind failed, or the directory could not be reached.+func (p *Provider) authOne(cfg *models.LDAPConfig, email, password string) (Identity, bool, error) {+ conn, err := p.dial(cfg)+ if err != nil {+ return Identity{}, false, err+ }+ defer func() { _ = conn.Close() }()+ if err := p.serviceBind(conn, cfg); err != nil {+ return Identity{}, false, err+ }++ entry, err := searchUser(conn, cfg, email)+ if err != nil || entry == nil {+ return Identity{}, false, err+ }++ // A fresh connection for the user bind, so it does not inherit the+ // service account's bind.+ userConn, err := p.dial(cfg)+ if err != nil {+ return Identity{}, false, err+ }+ defer func() { _ = userConn.Close() }()+ if err := userConn.Bind(entry.DN, password); err != nil {+ return Identity{}, false, fmt.Errorf("ldap: user bind failed: %w", err)+ }++ ident := Identity{+ Directory: cfg.Name,+ Email: strings.TrimSpace(entry.GetAttributeValue(attrOr(cfg.AttrEmail, "mail"))),+ Name: strings.TrimSpace(entry.GetAttributeValue(attrOr(cfg.AttrName, "displayName"))),+ }+ if ident.Email == "" {+ ident.Email = email+ }+ // Groups are read over the service connection: users often may not search+ // groups themselves.+ ident.Groups = resolveGroups(conn, cfg, entry)+ return ident, true, nil+}++func (p *Provider) serviceBind(conn *ldapv3.Conn, cfg *models.LDAPConfig) error {+ if cfg.BindDN == "" {+ return nil+ }+ pw, err := p.decrypt(cfg.BindPasswordEnc)+ if err != nil {+ return fmt.Errorf("ldap: read the service password: %w", err)+ }+ if err := conn.Bind(cfg.BindDN, pw); err != nil {+ return fmt.Errorf("ldap: service bind failed: %w", err)+ }+ return nil+}++// searchUser finds the user's entry with the configured filter, the email+// escaped against LDAP filter injection. nil means not found.+func searchUser(conn *ldapv3.Conn, cfg *models.LDAPConfig, email string) (*ldapv3.Entry, error) {+ filter := strings.ReplaceAll(userFilter(cfg), "%s", ldapv3.EscapeFilter(email))+ attrs := dedupe([]string{attrOr(cfg.AttrEmail, "mail"), attrOr(cfg.AttrName, "displayName"), attrOr(cfg.MemberAttr, "memberOf")})+ req := ldapv3.NewSearchRequest(cfg.UserBaseDN, ldapv3.ScopeWholeSubtree, ldapv3.NeverDerefAliases,+ 2, timeoutSeconds(cfg), false, filter, attrs, nil)+ res, err := conn.Search(req)+ if err != nil {+ return nil, fmt.Errorf("ldap: user search: %w", err)+ }+ switch len(res.Entries) {+ case 0:+ return nil, nil+ case 1:+ return res.Entries[0], nil+ default:+ // Two entries for one sign-in name: binding the first would be a guess.+ return nil, fmt.Errorf("ldap: the user filter matches more than one entry for %q", email)+ }+}++// resolveGroups returns the user's group DNs: the member attribute of their+// entry, or a group search when a group base or filter is configured, or when+// Active Directory nested groups are wanted. A failure yields the attribute's+// groups rather than blocking sign-in.+func resolveGroups(conn *ldapv3.Conn, cfg *models.LDAPConfig, entry *ldapv3.Entry) []string {+ direct := entry.GetAttributeValues(attrOr(cfg.MemberAttr, "memberOf"))+ if !cfg.NestedGroups && cfg.GroupBaseDN == "" && cfg.GroupFilter == "" {+ return direct+ }+ req := ldapv3.NewSearchRequest(orStr(cfg.GroupBaseDN, cfg.UserBaseDN), ldapv3.ScopeWholeSubtree,+ ldapv3.NeverDerefAliases, 0, timeoutSeconds(cfg), false, groupFilter(cfg, entry.DN), []string{"dn"}, nil)+ res, err := conn.Search(req)+ if err != nil {+ logger.Warn("ldap: group search failed", "directory", cfg.Name, "error", err)+ return direct+ }+ out := make([]string, 0, len(res.Entries))+ for _, e := range res.Entries {+ out = append(out, e.DN)+ }+ return out+}++func userFilter(cfg *models.LDAPConfig) string {+ if f := strings.TrimSpace(cfg.UserFilter); f != "" {+ return f+ }+ return "(" + attrOr(cfg.AttrEmail, "mail") + "=%s)"+}++func groupFilter(cfg *models.LDAPConfig, userDN string) string {+ esc := ldapv3.EscapeFilter(userDN)+ if f := strings.TrimSpace(cfg.GroupFilter); f != "" {+ return strings.ReplaceAll(f, "%s", esc)+ }+ if cfg.NestedGroups {+ // Active Directory: LDAP_MATCHING_RULE_IN_CHAIN expands nested groups.+ return "(member:1.2.840.113556.1.4.1941:=" + esc + ")"+ }+ return "(member=" + esc + ")"+}++// dial connects with the configured TLS mode and optional private CA.+func (p *Provider) dial(cfg *models.LDAPConfig) (*ldapv3.Conn, error) {+ host := strings.TrimSpace(cfg.Host)+ if host == "" {+ return nil, errors.New("ldap: host is required")+ }+ port := cfg.Port+ if port == 0 {+ port = 389+ if cfg.TLSMode == models.LDAPTLSLDAPS {+ port = 636+ }+ }+ addr := net.JoinHostPort(host, strconv.Itoa(port))+ timeout := time.Duration(timeoutSeconds(cfg)) * time.Second+ dialer := &net.Dialer{Timeout: timeout}++ var conn *ldapv3.Conn+ var err error+ if cfg.TLSMode == models.LDAPTLSLDAPS {+ conn, err = ldapv3.DialURL("ldaps://"+addr, ldapv3.DialWithDialer(dialer), ldapv3.DialWithTLSConfig(tlsConfig(cfg, host)))+ } else {+ conn, err = ldapv3.DialURL("ldap://"+addr, ldapv3.DialWithDialer(dialer))+ }+ if err != nil {+ return nil, fmt.Errorf("ldap: dial %s: %w", addr, err)+ }+ conn.SetTimeout(timeout)+ if cfg.TLSMode == models.LDAPTLSStartTLS {+ if err := conn.StartTLS(tlsConfig(cfg, host)); err != nil {+ _ = conn.Close()+ return nil, fmt.Errorf("ldap: starttls: %w", err)+ }+ }+ return conn, nil+}++func tlsConfig(cfg *models.LDAPConfig, host string) *tls.Config {+ t := &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12, InsecureSkipVerify: cfg.InsecureSkipTLS} //nolint:gosec // opt-in, warned about in the dashboard+ if pem := strings.TrimSpace(cfg.CACertPEM); pem != "" {+ pool := x509.NewCertPool()+ if pool.AppendCertsFromPEM([]byte(pem)) {+ t.RootCAs = pool+ }+ }+ return t+}++// TestConnection connects, binds as the service account and reads the user+// base DN. A failure is reported in the result, not as an error.+func (p *Provider) TestConnection(cfg *models.LDAPConfig) Result {+ conn, err := p.dial(cfg)+ if err != nil {+ return Result{Error: err.Error()}+ }+ defer func() { _ = conn.Close() }()+ if err := p.serviceBind(conn, cfg); err != nil {+ return Result{Error: err.Error()}+ }+ if cfg.UserBaseDN == "" {+ return Result{OK: true, Message: "Connected and bound."}+ }+ req := ldapv3.NewSearchRequest(cfg.UserBaseDN, ldapv3.ScopeBaseObject, ldapv3.NeverDerefAliases,+ 1, timeoutSeconds(cfg), false, "(objectClass=*)", []string{"dn"}, nil)+ if _, err := conn.Search(req); err != nil {+ return Result{Error: "the user base DN cannot be read: " + err.Error()}+ }+ return Result{OK: true, Message: "Connected, bound, and the user base DN is readable."}+}++func timeoutSeconds(cfg *models.LDAPConfig) int {+ if cfg.TimeoutSeconds > 0 {+ return cfg.TimeoutSeconds+ }+ return 10+}++func attrOr(v, def string) string {+ if s := strings.TrimSpace(v); s != "" {+ return s+ }+ return def+}++func orStr(v, def string) string {+ if strings.TrimSpace(v) != "" {+ return v+ }+ return def+}++func dedupe(in []string) []string {+ seen := map[string]bool{}+ out := make([]string, 0, len(in))+ for _, s := range in {+ if s == "" || seen[s] {+ continue+ }+ seen[s] = true+ out = append(out, s)+ }+ return out+}diff --git a/internal/enterprise/ldap/provider_test.go b/internal/enterprise/ldap/provider_test.gonew file mode 100644index 0000000..a6dea60--- /dev/null+++ b/internal/enterprise/ldap/provider_test.go@@ -0,0 +1,67 @@+//go:build enterprise++// Copyright (c) 2026 Jonas Kaninda. All rights reserved.+//+// This file is part of Posta Enterprise Edition.+//+// This file is licensed under the Posta Enterprise License, not the GNU+// Affero General Public License. See internal/enterprise/LICENSE.md.+//+// SPDX-License-Identifier: LicenseRef-Posta-Enterprise++package ldap++import (+ "context"+ "errors"+ "testing"++ "github.com/goposta/posta/internal/models"+)++func provider(cfgs ...models.LDAPConfig) *Provider {+ return New(func(context.Context) ([]models.LDAPConfig, error) { return cfgs, nil }, nil)+}++// An empty password is an anonymous bind most directories accept: it must+// never reach a directory.+func TestEmptyCredentialsNeverBind(t *testing.T) {+ p := provider(models.LDAPConfig{Name: "corp", Host: "ldap.invalid", Enabled: true, UserBaseDN: "dc=corp"})+ for _, tc := range [][2]string{{"[email protected]", ""}, {" ", "secret"}} {+ if _, err := p.Authenticate(context.Background(), tc[0], tc[1]); !errors.Is(err, ErrNoMatch) {+ t.Errorf("Authenticate(%q, %q) = %v, want ErrNoMatch without dialing", tc[0], tc[1], err)+ }+ }+}++func TestNoDirectories(t *testing.T) {+ if _, err := provider().Authenticate(context.Background(), "[email protected]", "pw"); !errors.Is(err, ErrNoMatch) {+ t.Fatalf("err = %v, want ErrNoMatch", err)+ }+}++func TestUnreachableDirectoryReportsAnError(t *testing.T) {+ p := provider(models.LDAPConfig{Name: "corp", Host: "127.0.0.1", Port: 1, TimeoutSeconds: 1, TLSMode: models.LDAPTLSNone, Enabled: true, UserBaseDN: "dc=corp"})+ if _, err := p.Authenticate(context.Background(), "[email protected]", "pw"); err == nil || errors.Is(err, ErrNoMatch) {+ t.Fatalf("err = %v, want a dial error", err)+ }+}++func TestFilters(t *testing.T) {+ if got := userFilter(&models.LDAPConfig{}); got != "(mail=%s)" {+ t.Errorf("default user filter = %q", got)+ }+ if got := userFilter(&models.LDAPConfig{AttrEmail: "userPrincipalName"}); got != "(userPrincipalName=%s)" {+ t.Errorf("user filter from the email attribute = %q", got)+ }+ if got := groupFilter(&models.LDAPConfig{}, "cn=a,dc=c"); got != "(member=cn=a,dc=c)" {+ t.Errorf("default group filter = %q", got)+ }+ if got := groupFilter(&models.LDAPConfig{NestedGroups: true}, "cn=a,dc=c"); got != "(member:1.2.840.113556.1.4.1941:=cn=a,dc=c)" {+ t.Errorf("nested group filter = %q", got)+ }+ // The user DN is escaped into the filter, so a crafted DN cannot widen it.+ if got := groupFilter(&models.LDAPConfig{GroupFilter: "(uniqueMember=%s)"}, "cn=a*)(x=*"); got != `(uniqueMember=cn=a\2a\29\28x=\2a)` {+ t.Errorf("escaped group filter = %q", got)+ }+}diff --git a/internal/handlers/helper.go b/internal/handlers/helper.goindex f3ce860..8ce32b1 100644--- a/internal/handlers/helper.go+++ b/internal/handlers/helper.go@@ -73,10 +73,9 @@ func created[T any](c *okapi.Context, data T) error {})}+// noContent answers 204 with no body, as HTTP requires for that status.func noContent(c *okapi.Context) error {- return c.JSON(http.StatusNoContent, dto.Response[any]{- Success: true,- })+ return c.NoContent()}// getScope extracts the ResourceScope from the request context.diff --git a/internal/handlers/ldap_admin_handler.go b/internal/handlers/ldap_admin_handler.gonew file mode 100644index 0000000..8079a62--- /dev/null+++ b/internal/handlers/ldap_admin_handler.go@@ -0,0 +1,298 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package handlers++import (+ "fmt"+ "slices"+ "strings"++ "github.com/goposta/posta/internal/enterprise"+ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/audit"+ "github.com/goposta/posta/internal/services/crypto"+ "github.com/goposta/posta/internal/services/directory"+ "github.com/goposta/posta/internal/storage/repositories"+ "github.com/jkaninda/okapi"+)++// LDAPAdminHandler manages the LDAP / Active Directory directories users sign+// in through, and their group mappings. It is plain storage: the directory+// itself is reached only through the enterprise seam. The routes require a+// license; reading needs any license, changing one that has not expired.+type LDAPAdminHandler struct {+ repo *repositories.LDAPRepository+ workspaces *repositories.WorkspaceRepository+ ee enterprise.EE+ audit *audit.Logger+}++func NewLDAPAdminHandler(repo *repositories.LDAPRepository, workspaces *repositories.WorkspaceRepository, ee enterprise.EE, auditLogger *audit.Logger) *LDAPAdminHandler {+ return &LDAPAdminHandler{repo: repo, workspaces: workspaces, ee: ee, audit: auditLogger}+}++type LDAPConfigBody struct {+ DisplayName string `json:"display_name" required:"true" doc:"Shown to admins, such as Corporate AD"`+ Host string `json:"host" required:"true"`+ Port int `json:"port" doc:"Default 389, or 636 for ldaps"`+ TLSMode string `json:"tls_mode" enum:"none,starttls,ldaps" doc:"Default starttls"`+ CACertPEM string `json:"ca_cert_pem" doc:"A private CA to trust, in PEM"`+ InsecureSkipTLS bool `json:"insecure_skip_tls" doc:"Skip certificate checks. Testing only."`+ TimeoutSeconds int `json:"timeout_seconds" doc:"Default 10"`+ BindDN string `json:"bind_dn" doc:"Service account that searches for users; empty binds anonymously"`+ BindPassword string `json:"bind_password" doc:"Service account password. Empty on update keeps the stored one."`+ UserBaseDN string `json:"user_base_dn" required:"true"`+ UserFilter string `json:"user_filter" doc:"%s is the sign-in email. Default (mail=%s)."`+ AttrEmail string `json:"attr_email" doc:"Default mail"`+ AttrName string `json:"attr_name" doc:"Default displayName"`+ GroupBaseDN string `json:"group_base_dn"`+ GroupFilter string `json:"group_filter" doc:"%s is the user's DN, such as (member=%s)"`+ MemberAttr string `json:"member_attr" doc:"Default memberOf"`+ NestedGroups bool `json:"nested_groups" doc:"Active Directory: include nested groups"`+ Enabled *bool `json:"enabled" doc:"Default true"`+}++type CreateLDAPConfigRequest struct {+ Body LDAPConfigBody `json:"body"`+}++type UpdateLDAPConfigRequest struct {+ ID int `param:"id"`+ Body LDAPConfigBody `json:"body"`+}++type LDAPConfigIDRequest struct {+ ID int `param:"id"`+}++type CreateLDAPMappingRequest struct {+ ID int `param:"id"`+ Body struct {+ GroupDN string `json:"group_dn" required:"true" doc:"A group DN, or a bare CN such as posta-admins"`+ PlatformAdmin bool `json:"platform_admin" doc:"Members become platform admins"`+ WorkspaceID *uint `json:"workspace_id" doc:"Members join this workspace"`+ WorkspaceRole models.WorkspaceRole `json:"workspace_role" enum:"admin,editor,viewer" doc:"Their role there"`+ } `json:"body"`+}++// LDAPTestResponse is the outcome of a connection test.+type LDAPTestResponse = enterprise.LDAPTestResult++type DeleteLDAPMappingRequest struct {+ ID int `param:"id"`+ MappingID int `param:"mapping_id"`+}++func (h *LDAPAdminHandler) List(c *okapi.Context) error {+ cfgs, err := h.repo.FindAll()+ if err != nil {+ return c.AbortInternalServerError("failed to list directories")+ }+ if cfgs == nil {+ cfgs = []models.LDAPConfig{}+ }+ return ok(c, cfgs)+}++func (h *LDAPAdminHandler) Create(c *okapi.Context, req *CreateLDAPConfigRequest) error {+ cfg := &models.LDAPConfig{Enabled: true}+ if err := h.apply(c, cfg, req.Body); err != nil {+ return err+ }+ cfg.Name = h.uniqueName(cfg.DisplayName)+ if err := h.repo.Create(cfg); err != nil {+ return c.AbortInternalServerError("failed to create the directory")+ }+ h.log(c, "ldap.created", "LDAP directory "+cfg.DisplayName+" added", cfg)+ saved, _ := h.repo.FindByID(cfg.ID)+ return created(c, saved)+}++func (h *LDAPAdminHandler) Update(c *okapi.Context, req *UpdateLDAPConfigRequest) error {+ cfg, err := h.repo.FindByID(uint(req.ID))+ if err != nil {+ return c.AbortNotFound("directory not found")+ }+ if err := h.apply(c, cfg, req.Body); err != nil {+ return err+ }+ if err := h.repo.Update(cfg); err != nil {+ return c.AbortInternalServerError("failed to update the directory")+ }+ h.log(c, "ldap.updated", "LDAP directory "+cfg.DisplayName+" updated", cfg)+ saved, _ := h.repo.FindByID(cfg.ID)+ return ok(c, saved)+}++func (h *LDAPAdminHandler) Delete(c *okapi.Context, req *LDAPConfigIDRequest) error {+ cfg, err := h.repo.FindByID(uint(req.ID))+ if err != nil {+ return c.AbortNotFound("directory not found")+ }+ if err := h.repo.Delete(cfg.ID); err != nil {+ return c.AbortInternalServerError("failed to delete the directory")+ }+ h.log(c, "ldap.deleted", "LDAP directory "+cfg.DisplayName+" deleted", cfg)+ return noContent(c)+}++// Test connects with the saved settings, binds as the service account and+// reads the user base DN.+func (h *LDAPAdminHandler) Test(c *okapi.Context, req *LDAPConfigIDRequest) error {+ a := h.ee.LDAP()+ if a == nil {+ return licenseAbort(c, h.ee.Require())+ }+ cfg, err := h.repo.FindByID(uint(req.ID))+ if err != nil {+ return c.AbortNotFound("directory not found")+ }+ return ok(c, a.TestConnection(c.Request().Context(), cfg))+}++func (h *LDAPAdminHandler) CreateMapping(c *okapi.Context, req *CreateLDAPMappingRequest) error {+ cfg, err := h.repo.FindByID(uint(req.ID))+ if err != nil {+ return c.AbortNotFound("directory not found")+ }+ b := req.Body+ group := strings.TrimSpace(b.GroupDN)+ switch {+ case group == "":+ return c.AbortBadRequest("group_dn is required")+ case !b.PlatformAdmin && b.WorkspaceID == nil:+ return c.AbortBadRequest("a mapping grants the platform admin role, a workspace, or both")+ case b.WorkspaceID != nil && !slices.Contains(directory.MappableRoles, b.WorkspaceRole):+ return c.AbortBadRequest("workspace_role must be admin, editor or viewer")+ case b.WorkspaceID == nil && b.WorkspaceRole != "":+ return c.AbortBadRequest("workspace_role needs a workspace_id")+ }+ if b.WorkspaceID != nil {+ if _, err := h.workspaces.FindByID(*b.WorkspaceID); err != nil {+ return c.AbortBadRequest(fmt.Sprintf("workspace %d does not exist", *b.WorkspaceID))+ }+ }+ m := &models.LDAPGroupMapping{+ LDAPConfigID: cfg.ID, GroupDN: group,+ PlatformAdmin: b.PlatformAdmin, WorkspaceID: b.WorkspaceID, WorkspaceRole: b.WorkspaceRole,+ }+ if err := h.repo.CreateMapping(m); err != nil {+ return c.AbortInternalServerError("failed to add the mapping")+ }+ h.log(c, "ldap.mapping_added", "Group "+group+" mapped on LDAP directory "+cfg.DisplayName, cfg)+ return created(c, m)+}++func (h *LDAPAdminHandler) DeleteMapping(c *okapi.Context, req *DeleteLDAPMappingRequest) error {+ cfg, err := h.repo.FindByID(uint(req.ID))+ if err != nil {+ return c.AbortNotFound("directory not found")+ }+ deleted, err := h.repo.DeleteMapping(cfg.ID, uint(req.MappingID))+ if err != nil {+ return c.AbortInternalServerError("failed to delete the mapping")+ }+ if !deleted {+ return c.AbortNotFound("mapping not found")+ }+ h.log(c, "ldap.mapping_removed", "Group mapping removed from LDAP directory "+cfg.DisplayName, cfg)+ return noContent(c)+}++func (h *LDAPAdminHandler) apply(c *okapi.Context, cfg *models.LDAPConfig, b LDAPConfigBody) error {+ cfg.DisplayName = strings.TrimSpace(b.DisplayName)+ cfg.Host = strings.TrimSpace(b.Host)+ cfg.UserBaseDN = strings.TrimSpace(b.UserBaseDN)+ tlsMode := b.TLSMode+ if tlsMode == "" {+ tlsMode = models.LDAPTLSStartTLS+ }+ switch {+ case cfg.DisplayName == "":+ return c.AbortBadRequest("display_name is required")+ case cfg.Host == "":+ return c.AbortBadRequest("host is required")+ case cfg.UserBaseDN == "":+ return c.AbortBadRequest("user_base_dn is required")+ case tlsMode != models.LDAPTLSNone && tlsMode != models.LDAPTLSStartTLS && tlsMode != models.LDAPTLSLDAPS:+ return c.AbortBadRequest("tls_mode must be none, starttls or ldaps")+ case b.Port < 0 || b.Port > 65535:+ return c.AbortBadRequest("port must be between 1 and 65535")+ case b.TimeoutSeconds < 0 || b.TimeoutSeconds > 120:+ return c.AbortBadRequest("timeout_seconds must be between 1 and 120")+ case b.UserFilter != "" && !strings.Contains(b.UserFilter, "%s"):+ return c.AbortBadRequest("user_filter must contain %s, the sign-in email")+ }+ cfg.TLSMode = tlsMode+ cfg.Port = b.Port+ if cfg.Port == 0 {+ cfg.Port = 389+ if tlsMode == models.LDAPTLSLDAPS {+ cfg.Port = 636+ }+ }+ cfg.TimeoutSeconds = b.TimeoutSeconds+ if cfg.TimeoutSeconds == 0 {+ cfg.TimeoutSeconds = 10+ }+ cfg.CACertPEM = strings.TrimSpace(b.CACertPEM)+ cfg.InsecureSkipTLS = b.InsecureSkipTLS+ cfg.BindDN = strings.TrimSpace(b.BindDN)+ cfg.UserFilter = strings.TrimSpace(b.UserFilter)+ cfg.AttrEmail = strings.TrimSpace(b.AttrEmail)+ cfg.AttrName = strings.TrimSpace(b.AttrName)+ cfg.GroupBaseDN = strings.TrimSpace(b.GroupBaseDN)+ cfg.GroupFilter = strings.TrimSpace(b.GroupFilter)+ cfg.MemberAttr = strings.TrimSpace(b.MemberAttr)+ cfg.NestedGroups = b.NestedGroups+ if b.Enabled != nil {+ cfg.Enabled = *b.Enabled+ }+ if cfg.BindDN == "" {+ cfg.BindPasswordEnc = ""+ } else if b.BindPassword != "" {+ enc, err := crypto.Encrypt(b.BindPassword)+ if err != nil {+ return c.AbortInternalServerError("failed to encrypt the bind password")+ }+ cfg.BindPasswordEnc = enc+ }+ return nil+}++// uniqueName derives the directory's handle from its display name.+func (h *LDAPAdminHandler) uniqueName(displayName string) string {+ base := slugify(displayName)+ if base == "" {+ base = "directory"+ }+ name := base+ for i := 2; h.repo.NameTaken(name, 0); i++ {+ name = fmt.Sprintf("%s-%d", base, i)+ }+ return name+}++func (h *LDAPAdminHandler) log(c *okapi.Context, action, message string, cfg *models.LDAPConfig) {+ if h.audit == nil {+ return+ }+ h.audit.LogCtx(c, action, message, map[string]any{"ldap_config_id": cfg.ID, "host": cfg.Host})+}diff --git a/internal/handlers/oauth_admin_handler.go b/internal/handlers/oauth_admin_handler.goindex 33a11b7..ce423f6 100644--- a/internal/handlers/oauth_admin_handler.go+++ b/internal/handlers/oauth_admin_handler.go@@ -23,6 +23,7 @@ import ("strings""time"+ "github.com/goposta/posta/internal/enterprise""github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/storage/repositories""github.com/jkaninda/okapi"@@ -31,8 +32,16 @@ import (type OAuthAdminHandler struct {providerRepo *repositories.OAuthProviderRepositoryssoRepo *repositories.WorkspaceSSORepository+ edition enterprise.EE}+// CommunityOAuthProviders is how many OAuth providers Posta Community+// configures. More need a Posta Enterprise license.+const CommunityOAuthProviders = 1++// SetEdition gates providers beyond the Community allowance on the license.+func (h *OAuthAdminHandler) SetEdition(ee enterprise.EE) { h.edition = ee }+func NewOAuthAdminHandler(providerRepo *repositories.OAuthProviderRepository, ssoRepo *repositories.WorkspaceSSORepository) *OAuthAdminHandler {return &OAuthAdminHandler{providerRepo: providerRepo, ssoRepo: ssoRepo}}@@ -109,6 +118,21 @@ type WorkspaceSSOResponse struct {}func (h *OAuthAdminHandler) CreateProvider(c *okapi.Context, req *CreateOAuthProviderRequest) error {+ // Installations that already have several providers keep them; only+ // adding one beyond the allowance needs a license.+ n, err := h.providerRepo.Count()+ if err != nil {+ return c.AbortInternalServerError("failed to count providers")+ }+ if n >= CommunityOAuthProviders {+ edition := h.edition+ if edition == nil {+ edition = enterprise.Community()+ }+ if err := edition.RequireMutable(); err != nil {+ return licenseAbort(c, err)+ }+ }slug := strings.ToLower(strings.TrimSpace(req.Body.Slug))providerType := models.OAuthProviderType(req.Body.Type)if providerType != models.OAuthProviderGoogle && providerType != models.OAuthProviderOIDC {diff --git a/internal/handlers/user_handler.go b/internal/handlers/user_handler.goindex 28ec09d..3b42d4d 100644--- a/internal/handlers/user_handler.go+++ b/internal/handlers/user_handler.go@@ -20,6 +20,7 @@package handlersimport (+ "errors""fmt""net/http""time"@@ -30,6 +31,7 @@ import ("github.com/goposta/posta/internal/dto""github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/services/clientinfo"+ "github.com/goposta/posta/internal/services/directory""github.com/goposta/posta/internal/services/emailverify""github.com/goposta/posta/internal/services/eventbus""github.com/goposta/posta/internal/services/notification"@@ -58,6 +60,7 @@ type UserHandler struct {passwordReset *passwordreset.Servicedb *gorm.DBmigrator *workspaceprovision.Service+ directory *directory.Service}func NewUserHandler(repo *repositories.UserRepository, jwtSecret string, seeder *seeder.Seeder, bus *eventbus.EventBus) *UserHandler {@@ -83,6 +86,9 @@ func (h *UserHandler) ensurePersonalWorkspace(userID uint) {}}+// SetDirectory lets sign-in fall back to LDAP / Active Directory.+func (h *UserHandler) SetDirectory(d *directory.Service) { h.directory = d }+func (h *UserHandler) SetSessionRepo(repo *repositories.SessionRepository) {h.sessionRepo = repo}@@ -467,14 +473,29 @@ func (h *UserHandler) publishLoginFailed(actorID *uint, email, ip, reason stringfunc (h *UserHandler) Login(c *okapi.Context, req *LoginRequest) error {user, err := h.repo.FindByEmail(req.Body.Email)- if err != nil {- h.publishLoginFailed(nil, req.Body.Email, c.RealIP(), "unknown_email")- return c.AbortUnauthorized("invalid credentials")- }-- if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Body.Password)); err != nil {- h.publishLoginFailed(&user.ID, user.Email, c.RealIP(), "bad_password")- return c.AbortUnauthorized("invalid credentials")+ localOK := err == nil && user.AuthMethod != models.AuthMethodLDAP &&+ bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Body.Password)) == nil+ if !localOK {+ // Only after the local check fails, so local accounts and the+ // bootstrap admin keep working when the directory is down.+ dirUser, dirErr := h.directory.Login(c.Request().Context(), req.Body.Email, req.Body.Password)+ switch {+ case dirUser != nil:+ user = dirUser+ case errors.Is(dirErr, directory.ErrAccountDisabled):+ h.publishLoginFailed(nil, req.Body.Email, c.RealIP(), "inactive")+ return c.AbortForbidden("account is disabled")+ case user == nil:+ reason := "unknown_email"+ if dirErr != nil {+ reason = "directory_refused"+ }+ h.publishLoginFailed(nil, req.Body.Email, c.RealIP(), reason)+ return c.AbortUnauthorized("invalid credentials")+ default:+ h.publishLoginFailed(&user.ID, user.Email, c.RealIP(), "bad_password")+ return c.AbortUnauthorized("invalid credentials")+ }}if !user.Active {diff --git a/internal/models/ldap.go b/internal/models/ldap.gonew file mode 100644index 0000000..5610b8b--- /dev/null+++ b/internal/models/ldap.go@@ -0,0 +1,91 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package models++import "time"++// LDAP TLS modes for the directory connection.+const (+ LDAPTLSNone = "none" // plain LDAP: development or a trusted LAN only+ LDAPTLSStartTLS = "starttls" // upgrade a plain connection with StartTLS+ LDAPTLSLDAPS = "ldaps" // implicit TLS, usually port 636+)++// AuthMethodLDAP marks accounts a directory created and manages. They have no+// usable local password.+const AuthMethodLDAP = "ldap"++// LDAPConfig is an LDAP or Active Directory connection users sign in through.+// The table exists in every build; only the Enterprise build reads it.+type LDAPConfig struct {+ ID uint `json:"id" gorm:"primaryKey"`+ // Name is the unique handle; DisplayName the label shown to admins.+ Name string `json:"name" gorm:"uniqueIndex;not null"`+ DisplayName string `json:"display_name"`++ Host string `json:"host" gorm:"not null"`+ Port int `json:"port" gorm:"not null;default:389"`+ TLSMode string `json:"tls_mode" gorm:"not null;default:'starttls'"`+ CACertPEM string `json:"ca_cert_pem" gorm:"type:text"`+ InsecureSkipTLS bool `json:"insecure_skip_tls" gorm:"not null;default:false"`+ TimeoutSeconds int `json:"timeout_seconds" gorm:"not null;default:10"`++ // BindDN is the service account that searches for the user entry before+ // Posta binds as the user to check the password.+ BindDN string `json:"bind_dn"`+ // BindPasswordEnc is the service account's password, encrypted at rest.+ BindPasswordEnc string `json:"-" gorm:"type:text"`++ UserBaseDN string `json:"user_base_dn"`+ // UserFilter finds the user; %s is the escaped sign-in email.+ UserFilter string `json:"user_filter"`+ AttrEmail string `json:"attr_email"` // blank: mail+ AttrName string `json:"attr_name"` // blank: displayName++ // Group resolution, used by LDAPGroupMapping.+ GroupBaseDN string `json:"group_base_dn"`+ GroupFilter string `json:"group_filter"` // %s is the user's DN; blank reads MemberAttr+ MemberAttr string `json:"member_attr"` // blank: memberOf+ NestedGroups bool `json:"nested_groups"` // Active Directory nested groups++ Enabled bool `json:"enabled" gorm:"not null;default:true"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`++ Mappings []LDAPGroupMapping `json:"mappings,omitempty" gorm:"foreignKey:LDAPConfigID;constraint:OnDelete:CASCADE"`++ // BindPasswordSet says whether a service password is stored, without it.+ BindPasswordSet bool `json:"bind_password_set" gorm:"-"`+}++// LDAPGroupMapping maps a directory group to Posta access, reconciled at every+// sign-in: PlatformAdmin grants the platform admin role, WorkspaceID with+// WorkspaceRole grants membership of a workspace.+type LDAPGroupMapping struct {+ ID uint `json:"id" gorm:"primaryKey"`+ LDAPConfigID uint `json:"ldap_config_id" gorm:"index;not null"`+ // GroupDN is matched case-insensitively against the user's groups; a bare+ // CN such as "posta-admins" also works.+ GroupDN string `json:"group_dn" gorm:"not null"`+ PlatformAdmin bool `json:"platform_admin" gorm:"not null;default:false"`+ WorkspaceID *uint `json:"workspace_id"`+ WorkspaceRole WorkspaceRole `json:"workspace_role"`+ CreatedAt time.Time `json:"created_at"`+}diff --git a/internal/routes/ldap_routes.go b/internal/routes/ldap_routes.gonew file mode 100644index 0000000..61c64d9--- /dev/null+++ b/internal/routes/ldap_routes.go@@ -0,0 +1,120 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package routes++import (+ "net/http"++ "github.com/goposta/posta/internal/dto"+ "github.com/goposta/posta/internal/handlers"+ "github.com/goposta/posta/internal/models"+ "github.com/jkaninda/okapi"+)++// ldapRoutes manage the LDAP / Active Directory directories users sign in+// through. Platform admins only; a Posta Enterprise license is required.+func (r *Router) ldapRoutes() []okapi.RouteDefinition {+ admin := r.v1.Group("/admin/ldap", r.mw.jwtAdminAuth.Middleware).WithTagInfo(okapi.GroupTag{+ Name: tagAdmin,+ Description: descAdmin,+ })+ admin.WithBearerAuth()+ id := okapi.DocPathParam("id", "integer", "Directory ID")++ return []okapi.RouteDefinition{+ {+ Method: http.MethodGet,+ Path: "",+ Handler: r.h.ldapAdmin.List,+ Group: admin,+ Middlewares: r.licensed(),+ Summary: "List LDAP directories",+ Description: "The LDAP / Active Directory directories users sign in through, with their group mappings, in the order sign-in tries them.",+ Response: &dto.Response[[]models.LDAPConfig]{},+ },+ {+ Method: http.MethodPost,+ Path: "",+ Handler: okapi.H(r.h.ldapAdmin.Create),+ Group: admin,+ Middlewares: r.licensedToChange(),+ Summary: "Add an LDAP directory",+ Request: &handlers.CreateLDAPConfigRequest{},+ Options: []okapi.RouteOption{okapi.DocResponse(201, &dto.Response[models.LDAPConfig]{})},+ },+ {+ Method: http.MethodPut,+ Path: pathByID,+ Handler: okapi.H(r.h.ldapAdmin.Update),+ Group: admin,+ Middlewares: r.licensedToChange(),+ Summary: "Update an LDAP directory",+ Description: "An empty bind_password keeps the stored one.",+ Request: &handlers.UpdateLDAPConfigRequest{},+ Response: &dto.Response[models.LDAPConfig]{},+ Options: []okapi.RouteOption{id},+ },+ {+ Method: http.MethodDelete,+ Path: pathByID,+ Handler: okapi.H(r.h.ldapAdmin.Delete),+ Group: admin,+ Middlewares: r.licensedToChange(),+ Summary: "Delete an LDAP directory",+ Description: "Accounts it created stay, but can no longer sign in until another directory or a password reset lets them.",+ Options: []okapi.RouteOption{id, okapi.DocResponse(204, nil)},+ },+ {+ Method: http.MethodPost,+ Path: pathByID + "/test",+ Handler: okapi.H(r.h.ldapAdmin.Test),+ Group: admin,+ Middlewares: r.licensed(),+ Summary: "Test an LDAP directory",+ Description: "Connects with the saved settings, binds as the service account and reads the user base DN. A failure is reported in the result, not as an error status.",+ Response: &dto.Response[handlers.LDAPTestResponse]{},+ Options: []okapi.RouteOption{id},+ },+ {+ Method: http.MethodPost,+ Path: pathByID + "/mappings",+ Handler: okapi.H(r.h.ldapAdmin.CreateMapping),+ Group: admin,+ Middlewares: r.licensedToChange(),+ Summary: "Map a directory group to Posta access",+ Description: "Members of the group become platform admins, or join a workspace with a role. Applied at every sign-in, to accounts the directory created.",+ Request: &handlers.CreateLDAPMappingRequest{},+ Options: []okapi.RouteOption{id, okapi.DocResponse(201, &dto.Response[models.LDAPGroupMapping]{})},+ },+ {+ Method: http.MethodDelete,+ Path: pathByID + "/mappings/{mapping_id:int}",+ Handler: okapi.H(r.h.ldapAdmin.DeleteMapping),+ Group: admin,+ Middlewares: r.licensedToChange(),+ Summary: "Remove a group mapping",+ Options: []okapi.RouteOption{+ id,+ okapi.DocPathParam("mapping_id", "integer", "Mapping ID"),+ okapi.DocResponse(204, nil),+ },+ },+ }+}diff --git a/internal/routes/oauth_routes.go b/internal/routes/oauth_routes.goindex b8a9793..5f79c63 100644--- a/internal/routes/oauth_routes.go+++ b/internal/routes/oauth_routes.go@@ -147,7 +147,7 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {},{Method: http.MethodPut,- Path: "/{id:int}",+ Path: pathByID,Handler: okapi.H(r.h.oauthAdmin.UpdateProvider),Group: oauthAdmin,Summary: "Update OAuth provider",@@ -159,7 +159,7 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {},{Method: http.MethodDelete,- Path: "/{id:int}",+ Path: pathByID,Handler: okapi.H(r.h.oauthAdmin.DeleteProvider),Group: oauthAdmin,Summary: "Delete OAuth provider",diff --git a/internal/routes/paths.go b/internal/routes/paths.goindex 7e168be..1321176 100644--- a/internal/routes/paths.go+++ b/internal/routes/paths.go@@ -36,6 +36,7 @@ const (pathWebhooks = "/webhooks"pathWorkspaces = "/workspaces"+ pathByID = "/{id:int}"pathAnnouncementByID = "/announcements/{id:int}"pathCampaignByID = "/campaigns/{id:int}"pathDomainByID = "/domains/{id:int}"diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 80ad5fa..ab4bb89 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -33,6 +33,7 @@ import ("github.com/goposta/posta/internal/services/audit""github.com/goposta/posta/internal/services/auth""github.com/goposta/posta/internal/services/cache"+ "github.com/goposta/posta/internal/services/directory""github.com/goposta/posta/internal/services/email""github.com/goposta/posta/internal/services/emailverify""github.com/goposta/posta/internal/services/eventbus"@@ -147,6 +148,7 @@ type routerHandlers struct {team *handlers.TeamHandlerformIngest *handlers.FormIngestHandlerlicense *handlers.LicenseHandler+ ldapAdmin *handlers.LDAPAdminHandler}func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *config.Config, edition enterprise.EE, producer *worker.Producer, cronManager *cronpkg.Manager, blobStore blob.Store, ctx context.Context, notifier ...*notification.Service) *email.Service {@@ -380,6 +382,11 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c)r.h.oauth.SetMigrator(db, migrator)r.h.oauthAdmin = handlers.NewOAuthAdminHandler(oauthProviderRepo, ssoRepo)+ r.h.oauthAdmin.SetEdition(edition)++ ldapRepo := repositories.NewLDAPRepository(db)+ r.h.ldapAdmin = handlers.NewLDAPAdminHandler(ldapRepo, workspaceRepo, edition, auditLogger)+ r.h.user.SetDirectory(directory.NewService(edition, userRepo, workspaceRepo, ldapRepo))// SubscriberssubscriberRepo := repositories.NewSubscriberRepository(db)@@ -610,6 +617,7 @@ func (r *Router) registerRoutes() {r.app.Register(r.adminSSERoutes()...)r.app.Register(r.adminRoutes()...)r.app.Register(r.licenseRoutes()...)+ r.app.Register(r.ldapRoutes()...)// Documentation-only OpenAPI webhooks (events Posta POSTs to subscribers).r.registerWebhookDocs()diff --git a/internal/services/directory/service.go b/internal/services/directory/service.gonew file mode 100644index 0000000..fcd32de--- /dev/null+++ b/internal/services/directory/service.go@@ -0,0 +1,291 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++// Package directory turns a successful LDAP or Active Directory sign-in into+// a Posta user: it creates the account the first time, and keeps the platform+// admin role and workspace memberships in step with the user's directory+// groups. The bind itself sits behind the enterprise seam, so this package+// never talks to a directory.+package directory++import (+ "context"+ "crypto/rand"+ "errors"+ "strings"+ "time"++ "github.com/goposta/posta/internal/enterprise"+ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/storage/repositories"+ "github.com/jkaninda/logger"+ "golang.org/x/crypto/bcrypt"+ "gorm.io/gorm"+)++var (+ // ErrAccountDisabled: the directory accepted the password, but the Posta+ // account is disabled.+ ErrAccountDisabled = errors.New("account is disabled")+ // ErrNoEmail: the directory entry has no email, a mapping mistake the+ // admin needs to fix.+ ErrNoEmail = errors.New("the directory entry has no email address")+)++type Service struct {+ ee enterprise.EE+ users *repositories.UserRepository+ workspaces *repositories.WorkspaceRepository+ ldap *repositories.LDAPRepository+}++func NewService(ee enterprise.EE, users *repositories.UserRepository, workspaces *repositories.WorkspaceRepository, ldap *repositories.LDAPRepository) *Service {+ return &Service{ee: ee, users: users, workspaces: workspaces, ldap: ldap}+}++// Login tries the directories after the local password check failed.+// (user, nil): the password bound and the account is ready. (nil, nil): no+// directory knows the email, so the caller keeps its local result. (nil,+// err): a directory knows the user but refused the password or could not be+// reached, or the Posta account is disabled.+func (s *Service) Login(ctx context.Context, email, password string) (*models.User, error) {+ if s == nil || s.ee == nil {+ return nil, nil+ }+ a := s.ee.LDAP()+ if a == nil {+ return nil, nil // Community, or no license+ }+ ident, err := a.Authenticate(ctx, email, password)+ if errors.Is(err, enterprise.ErrLDAPNoMatch) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }+ user, err := s.provision(ident)+ if err != nil {+ return nil, err+ }+ // Group mapping is best effort: it must never block a valid sign-in.+ if err := s.reconcile(user, ident); err != nil {+ logger.Warn("directory: group mapping failed", "user", user.ID, "error", err)+ }+ return user, nil+}++// provision finds the account by email, or creates a directory-managed one.+// An existing local or OAuth account with the same email is used as is: the+// directory has just proved the person owns that address.+func (s *Service) provision(ident enterprise.LDAPIdentity) (*models.User, error) {+ email := strings.ToLower(strings.TrimSpace(ident.Email))+ if email == "" {+ return nil, ErrNoEmail+ }+ if u, err := s.users.FindByEmail(email); err == nil {+ if !u.Active {+ return nil, ErrAccountDisabled+ }+ return u, nil+ } else if !errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, err+ }+ name := strings.TrimSpace(ident.Name)+ if name == "" {+ name = strings.SplitN(email, "@", 2)[0]+ }+ now := time.Now()+ user := &models.User{+ Name: name,+ Email: email,+ PasswordHash: unusablePassword(),+ Role: models.UserRoleUser,+ Active: true,+ AuthMethod: models.AuthMethodLDAP,+ EmailVerifiedAt: &now, // the directory vouches for the address+ }+ if err := s.users.Create(user); err != nil {+ return nil, err+ }+ logger.Info("directory: account created on first sign-in", "user", user.ID, "directory", ident.Directory)+ return user, nil+}++// reconcile applies the directory's group mappings. Only accounts the+// directory created are touched, and only the access a mapping governs: a+// workspace no mapping names, or the admin role when no mapping grants it, is+// left as an admin set it by hand.+func (s *Service) reconcile(user *models.User, ident enterprise.LDAPIdentity) error {+ if user.AuthMethod != models.AuthMethodLDAP {+ return nil+ }+ cfg, err := s.ldap.FindByName(ident.Directory)+ if err != nil || len(cfg.Mappings) == 0 {+ return err+ }+ plan := Plan(cfg.Mappings, ident.Groups)+ if plan.AdminManaged {+ s.reconcileAdmin(user, plan.Admin)+ }+ for wsID := range plan.Managed {+ role, want := plan.Roles[wsID]+ member, err := s.workspaces.FindMember(wsID, user.ID)+ if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {+ logger.Warn("directory: read membership failed", "workspace", wsID, "user", user.ID, "error", err)+ continue+ }+ switch {+ case member != nil && member.Role == models.WorkspaceRoleOwner:+ // The owner's membership is never changed from a directory.+ case want && member == nil:+ if err := s.workspaces.AddMember(&models.WorkspaceMember{WorkspaceID: wsID, UserID: user.ID, Role: role}); err != nil {+ logger.Warn("directory: add member failed", "workspace", wsID, "user", user.ID, "error", err)+ }+ case want && member.Role != role:+ if err := s.workspaces.UpdateMemberRole(wsID, user.ID, role); err != nil {+ logger.Warn("directory: change role failed", "workspace", wsID, "user", user.ID, "error", err)+ }+ case !want && member != nil:+ if err := s.workspaces.RemoveMember(wsID, user.ID); err != nil {+ logger.Warn("directory: remove member failed", "workspace", wsID, "user", user.ID, "error", err)+ }+ }+ }+ return nil+}++// reconcileAdmin grants or withdraws the platform admin role, never taking it+// from the last admin who can sign in.+func (s *Service) reconcileAdmin(user *models.User, want bool) {+ isAdmin := user.Role == models.UserRoleAdmin+ switch {+ case want && !isAdmin:+ user.Role = models.UserRoleAdmin+ case !want && isAdmin:+ if n, err := s.users.CountActiveAdmins(); err != nil || n <= 1 {+ return+ }+ user.Role = models.UserRoleUser+ default:+ return+ }+ if err := s.users.Update(user); err != nil {+ logger.Warn("directory: change platform role failed", "user", user.ID, "error", err)+ }+}++// Access is what a user's groups grant under a directory's mappings.+type Access struct {+ // Admin is whether a mapping grants the platform admin role, and+ // AdminManaged whether any mapping governs it at all.+ Admin bool+ AdminManaged bool+ // Roles is the highest role granted per workspace; Managed every+ // workspace a mapping names.+ Roles map[uint]models.WorkspaceRole+ Managed map[uint]bool+}++// Plan works out what groups grant under mappings.+func Plan(mappings []models.LDAPGroupMapping, groups []string) Access {+ have := normalizeGroups(groups)+ a := Access{Roles: map[uint]models.WorkspaceRole{}, Managed: map[uint]bool{}}+ for _, m := range mappings {+ if m.PlatformAdmin {+ a.AdminManaged = true+ }+ if m.WorkspaceID != nil {+ a.Managed[*m.WorkspaceID] = true+ }+ if !groupMatches(have, m.GroupDN) {+ continue+ }+ if m.PlatformAdmin {+ a.Admin = true+ }+ if m.WorkspaceID != nil && roleRank(m.WorkspaceRole) > roleRank(a.Roles[*m.WorkspaceID]) {+ a.Roles[*m.WorkspaceID] = m.WorkspaceRole+ }+ }+ return a+}++// MappableRoles are the workspace roles a group may grant. Owner is not one:+// a workspace has exactly one owner, who is never managed by a directory.+var MappableRoles = []models.WorkspaceRole{models.WorkspaceRoleAdmin, models.WorkspaceRoleEditor, models.WorkspaceRoleViewer}++func roleRank(r models.WorkspaceRole) int {+ switch r {+ case models.WorkspaceRoleAdmin:+ return 3+ case models.WorkspaceRoleEditor:+ return 2+ case models.WorkspaceRoleViewer:+ return 1+ }+ return 0+}++func normalizeGroups(groups []string) map[string]bool {+ m := make(map[string]bool, len(groups))+ for _, g := range groups {+ if g = strings.ToLower(strings.TrimSpace(g)); g != "" {+ m[g] = true+ }+ }+ return m+}++// groupMatches reports whether a mapping's group, a full DN or a bare CN,+// matches one of the user's groups, ignoring case.+func groupMatches(have map[string]bool, group string) bool {+ g := strings.ToLower(strings.TrimSpace(group))+ if g == "" {+ return false+ }+ if have[g] {+ return true+ }+ if !strings.Contains(g, "=") {+ for dn := range have {+ if cnOf(dn) == g {+ return true+ }+ }+ }+ return false+}++// cnOf is the value of a DN's first RDN: "cn=admins,ou=groups" gives "admins".+func cnOf(dn string) string {+ first, _, _ := strings.Cut(dn, ",")+ if _, v, ok := strings.Cut(first, "="); ok {+ return strings.TrimSpace(v)+ }+ return strings.TrimSpace(first)+}++// unusablePassword is a bcrypt hash of random bytes, so a directory account+// can never sign in with a local password.+func unusablePassword() string {+ b := make([]byte, 32)+ _, _ = rand.Read(b)+ hash, _ := bcrypt.GenerateFromPassword(b, bcrypt.DefaultCost)+ return string(hash)+}diff --git a/internal/services/directory/service_test.go b/internal/services/directory/service_test.gonew file mode 100644index 0000000..358eeee--- /dev/null+++ b/internal/services/directory/service_test.go@@ -0,0 +1,94 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package directory++import (+ "testing"++ "github.com/goposta/posta/internal/models"+)++func ws(id uint) *uint { return &id }++func TestPlan(t *testing.T) {+ mappings := []models.LDAPGroupMapping{+ {GroupDN: "cn=posta-admins,ou=groups,dc=corp,dc=test", PlatformAdmin: true},+ {GroupDN: "sales", WorkspaceID: ws(1), WorkspaceRole: models.WorkspaceRoleViewer},+ {GroupDN: "sales-leads", WorkspaceID: ws(1), WorkspaceRole: models.WorkspaceRoleAdmin},+ {GroupDN: "support", WorkspaceID: ws(2), WorkspaceRole: models.WorkspaceRoleEditor},+ }++ a := Plan(mappings, []string{"CN=Sales,OU=Groups,DC=corp,DC=test", "cn=sales-leads,ou=groups,dc=corp,dc=test"})+ if a.Admin || !a.AdminManaged {+ t.Errorf("admin = %v, managed = %v", a.Admin, a.AdminManaged)+ }+ if a.Roles[1] != models.WorkspaceRoleAdmin {+ t.Errorf("workspace 1 role = %q, want the highest granted, admin", a.Roles[1])+ }+ if _, ok := a.Roles[2]; ok || !a.Managed[2] {+ t.Errorf("workspace 2: no group grants it, but a mapping governs it: %+v", a)+ }++ a = Plan(mappings, []string{"cn=posta-admins,ou=groups,dc=corp,dc=test"})+ if !a.Admin || len(a.Roles) != 0 {+ t.Errorf("full DN match: %+v", a)+ }++ a = Plan([]models.LDAPGroupMapping{{GroupDN: "sales", WorkspaceID: ws(1), WorkspaceRole: models.WorkspaceRoleEditor}}, nil)+ if a.AdminManaged {+ t.Error("no mapping grants admin, so the admin role must be left alone")+ }+}++func TestGroupMatches(t *testing.T) {+ have := normalizeGroups([]string{"cn=Engineering,ou=groups,dc=corp,dc=test", " "})+ cases := map[string]bool{+ "engineering": true,+ "CN=ENGINEERING,OU=GROUPS,DC=CORP,DC=TEST": true,+ "cn=engineering,ou=other,dc=corp,dc=test": false,+ "eng": false,+ "": false,+ }+ for group, want := range cases {+ if got := groupMatches(have, group); got != want {+ t.Errorf("groupMatches(%q) = %v, want %v", group, got, want)+ }+ }+}++func TestCnOf(t *testing.T) {+ for dn, want := range map[string]string{+ "cn=admins,ou=groups,dc=x": "admins",+ "cn= spaced ,dc=x": "spaced",+ "plain": "plain",+ } {+ if got := cnOf(dn); got != want {+ t.Errorf("cnOf(%q) = %q, want %q", dn, got, want)+ }+ }+}++func TestOwnerIsNotMappable(t *testing.T) {+ for _, r := range MappableRoles {+ if r == models.WorkspaceRoleOwner {+ t.Fatal("a directory group must never grant workspace ownership")+ }+ }+}diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.goindex eeba3f8..1882ab2 100644--- a/internal/storage/migration/migration.go+++ b/internal/storage/migration/migration.go@@ -85,6 +85,8 @@ func Run(db *gorm.DB) error {&models.UpgradeStep{},&models.UpdateStatus{},&models.License{},+ &models.LDAPConfig{},+ &models.LDAPGroupMapping{},); err != nil {return fmt.Errorf("failed to migrate database: %w", err)}diff --git a/internal/storage/repositories/ldap_repo.go b/internal/storage/repositories/ldap_repo.gonew file mode 100644index 0000000..fa62cb7--- /dev/null+++ b/internal/storage/repositories/ldap_repo.go@@ -0,0 +1,110 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package repositories++import (+ "github.com/goposta/posta/internal/models"+ "gorm.io/gorm"+)++type LDAPRepository struct {+ db *gorm.DB+}++func NewLDAPRepository(db *gorm.DB) *LDAPRepository {+ return &LDAPRepository{db: db}+}++func withPasswordFlag(cfg *models.LDAPConfig) *models.LDAPConfig {+ cfg.BindPasswordSet = cfg.BindPasswordEnc != ""+ return cfg+}++// FindAll lists every directory with its group mappings, oldest first: the+// order sign-in tries them in.+func (r *LDAPRepository) FindAll() ([]models.LDAPConfig, error) {+ var cfgs []models.LDAPConfig+ if err := r.db.Preload("Mappings", func(db *gorm.DB) *gorm.DB { return db.Order("id ASC") }).+ Order("id ASC").Find(&cfgs).Error; err != nil {+ return nil, err+ }+ for i := range cfgs {+ withPasswordFlag(&cfgs[i])+ }+ return cfgs, nil+}++// Enabled lists the directories sign-in tries, in order.+func (r *LDAPRepository) Enabled() ([]models.LDAPConfig, error) {+ var cfgs []models.LDAPConfig+ err := r.db.Where("enabled = ?", true).Order("id ASC").Find(&cfgs).Error+ return cfgs, err+}++func (r *LDAPRepository) FindByID(id uint) (*models.LDAPConfig, error) {+ var cfg models.LDAPConfig+ if err := r.db.Preload("Mappings", func(db *gorm.DB) *gorm.DB { return db.Order("id ASC") }).+ First(&cfg, id).Error; err != nil {+ return nil, err+ }+ return withPasswordFlag(&cfg), nil+}++func (r *LDAPRepository) FindByName(name string) (*models.LDAPConfig, error) {+ var cfg models.LDAPConfig+ if err := r.db.Preload("Mappings").Where("name = ?", name).First(&cfg).Error; err != nil {+ return nil, err+ }+ return withPasswordFlag(&cfg), nil+}++func (r *LDAPRepository) NameTaken(name string, exceptID uint) bool {+ var n int64+ r.db.Model(&models.LDAPConfig{}).Where("name = ? AND id <> ?", name, exceptID).Count(&n)+ return n > 0+}++func (r *LDAPRepository) Create(cfg *models.LDAPConfig) error {+ return r.db.Omit("Mappings").Create(cfg).Error+}++func (r *LDAPRepository) Update(cfg *models.LDAPConfig) error {+ return r.db.Omit("Mappings").Save(cfg).Error+}++// Delete removes a directory and its group mappings.+func (r *LDAPRepository) Delete(id uint) error {+ return r.db.Transaction(func(tx *gorm.DB) error {+ if err := tx.Where("ldap_config_id = ?", id).Delete(&models.LDAPGroupMapping{}).Error; err != nil {+ return err+ }+ return tx.Delete(&models.LDAPConfig{}, id).Error+ })+}++func (r *LDAPRepository) CreateMapping(m *models.LDAPGroupMapping) error {+ return r.db.Create(m).Error+}++// DeleteMapping removes one mapping of a directory; false when there was none.+func (r *LDAPRepository) DeleteMapping(configID, mappingID uint) (bool, error) {+ res := r.db.Where("id = ? AND ldap_config_id = ?", mappingID, configID).Delete(&models.LDAPGroupMapping{})+ return res.RowsAffected > 0, res.Error+}diff --git a/internal/storage/repositories/oauth_provider_repo.go b/internal/storage/repositories/oauth_provider_repo.goindex 1087a8a..066b2af 100644--- a/internal/storage/repositories/oauth_provider_repo.go+++ b/internal/storage/repositories/oauth_provider_repo.go@@ -34,6 +34,13 @@ func NewOAuthProviderRepository(db *gorm.DB) *OAuthProviderRepository {return &OAuthProviderRepository{db: db}}+// Count counts the configured providers, enabled or not.+func (r *OAuthProviderRepository) Count() (int64, error) {+ var n int64+ err := r.db.Model(&models.OAuthProvider{}).Count(&n).Error+ return n, err+}+func (r *OAuthProviderRepository) Create(p *models.OAuthProvider) error {return r.db.Create(p).Error}diff --git a/internal/storage/repositories/user_repo.go b/internal/storage/repositories/user_repo.goindex fe81196..ed6639d 100644--- a/internal/storage/repositories/user_repo.go+++ b/internal/storage/repositories/user_repo.go@@ -158,6 +158,13 @@ func (r *UserRepository) FindAll(search string, limit, offset int) ([]models.Usereturn users, total, nil}+// CountActiveAdmins counts the platform admins who can still sign in.+func (r *UserRepository) CountActiveAdmins() (int64, error) {+ var n int64+ err := r.db.Model(&models.User{}).Where("role = ? AND active = ?", models.UserRoleAdmin, true).Count(&n).Error+ return n, err+}+func (r *UserRepository) Update(user *models.User) error {return r.db.Save(user).Error}diff --git a/web/src/api/ldap.ts b/web/src/api/ldap.tsnew file mode 100644index 0000000..56d9a14--- /dev/null+++ b/web/src/api/ldap.ts@@ -0,0 +1,100 @@+import api from './client'+import type { ApiResponse } from './types'++export type LDAPTLSMode = 'none' | 'starttls' | 'ldaps'+export type MappableRole = 'admin' | 'editor' | 'viewer'++export interface LDAPGroupMapping {+ id: number+ ldap_config_id: number+ group_dn: string+ platform_admin: boolean+ workspace_id: number | null+ workspace_role: MappableRole | ''+ created_at: string+}++export interface LDAPDirectory {+ id: number+ name: string+ display_name: string+ host: string+ port: number+ tls_mode: LDAPTLSMode+ ca_cert_pem: string+ insecure_skip_tls: boolean+ timeout_seconds: number+ bind_dn: string+ /** Whether a service password is stored; the password itself is never returned. */+ bind_password_set: boolean+ user_base_dn: string+ user_filter: string+ attr_email: string+ attr_name: string+ group_base_dn: string+ group_filter: string+ member_attr: string+ nested_groups: boolean+ enabled: boolean+ mappings?: LDAPGroupMapping[]+ created_at: string+}++export interface LDAPDirectoryInput {+ display_name: string+ host: string+ port?: number+ tls_mode: LDAPTLSMode+ ca_cert_pem?: string+ insecure_skip_tls?: boolean+ timeout_seconds?: number+ bind_dn?: string+ /** Empty on update keeps the stored password. */+ bind_password?: string+ user_base_dn: string+ user_filter?: string+ attr_email?: string+ attr_name?: string+ group_base_dn?: string+ group_filter?: string+ member_attr?: string+ nested_groups?: boolean+ enabled?: boolean+}++export interface LDAPMappingInput {+ group_dn: string+ platform_admin: boolean+ workspace_id?: number+ workspace_role?: MappableRole+}++export interface LDAPTestResult {+ ok: boolean+ message?: string+ error?: string+}++export const ldapApi = {+ list() {+ return api.get<ApiResponse<LDAPDirectory[]>>('/admin/ldap')+ },+ create(input: LDAPDirectoryInput) {+ return api.post<ApiResponse<LDAPDirectory>>('/admin/ldap', input)+ },+ update(id: number, input: LDAPDirectoryInput) {+ return api.put<ApiResponse<LDAPDirectory>>(`/admin/ldap/${id}`, input)+ },+ remove(id: number) {+ return api.delete(`/admin/ldap/${id}`)+ },+ test(id: number) {+ return api.post<ApiResponse<LDAPTestResult>>(`/admin/ldap/${id}/test`)+ },+ addMapping(id: number, input: LDAPMappingInput) {+ return api.post<ApiResponse<LDAPGroupMapping>>(`/admin/ldap/${id}/mappings`, input)+ },+ removeMapping(id: number, mappingId: number) {+ return api.delete(`/admin/ldap/${id}/mappings/${mappingId}`)+ },+}diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vueindex 58fe9ef..6fe4636 100644--- a/web/src/layouts/DashboardLayout.vue+++ b/web/src/layouts/DashboardLayout.vue@@ -296,6 +296,7 @@ const adminNavSections: NavSection[] = [items: [{ name: 'Users', path: '/admin/users', icon: 'users' },{ name: 'OAuth Providers', path: '/admin/oauth', icon: 'shield' },+ { name: 'LDAP Directories', path: '/admin/ldap', icon: 'server', enterprise: true },],},{diff --git a/web/src/router/index.ts b/web/src/router/index.tsindex 3c66805..212edbb 100644--- a/web/src/router/index.ts+++ b/web/src/router/index.ts@@ -126,6 +126,7 @@ const routes = [{ path: 'admin/jobs', name: 'admin-jobs', component: () => import('../views/admin/Jobs.vue'), meta: { admin: true, title: 'Admin · Jobs' } },{ path: 'admin/oauth', name: 'admin-oauth', component: () => import('../views/admin/OAuthProviders.vue'), meta: { admin: true, title: 'Admin · OAuth Providers' } },{ path: 'admin/settings', name: 'admin-settings', component: () => import('../views/admin/Settings.vue'), meta: { admin: true, title: 'Admin · Settings' } },+ { path: 'admin/ldap', name: 'admin-ldap', component: () => import('../views/admin/LdapDirectories.vue'), meta: { admin: true, title: 'Admin · LDAP Directories' } },{ path: 'admin/license', name: 'admin-license', component: () => import('../views/admin/License.vue'), meta: { admin: true, title: 'Admin · License' } },],},diff --git a/web/src/views/admin/LdapDirectories.vue b/web/src/views/admin/LdapDirectories.vuenew file mode 100644index 0000000..b28198d--- /dev/null+++ b/web/src/views/admin/LdapDirectories.vue@@ -0,0 +1,562 @@+<script setup lang="ts">+import { computed, onMounted, ref } from 'vue'+import { ldapApi, type LDAPDirectory, type LDAPDirectoryInput, type LDAPTestResult, type MappableRole } from '../../api/ldap'+import { adminApi } from '../../api/admin'+import type { AdminWorkspaceRow } from '../../api/types'+import { useNotificationStore } from '../../stores/notification'+import { useLicenseStore } from '../../stores/license'+import { useConfirm } from '../../composables/useConfirm'+import { apiMessage } from '../../composables/apiError'+import EnterpriseLock from '../../components/EnterpriseLock.vue'++// LDAP / Active Directory sign-in. People sign in with their directory email+// and password; Posta asks the directories only after the local password+// check fails, so local accounts keep working when a directory is down.++const notify = useNotificationStore()+const license = useLicenseStore()+const { confirm } = useConfirm()++const loading = ref(true)+const directories = ref<LDAPDirectory[]>([])+const workspaces = ref<AdminWorkspaceRow[]>([])+const tests = ref<Record<number, LDAPTestResult | 'running'>>({})++const workspaceName = computed(() => Object.fromEntries(workspaces.value.map((w) => [w.id, w.name])))++async function load() {+ loading.value = true+ try {+ const [dirRes, wsRes] = await Promise.all([ldapApi.list(), adminApi.listWorkspaces(0, 200).catch(() => null)])+ directories.value = dirRes.data.data+ if (wsRes) workspaces.value = wsRes.data.data.filter((w) => !w.system)+ } catch (e: any) {+ notify.error(apiMessage(e, 'Failed to load directories'))+ } finally {+ loading.value = false+ }+}++// ---- Directory editor ----++const showEditor = ref(false)+const editing = ref<LDAPDirectory | null>(null)+const saving = ref(false)+const blank = (): LDAPDirectoryInput & { bind_password: string } => ({+ display_name: '',+ host: '',+ port: undefined,+ tls_mode: 'starttls',+ ca_cert_pem: '',+ insecure_skip_tls: false,+ timeout_seconds: 10,+ bind_dn: '',+ bind_password: '',+ user_base_dn: '',+ user_filter: '',+ attr_email: '',+ attr_name: '',+ group_base_dn: '',+ group_filter: '',+ member_attr: '',+ nested_groups: false,+ enabled: true,+})+const draft = ref(blank())++function openEditor(dir: LDAPDirectory | null) {+ editing.value = dir+ draft.value = dir+ ? {+ display_name: dir.display_name,+ host: dir.host,+ port: dir.port,+ tls_mode: dir.tls_mode,+ ca_cert_pem: dir.ca_cert_pem,+ insecure_skip_tls: dir.insecure_skip_tls,+ timeout_seconds: dir.timeout_seconds,+ bind_dn: dir.bind_dn,+ bind_password: '',+ user_base_dn: dir.user_base_dn,+ user_filter: dir.user_filter,+ attr_email: dir.attr_email,+ attr_name: dir.attr_name,+ group_base_dn: dir.group_base_dn,+ group_filter: dir.group_filter,+ member_attr: dir.member_attr,+ nested_groups: dir.nested_groups,+ enabled: dir.enabled,+ }+ : blank()+ showEditor.value = true+}++const canSave = computed(+ () => !!draft.value.display_name.trim() && !!draft.value.host.trim() && !!draft.value.user_base_dn.trim(),+)++async function save() {+ saving.value = true+ try {+ const input = { ...draft.value, port: draft.value.port || undefined }+ if (editing.value) await ldapApi.update(editing.value.id, input)+ else await ldapApi.create(input)+ notify.success(editing.value ? 'Directory saved.' : 'Directory added. Test it before people sign in.')+ showEditor.value = false+ await load()+ } catch (e: any) {+ notify.error(apiMessage(e, 'Failed to save the directory'))+ } finally {+ saving.value = false+ }+}++async function remove(dir: LDAPDirectory) {+ const ok = await confirm({+ title: `Delete ${dir.display_name}?`,+ message:+ 'People can no longer sign in through it. Accounts it created stay, with their data, but cannot sign in until another directory or a password reset lets them.',+ confirmText: 'Delete directory',+ variant: 'danger',+ })+ if (!ok) return+ try {+ await ldapApi.remove(dir.id)+ notify.success('Directory deleted.')+ await load()+ } catch (e: any) {+ notify.error(apiMessage(e, 'Failed to delete the directory'))+ }+}++async function test(dir: LDAPDirectory) {+ tests.value[dir.id] = 'running'+ try {+ tests.value[dir.id] = (await ldapApi.test(dir.id)).data.data+ } catch (e: any) {+ delete tests.value[dir.id]+ notify.error(apiMessage(e, 'Failed to test the directory'))+ }+}++// ---- Group mappings ----++const mappingDrafts = ref<Record<number, { group_dn: string; platform_admin: boolean; workspace_id: number | ''; workspace_role: MappableRole }>>({})++function mappingDraft(id: number) {+ if (!mappingDrafts.value[id]) {+ mappingDrafts.value[id] = { group_dn: '', platform_admin: false, workspace_id: '', workspace_role: 'viewer' }+ }+ return mappingDrafts.value[id]+}++function canAddMapping(id: number) {+ const m = mappingDraft(id)+ return !!m.group_dn.trim() && (m.platform_admin || m.workspace_id !== '')+}++async function addMapping(dir: LDAPDirectory) {+ const m = mappingDraft(dir.id)+ try {+ await ldapApi.addMapping(dir.id, {+ group_dn: m.group_dn.trim(),+ platform_admin: m.platform_admin,+ workspace_id: m.workspace_id === '' ? undefined : m.workspace_id,+ workspace_role: m.workspace_id === '' ? undefined : m.workspace_role,+ })+ delete mappingDrafts.value[dir.id]+ notify.success('Group mapped. It applies from the next sign-in.')+ await load()+ } catch (e: any) {+ notify.error(apiMessage(e, 'Failed to add the mapping'))+ }+}++async function removeMapping(dir: LDAPDirectory, mappingId: number) {+ try {+ await ldapApi.removeMapping(dir.id, mappingId)+ await load()+ } catch (e: any) {+ notify.error(apiMessage(e, 'Failed to remove the mapping'))+ }+}++function grants(m: { platform_admin: boolean; workspace_id: number | null; workspace_role: string }) {+ const out: string[] = []+ if (m.platform_admin) out.push('Platform admin')+ if (m.workspace_id) out.push(`${m.workspace_role} in ${workspaceName.value[m.workspace_id] || `workspace #${m.workspace_id}`}`)+ return out.join(' · ')+}++function testOf(id: number) {+ const t = tests.value[id]+ return t === 'running' ? null : t+}++onMounted(async () => {+ await license.load()+ if (license.licensed) await load()+ else loading.value = false+})+</script>++<template>+ <div>+ <div class="page-header">+ <div>+ <h1>LDAP Directories</h1>+ <p class="ldap-intro">+ People sign in with their directory email and password. Posta asks a directory only when the local+ password does not match, so local accounts keep working if it is down.+ </p>+ </div>+ <button v-if="license.mutable" class="btn btn-primary" @click="openEditor(null)">Add directory</button>+ </div>++ <EnterpriseLock+ feature="LDAP / Active Directory sign-in"+ description="Let people sign in with their LDAP or Active Directory account. Posta creates their account on first sign-in, and directory groups can make them platform admins or members of workspaces."+ >+ <div v-if="loading" class="loading-page"><div class="spinner"></div></div>++ <div v-else-if="!directories.length" class="card">+ <div class="empty-state">+ <h3>No directories yet</h3>+ <p>Add your LDAP server or Active Directory domain controller, test the connection, then map groups to access.</p>+ <button v-if="license.mutable" class="btn btn-primary" @click="openEditor(null)">Add directory</button>+ </div>+ </div>++ <div v-for="dir in directories" v-else :key="dir.id" class="card ldap-card">+ <div class="card-header">+ <div class="ldap-title">+ <h2>{{ dir.display_name }}</h2>+ <span v-if="dir.enabled" class="badge badge-success">On</span>+ <span v-else class="badge badge-neutral">Off</span>+ <span class="badge badge-secondary">{{ dir.tls_mode }}</span>+ <span v-if="dir.insecure_skip_tls" class="badge badge-warning">Certificate not checked</span>+ </div>+ <div class="ldap-actions">+ <button class="btn btn-secondary btn-sm" :disabled="tests[dir.id] === 'running'" @click="test(dir)">+ {{ tests[dir.id] === 'running' ? 'Testing…' : 'Test connection' }}+ </button>+ <template v-if="license.mutable">+ <button class="btn btn-secondary btn-sm" @click="openEditor(dir)">Edit</button>+ <button class="btn btn-ghost btn-sm" @click="remove(dir)">Delete</button>+ </template>+ </div>+ </div>+ <div class="card-body">+ <div+ v-if="testOf(dir.id)"+ class="app-banner ldap-test"+ :class="testOf(dir.id)?.ok ? 'app-banner--success' : 'app-banner--danger'"+ role="status"+ >+ <div class="app-banner-content">+ <p class="app-banner-text">{{ testOf(dir.id)?.ok ? testOf(dir.id)?.message : testOf(dir.id)?.error }}</p>+ </div>+ </div>++ <dl class="ldap-facts">+ <dt>Server</dt>+ <dd><code>{{ dir.host }}:{{ dir.port }}</code></dd>+ <dt>Service account</dt>+ <dd>+ <code v-if="dir.bind_dn">{{ dir.bind_dn }}</code><span v-else class="muted">Anonymous</span>+ <span v-if="dir.bind_dn && !dir.bind_password_set" class="badge badge-warning">No password</span>+ </dd>+ <dt>Users</dt>+ <dd>+ <code>{{ dir.user_base_dn }}</code> · <code>{{ dir.user_filter || `(${dir.attr_email || 'mail'}=%s)` }}</code>+ </dd>+ <dt>Groups</dt>+ <dd>+ <template v-if="dir.group_base_dn || dir.group_filter">+ <code>{{ dir.group_base_dn || dir.user_base_dn }}</code> · <code>{{ dir.group_filter || '(member=%s)' }}</code>+ </template>+ <template v-else><code>{{ dir.member_attr || 'memberOf' }}</code> on the user</template>+ <span v-if="dir.nested_groups" class="muted"> · nested</span>+ </dd>+ </dl>++ <h3 class="ldap-subtitle">Group mappings</h3>+ <p class="muted ldap-help">+ Applied at every sign-in to accounts this directory created: members of a group become platform admins+ or join a workspace. Access a mapping does not govern is left as set by hand.+ </p>+ <div v-if="dir.mappings?.length" class="table-wrapper">+ <table>+ <thead>+ <tr>+ <th>Group</th>+ <th>Grants</th>+ <th v-if="license.mutable"></th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="m in dir.mappings" :key="m.id">+ <td><code>{{ m.group_dn }}</code></td>+ <td>{{ grants(m) }}</td>+ <td v-if="license.mutable" class="ldap-row-actions">+ <button class="btn btn-ghost btn-sm" @click="removeMapping(dir, m.id)">Remove</button>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ <p v-else class="muted ldap-help">No mappings: directory accounts sign in as plain users of their own workspace.</p>++ <div v-if="license.mutable" class="ldap-mapping-form">+ <input+ v-model="mappingDraft(dir.id).group_dn"+ class="form-input"+ placeholder="cn=posta-admins,ou=groups,dc=example,dc=com, or posta-admins"+ aria-label="Directory group"+ />+ <label class="checkbox-label">+ <input v-model="mappingDraft(dir.id).platform_admin" type="checkbox" /> Platform admin+ </label>+ <select v-model="mappingDraft(dir.id).workspace_id" class="form-select" aria-label="Workspace">+ <option value="">No workspace</option>+ <option v-for="w in workspaces" :key="w.id" :value="w.id">{{ w.name }}</option>+ </select>+ <select+ v-model="mappingDraft(dir.id).workspace_role"+ class="form-select"+ aria-label="Workspace role"+ :disabled="mappingDraft(dir.id).workspace_id === ''"+ >+ <option value="admin">Admin</option>+ <option value="editor">Editor</option>+ <option value="viewer">Viewer</option>+ </select>+ <button class="btn btn-primary" :disabled="!canAddMapping(dir.id)" @click="addMapping(dir)">Add mapping</button>+ </div>+ </div>+ </div>+ </EnterpriseLock>++ <div v-if="showEditor" class="modal-overlay" @click.self="showEditor = false">+ <div class="modal ldap-modal">+ <div class="modal-header">+ <h3>{{ editing ? `Edit ${editing.display_name}` : 'Add a directory' }}</h3>+ </div>+ <div class="modal-body">+ <h4 class="ldap-section">Connection</h4>+ <div class="ldap-grid">+ <div class="form-group">+ <label class="form-label" for="ldap-name">Name</label>+ <input id="ldap-name" v-model="draft.display_name" class="form-input" placeholder="Corporate AD" />+ </div>+ <div class="form-group">+ <label class="form-label" for="ldap-host">Host</label>+ <input id="ldap-host" v-model="draft.host" class="form-input" placeholder="ldap.example.com" />+ </div>+ <div class="form-group">+ <label class="form-label" for="ldap-tls">Encryption</label>+ <select id="ldap-tls" v-model="draft.tls_mode" class="form-select">+ <option value="starttls">StartTLS (port 389)</option>+ <option value="ldaps">LDAPS (port 636)</option>+ <option value="none">None: development only</option>+ </select>+ </div>+ <div class="form-group">+ <label class="form-label" for="ldap-port">Port</label>+ <input+ id="ldap-port"+ v-model.number="draft.port"+ type="number"+ min="1"+ max="65535"+ class="form-input"+ :placeholder="draft.tls_mode === 'ldaps' ? '636' : '389'"+ />+ </div>+ </div>+ <div class="form-group">+ <label class="form-label" for="ldap-ca">Private CA certificate <span class="muted">(optional, PEM)</span></label>+ <textarea id="ldap-ca" v-model="draft.ca_cert_pem" class="form-input ldap-mono" rows="3" spellcheck="false" />+ </div>+ <label class="checkbox-label">+ <input v-model="draft.insecure_skip_tls" type="checkbox" /> Don't check the server certificate+ <span class="muted">(testing only: anyone on the network could read passwords)</span>+ </label>++ <h4 class="ldap-section">Service account</h4>+ <p class="muted ldap-help">Searches for the person signing in. Leave empty to search anonymously.</p>+ <div class="ldap-grid">+ <div class="form-group">+ <label class="form-label" for="ldap-binddn">Bind DN</label>+ <input id="ldap-binddn" v-model="draft.bind_dn" class="form-input" placeholder="cn=posta,ou=services,dc=example,dc=com" />+ </div>+ <div class="form-group">+ <label class="form-label" for="ldap-bindpw">Password</label>+ <input+ id="ldap-bindpw"+ v-model="draft.bind_password"+ type="password"+ class="form-input"+ autocomplete="new-password"+ :placeholder="editing?.bind_password_set ? 'Stored: leave empty to keep' : ''"+ />+ </div>+ </div>++ <h4 class="ldap-section">Users</h4>+ <div class="ldap-grid">+ <div class="form-group">+ <label class="form-label" for="ldap-base">Base DN</label>+ <input id="ldap-base" v-model="draft.user_base_dn" class="form-input" placeholder="ou=people,dc=example,dc=com" />+ </div>+ <div class="form-group">+ <label class="form-label" for="ldap-filter">Filter <span class="muted">(%s is the email)</span></label>+ <input id="ldap-filter" v-model="draft.user_filter" class="form-input" placeholder="(mail=%s)" />+ </div>+ <div class="form-group">+ <label class="form-label" for="ldap-attr-email">Email attribute</label>+ <input id="ldap-attr-email" v-model="draft.attr_email" class="form-input" placeholder="mail" />+ </div>+ <div class="form-group">+ <label class="form-label" for="ldap-attr-name">Name attribute</label>+ <input id="ldap-attr-name" v-model="draft.attr_name" class="form-input" placeholder="displayName" />+ </div>+ </div>++ <h4 class="ldap-section">Groups</h4>+ <p class="muted ldap-help">+ By default Posta reads the user's <code>memberOf</code>. Set a group base DN or filter to search for+ groups instead.+ </p>+ <div class="ldap-grid">+ <div class="form-group">+ <label class="form-label" for="ldap-member">Member attribute</label>+ <input id="ldap-member" v-model="draft.member_attr" class="form-input" placeholder="memberOf" />+ </div>+ <div class="form-group">+ <label class="form-label" for="ldap-gbase">Group base DN</label>+ <input id="ldap-gbase" v-model="draft.group_base_dn" class="form-input" placeholder="ou=groups,dc=example,dc=com" />+ </div>+ <div class="form-group">+ <label class="form-label" for="ldap-gfilter">Group filter <span class="muted">(%s is the user's DN)</span></label>+ <input id="ldap-gfilter" v-model="draft.group_filter" class="form-input" placeholder="(member=%s)" />+ </div>+ </div>+ <label class="checkbox-label">+ <input v-model="draft.nested_groups" type="checkbox" /> Include nested groups (Active Directory)+ </label>+ <label class="checkbox-label">+ <input v-model="draft.enabled" type="checkbox" /> People can sign in through this directory+ </label>+ </div>+ <div class="modal-footer">+ <button class="btn btn-secondary" @click="showEditor = false">Cancel</button>+ <button class="btn btn-primary" :disabled="saving || !canSave" @click="save">+ {{ saving ? 'Saving…' : editing ? 'Save directory' : 'Add directory' }}+ </button>+ </div>+ </div>+ </div>+ </div>+</template>++<style scoped>+.ldap-modal {+ width: min(760px, calc(100vw - 32px));+ max-width: 760px;+}++.ldap-intro {+ margin: 4px 0 0;+ color: var(--text-muted);+ font-size: 13px;+ max-width: 640px;+}++.ldap-card {+ margin-bottom: 20px;+}++.ldap-title {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+}++.ldap-actions {+ display: flex;+ gap: 6px;+ flex-wrap: wrap;+}++.ldap-test {+ margin-bottom: 16px;+}++.ldap-facts {+ display: grid;+ grid-template-columns: max-content 1fr;+ gap: 8px 16px;+ margin: 0 0 20px;+ font-size: 14px;+}++.ldap-facts dt {+ color: var(--text-tertiary);+}++.ldap-facts dd {+ margin: 0;+ min-width: 0;+ overflow-wrap: anywhere;+}++.ldap-subtitle {+ margin: 0 0 4px;+ font-size: 15px;+}++.ldap-help {+ margin: 0 0 12px;+ font-size: 13px;+}++.ldap-mapping-form {+ display: grid;+ grid-template-columns: minmax(220px, 2fr) auto minmax(140px, 1fr) minmax(110px, auto) auto;+ gap: 8px;+ align-items: center;+ margin-top: 12px;+}++.ldap-row-actions {+ text-align: right;+}++.ldap-section {+ margin: 20px 0 8px;+ font-size: 14px;+}++.ldap-section:first-child {+ margin-top: 0;+}++.ldap-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));+ gap: 0 16px;+}++.ldap-mono {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12px;+}++@media (max-width: 900px) {+ .ldap-mapping-form {+ grid-template-columns: 1fr;+ }+}+</style>diff --git a/web/src/views/admin/License.vue b/web/src/views/admin/License.vueindex 757bc1c..8f67e49 100644--- a/web/src/views/admin/License.vue+++ b/web/src/views/admin/License.vue@@ -122,8 +122,8 @@ onMounted(load)<div><h1>License</h1><p class="page-description">- Posta Enterprise adds routing rules and teams, branching forms and encryption of personal data, on top- of everything in Posta Community.+ Posta Enterprise adds routing rules and teams, branching forms, encryption of personal data, LDAP /+ Active Directory sign-in and several OAuth providers, on top of everything in Posta Community.</p></div></div>diff --git a/web/src/views/admin/OAuthProviders.vue b/web/src/views/admin/OAuthProviders.vueindex 8b73a50..e13f083 100644--- a/web/src/views/admin/OAuthProviders.vue+++ b/web/src/views/admin/OAuthProviders.vue@@ -1,12 +1,19 @@<script setup lang="ts">-import { ref, onMounted } from 'vue'+import { computed, ref, onMounted } from 'vue'import { oauthApi } from '../../api/oauth'import type { OAuthProviderAdmin } from '../../api/types'import { useNotificationStore } from '../../stores/notification'import { useConfirm } from '../../composables/useConfirm'+import { useLicenseStore } from '../../stores/license'+import { ENTERPRISE_URL } from '../../api/license'const notify = useNotificationStore()const { confirm } = useConfirm()+const license = useLicenseStore()++// Posta Community configures one OAuth provider; more need Enterprise.+const COMMUNITY_PROVIDERS = 1+const atCommunityLimit = computed(() => !license.mutable && providers.value.length >= COMMUNITY_PROVIDERS)const providers = ref<OAuthProviderAdmin[]>([])const loading = ref(true)@@ -131,14 +138,35 @@ function formatDate(d: string) {return new Date(d).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}-onMounted(fetchProviders)+onMounted(() => {+ license.load()+ fetchProviders()+})</script><template><div><div class="page-header"><h1>OAuth Providers</h1>- <button class="btn btn-primary" @click="showCreateModal = true">Add Provider</button>+ <button+ class="btn btn-primary"+ :disabled="atCommunityLimit"+ :title="atCommunityLimit ? 'More than one provider needs Posta Enterprise' : undefined"+ @click="showCreateModal = true"+ >+ Add Provider+ </button>+ </div>++ <div v-if="!loading && atCommunityLimit" class="app-banner app-banner--info oauth-limit" role="status">+ <div class="app-banner-content">+ <p class="app-banner-text">+ Posta Community signs in through one OAuth provider. Several providers, and LDAP / Active Directory,+ come with <span class="ee-badge">Enterprise</span>.+ <router-link to="/admin/license">Install a license</router-link> ·+ <a :href="ENTERPRISE_URL" target="_blank" rel="noopener noreferrer">About Posta Enterprise</a>+ </p>+ </div></div><div v-if="loading" class="loading-page"><div class="spinner"></div></div>@@ -309,3 +337,9 @@ onMounted(fetchProviders)</div></div></template>++<style scoped>+.oauth-limit {+ margin-bottom: 16px;+}+</style>