outpost: migrate to openapitools/openapi-generator-cli

Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
This commit is contained in:
Jens Langhammer
2021-05-16 21:07:01 +02:00
parent 8b6292b3de
commit a5233f89b2
19 changed files with 218 additions and 234 deletions

View File

@ -1,6 +1,7 @@
package ldap
import (
"context"
"errors"
"fmt"
"net/http"
@ -9,28 +10,27 @@ import (
"github.com/go-openapi/strfmt"
log "github.com/sirupsen/logrus"
"goauthentik.io/outpost/pkg/client/outposts"
)
func (ls *LDAPServer) Refresh() error {
outposts, err := ls.ac.Client.Outposts.OutpostsLdapList(outposts.NewOutpostsLdapListParams(), ls.ac.Auth)
outposts, _, err := ls.ac.Client.OutpostsApi.OutpostsLdapListExecute(ls.ac.Client.OutpostsApi.OutpostsLdapList(context.Background()))
if err != nil {
return err
}
if len(outposts.Payload.Results) < 1 {
if len(outposts.Results) < 1 {
return errors.New("no ldap provider defined")
}
providers := make([]*ProviderInstance, len(outposts.Payload.Results))
for idx, provider := range outposts.Payload.Results {
userDN := strings.ToLower(fmt.Sprintf("ou=users,%s", provider.BaseDn))
groupDN := strings.ToLower(fmt.Sprintf("ou=groups,%s", provider.BaseDn))
providers := make([]*ProviderInstance, len(outposts.Results))
for idx, provider := range outposts.Results {
userDN := strings.ToLower(fmt.Sprintf("ou=users,%s", *provider.BaseDn))
groupDN := strings.ToLower(fmt.Sprintf("ou=groups,%s", *provider.BaseDn))
providers[idx] = &ProviderInstance{
BaseDN: provider.BaseDn,
BaseDN: *provider.BaseDn,
GroupDN: groupDN,
UserDN: userDN,
appSlug: *provider.ApplicationSlug,
flowSlug: *provider.BindFlowSlug,
searchAllowedGroups: []*strfmt.UUID{provider.SearchGroup},
appSlug: provider.ApplicationSlug,
flowSlug: provider.BindFlowSlug,
searchAllowedGroups: []*strfmt.UUID{(*strfmt.UUID)(provider.SearchGroup.Get())},
boundUsersMutex: sync.RWMutex{},
boundUsers: make(map[string]UserFlags),
s: ls,
@ -55,14 +55,18 @@ func (ls *LDAPServer) Start() error {
type transport struct {
headers map[string]string
inner http.RoundTripper
}
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
for key, value := range t.headers {
req.Header.Add(key, value)
}
return http.DefaultTransport.RoundTrip(req)
return t.inner.RoundTrip(req)
}
func newTransport(headers map[string]string) *transport {
return &transport{headers}
func newTransport(inner http.RoundTripper, headers map[string]string) *transport {
return &transport{
inner: inner,
headers: headers,
}
}

View File

@ -12,23 +12,14 @@ import (
"time"
goldap "github.com/go-ldap/ldap/v3"
httptransport "github.com/go-openapi/runtime/client"
"github.com/nmcclain/ldap"
"goauthentik.io/outpost/pkg/client/core"
"goauthentik.io/outpost/pkg/client/flows"
"goauthentik.io/outpost/pkg/models"
"goauthentik.io/outpost/api"
"goauthentik.io/outpost/pkg"
"goauthentik.io/outpost/pkg/ak"
)
const ContextUserKey = "ak_user"
type UIDResponse struct {
UIDFIeld string `json:"uid_field"`
}
type PasswordResponse struct {
Password string `json:"password"`
}
func (pi *ProviderInstance) getUsername(dn string) (string, error) {
if !strings.HasSuffix(strings.ToLower(dn), strings.ToLower(pi.BaseDN)) {
return "", errors.New("invalid base DN")
@ -58,16 +49,25 @@ func (pi *ProviderInstance) Bind(username string, bindDN, bindPW string, conn ne
pi.log.WithError(err).Warning("Failed to get remote IP")
return ldap.LDAPResultOperationsError, nil
}
// Create new http client that also sets the correct ip
client := &http.Client{
config := api.NewConfiguration()
// Carry over the bearer authentication, so that failed login attempts are attributed to the outpost
config.DefaultHeader = pi.s.ac.Client.GetConfig().DefaultHeader
config.Host = pi.s.ac.Client.GetConfig().Host
config.Scheme = pi.s.ac.Client.GetConfig().Scheme
config.HTTPClient = &http.Client{
Jar: jar,
Transport: newTransport(map[string]string{
Transport: newTransport(ak.SetUserAgent(ak.GetTLSTransport(), pkg.UserAgent()), map[string]string{
"X-authentik-remote-ip": host,
}),
}
// create the API client, with the transport
apiClient := api.NewAPIClient(config)
params := url.Values{}
params.Add("goauthentik.io/outpost/ldap", "true")
passed, err := pi.solveFlowChallenge(username, bindPW, client, params.Encode(), 1)
passed, err := pi.solveFlowChallenge(username, bindPW, apiClient, params.Encode(), 1)
if err != nil {
pi.log.WithField("bindDN", bindDN).WithError(err).Warning("failed to solve challenge")
return ldap.LDAPResultOperationsError, nil
@ -75,33 +75,26 @@ func (pi *ProviderInstance) Bind(username string, bindDN, bindPW string, conn ne
if !passed {
return ldap.LDAPResultInvalidCredentials, nil
}
_, err = pi.s.ac.Client.Core.CoreApplicationsCheckAccess(&core.CoreApplicationsCheckAccessParams{
Slug: pi.appSlug,
Context: context.Background(),
HTTPClient: client,
}, httptransport.PassThroughAuth)
r, err := pi.s.ac.Client.CoreApi.CoreApplicationsCheckAccessRetrieve(context.Background(), pi.appSlug).Execute()
if r.StatusCode == 403 {
pi.log.WithField("bindDN", bindDN).Info("Access denied for user")
return ldap.LDAPResultInsufficientAccessRights, nil
}
if err != nil {
if _, denied := err.(*core.CoreApplicationsCheckAccessForbidden); denied {
pi.log.WithField("bindDN", bindDN).Info("Access denied for user")
return ldap.LDAPResultInsufficientAccessRights, nil
}
pi.log.WithField("bindDN", bindDN).WithError(err).Warning("failed to check access")
return ldap.LDAPResultOperationsError, nil
}
pi.log.WithField("bindDN", bindDN).Info("User has access")
// Get user info to store in context
userInfo, err := pi.s.ac.Client.Core.CoreUsersMe(&core.CoreUsersMeParams{
Context: context.Background(),
HTTPClient: client,
}, httptransport.PassThroughAuth)
userInfo, _, err := pi.s.ac.Client.CoreApi.CoreUsersMeRetrieve(context.Background()).Execute()
if err != nil {
pi.log.WithField("bindDN", bindDN).WithError(err).Warning("failed to get user info")
return ldap.LDAPResultOperationsError, nil
}
pi.boundUsersMutex.Lock()
pi.boundUsers[bindDN] = UserFlags{
UserInfo: *userInfo.Payload.User,
CanSearch: pi.SearchAccessCheck(userInfo.Payload.User),
UserInfo: userInfo.User,
CanSearch: pi.SearchAccessCheck(userInfo.User),
}
defer pi.boundUsersMutex.Unlock()
pi.delayDeleteUserInfo(username)
@ -109,11 +102,11 @@ func (pi *ProviderInstance) Bind(username string, bindDN, bindPW string, conn ne
}
// SearchAccessCheck Check if the current user is allowed to search
func (pi *ProviderInstance) SearchAccessCheck(user *models.User) bool {
func (pi *ProviderInstance) SearchAccessCheck(user api.User) bool {
for _, group := range user.Groups {
for _, allowedGroup := range pi.searchAllowedGroups {
pi.log.WithField("userGroup", group.Pk).WithField("allowedGroup", allowedGroup).Trace("Checking search access")
if group.Pk.String() == allowedGroup.String() {
if group.Pk == allowedGroup.String() {
pi.log.WithField("group", group.Name).Info("Allowed access to search")
return true
}
@ -140,51 +133,48 @@ func (pi *ProviderInstance) delayDeleteUserInfo(dn string) {
}()
}
func (pi *ProviderInstance) solveFlowChallenge(bindDN string, password string, client *http.Client, urlParams string, depth int) (bool, error) {
challenge, err := pi.s.ac.Client.Flows.FlowsExecutorGet(&flows.FlowsExecutorGetParams{
FlowSlug: pi.flowSlug,
Query: urlParams,
Context: context.Background(),
HTTPClient: client,
}, pi.s.ac.Auth)
func (pi *ProviderInstance) solveFlowChallenge(bindDN string, password string, client *api.APIClient, urlParams string, depth int) (bool, error) {
req := client.FlowsApi.FlowsExecutorGet(context.Background(), pi.flowSlug)
req.Query(urlParams)
challenge, _, err := req.Execute()
if err != nil {
pi.log.WithError(err).Warning("Failed to get challenge")
return false, err
}
pi.log.WithField("component", challenge.Payload.Component).WithField("type", *challenge.Payload.Type).Debug("Got challenge")
responseParams := &flows.FlowsExecutorSolveParams{
FlowSlug: pi.flowSlug,
Query: urlParams,
Context: context.Background(),
HTTPClient: client,
}
switch challenge.Payload.Component {
pi.log.WithField("component", challenge.Component).WithField("type", challenge.Type).Debug("Got challenge")
responseReq := client.FlowsApi.FlowsExecutorSolve(context.Background(), pi.flowSlug)
responseReq.Query(urlParams)
switch *challenge.Component {
case "ak-stage-identification":
responseParams.Data = &UIDResponse{UIDFIeld: bindDN}
responseReq.RequestBody(map[string]interface{}{
"uid_field": bindDN,
})
case "ak-stage-password":
responseParams.Data = &PasswordResponse{Password: password}
responseReq.RequestBody(map[string]interface{}{
"password": password,
})
case "ak-stage-access-denied":
return false, errors.New("got ak-stage-access-denied")
default:
return false, fmt.Errorf("unsupported challenge type: %s", challenge.Payload.Component)
return false, fmt.Errorf("unsupported challenge type: %s", *challenge.Component)
}
response, err := pi.s.ac.Client.Flows.FlowsExecutorSolve(responseParams, pi.s.ac.Auth)
pi.log.WithField("component", response.Payload.Component).WithField("type", *response.Payload.Type).Debug("Got response")
switch response.Payload.Component {
response, _, err := responseReq.Execute()
pi.log.WithField("component", response.Component).WithField("type", response.Type).Debug("Got response")
switch *response.Component {
case "ak-stage-access-denied":
return false, errors.New("got ak-stage-access-denied")
}
if *response.Payload.Type == "redirect" {
if response.Type == "redirect" {
return true, nil
}
if err != nil {
pi.log.WithError(err).Warning("Failed to submit challenge")
return false, err
}
if len(response.Payload.ResponseErrors) > 0 {
for key, errs := range response.Payload.ResponseErrors {
if len(*response.ResponseErrors) > 0 {
for key, errs := range *response.ResponseErrors {
for _, err := range errs {
pi.log.WithField("key", key).WithField("code", *err.Code).Debug(*err.String)
pi.log.WithField("key", key).WithField("code", err.Code).Debug(err.String)
return false, nil
}
}

View File

@ -1,13 +1,13 @@
package ldap
import (
"context"
"errors"
"fmt"
"net"
"strings"
"github.com/nmcclain/ldap"
"goauthentik.io/outpost/pkg/client/core"
)
func (pi *ProviderInstance) Search(bindDN string, searchReq ldap.SearchRequest, conn net.Conn) (ldap.ServerSearchResult, error) {
@ -43,16 +43,16 @@ func (pi *ProviderInstance) Search(bindDN string, searchReq ldap.SearchRequest,
default:
return ldap.ServerSearchResult{ResultCode: ldap.LDAPResultOperationsError}, fmt.Errorf("Search Error: unhandled filter type: %s [%s]", filterEntity, searchReq.Filter)
case GroupObjectClass:
groups, err := pi.s.ac.Client.Core.CoreGroupsList(core.NewCoreGroupsListParams(), pi.s.ac.Auth)
groups, _, err := pi.s.ac.Client.CoreApi.CoreGroupsListExecute(pi.s.ac.Client.CoreApi.CoreGroupsList(context.Background()))
if err != nil {
return ldap.ServerSearchResult{ResultCode: ldap.LDAPResultOperationsError}, fmt.Errorf("API Error: %s", err)
}
pi.log.WithField("count", len(groups.Payload.Results)).Trace("Got results from API")
for _, g := range groups.Payload.Results {
pi.log.WithField("count", len(groups.Results)).Trace("Got results from API")
for _, g := range groups.Results {
attrs := []*ldap.EntryAttribute{
{
Name: "cn",
Values: []string{*g.Name},
Values: []string{g.Name},
},
{
Name: "uid",
@ -69,31 +69,31 @@ func (pi *ProviderInstance) Search(bindDN string, searchReq ldap.SearchRequest,
entries = append(entries, &ldap.Entry{DN: dn, Attributes: attrs})
}
case UserObjectClass, "":
users, err := pi.s.ac.Client.Core.CoreUsersList(core.NewCoreUsersListParams(), pi.s.ac.Auth)
users, _, err := pi.s.ac.Client.CoreApi.CoreUsersListExecute(pi.s.ac.Client.CoreApi.CoreUsersList(context.Background()))
if err != nil {
return ldap.ServerSearchResult{ResultCode: ldap.LDAPResultOperationsError}, fmt.Errorf("API Error: %s", err)
}
for _, u := range users.Payload.Results {
for _, u := range users.Results {
attrs := []*ldap.EntryAttribute{
{
Name: "cn",
Values: []string{*u.Username},
Values: []string{u.Username},
},
{
Name: "uid",
Values: []string{u.UID},
Values: []string{u.Uid},
},
{
Name: "name",
Values: []string{*u.Name},
Values: []string{u.Name},
},
{
Name: "displayName",
Values: []string{*u.Name},
Values: []string{u.Name},
},
{
Name: "mail",
Values: []string{u.Email.String()},
Values: []string{*u.Email},
},
{
Name: "objectClass",
@ -101,13 +101,13 @@ func (pi *ProviderInstance) Search(bindDN string, searchReq ldap.SearchRequest,
},
}
if u.IsActive {
if *u.IsActive {
attrs = append(attrs, &ldap.EntryAttribute{Name: "accountStatus", Values: []string{"inactive"}})
} else {
attrs = append(attrs, &ldap.EntryAttribute{Name: "accountStatus", Values: []string{"active"}})
}
if *u.IsSuperuser {
if u.IsSuperuser {
attrs = append(attrs, &ldap.EntryAttribute{Name: "superuser", Values: []string{"inactive"}})
} else {
attrs = append(attrs, &ldap.EntryAttribute{Name: "superuser", Values: []string{"active"}})
@ -117,7 +117,7 @@ func (pi *ProviderInstance) Search(bindDN string, searchReq ldap.SearchRequest,
attrs = append(attrs, AKAttrsToLDAP(u.Attributes)...)
dn := fmt.Sprintf("cn=%s,%s", *u.Username, pi.UserDN)
dn := fmt.Sprintf("cn=%s,%s", u.Username, pi.UserDN)
entries = append(entries, &ldap.Entry{DN: dn, Attributes: attrs})
}
}

View File

@ -5,8 +5,8 @@ import (
"github.com/go-openapi/strfmt"
log "github.com/sirupsen/logrus"
"goauthentik.io/outpost/api"
"goauthentik.io/outpost/pkg/ak"
"goauthentik.io/outpost/pkg/models"
"github.com/nmcclain/ldap"
)
@ -31,7 +31,7 @@ type ProviderInstance struct {
}
type UserFlags struct {
UserInfo models.User
UserInfo api.User
CanSearch bool
}

View File

@ -4,7 +4,7 @@ import (
"fmt"
"github.com/nmcclain/ldap"
"goauthentik.io/outpost/pkg/models"
"goauthentik.io/outpost/api"
)
func AKAttrsToLDAP(attrs interface{}) []*ldap.EntryAttribute {
@ -22,7 +22,7 @@ func AKAttrsToLDAP(attrs interface{}) []*ldap.EntryAttribute {
return attrList
}
func (pi *ProviderInstance) GroupsForUser(user *models.User) []string {
func (pi *ProviderInstance) GroupsForUser(user api.User) []string {
groups := make([]string, len(user.Groups))
for i, group := range user.Groups {
groups[i] = pi.GetGroupDN(group)
@ -30,6 +30,6 @@ func (pi *ProviderInstance) GroupsForUser(user *models.User) []string {
return groups
}
func (pi *ProviderInstance) GetGroupDN(group *models.Group) string {
return fmt.Sprintf("cn=%s,%s", *group.Name, pi.GroupDN)
func (pi *ProviderInstance) GetGroupDN(group api.Group) string {
return fmt.Sprintf("cn=%s,%s", group.Name, pi.GroupDN)
}