-
Notifications
You must be signed in to change notification settings - Fork 0
Gateway with ldap authentication #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jk4102
wants to merge
12
commits into
main
Choose a base branch
from
feat/ldap-auth
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
621a86f
setting up ldap with sample user data - authentication, no authorizat…
jk4102 3936bff
Merge branch 'main' into feat/ldap-auth
jk4102 5e239f6
ldap authentication works in cluster
jk4102 9b4f7c9
authorize against env var user list
jk4102 e241e2f
setting allowed users env
jk4102 ab049f2
allowed users proto
jk4102 d7d40dd
remove unused
jk4102 921e06a
clean up
jk4102 bec5b16
clean up
jk4102 4fbb551
clean up
jk4102 9ebc728
comments
jk4102 2a95fb4
rename
jk4102 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,204 @@ | ||
| /* | ||
| Copyright 2024 BlackRock, Inc. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
|
|
||
| package auth | ||
|
|
||
| import ( | ||
| "crypto/tls" | ||
| "encoding/base64" | ||
| "fmt" | ||
| "net/http" | ||
| "strings" | ||
|
|
||
| "github.com/go-ldap/ldap/v3" | ||
| "github.com/tinymultiverse/tinyapp/gateway/internal" | ||
| "go.uber.org/zap" | ||
| ) | ||
|
|
||
| type LDAPAuthNZ struct { | ||
| config internal.EnvVars | ||
| } | ||
|
|
||
| func NewLDAPAuthNZ(config internal.EnvVars) *LDAPAuthNZ { | ||
| return &LDAPAuthNZ{ | ||
| config: config, | ||
| } | ||
| } | ||
|
|
||
| // Authenticate performs LDAP authentication | ||
| func (la *LDAPAuthNZ) Authenticate(req *http.Request) (string, error) { | ||
| if !la.config.LdapEnabled { | ||
| return "", nil | ||
| } | ||
|
|
||
| username, password, err := extractCredentials(req) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| return la.authenticateLDAP(username, password) | ||
| } | ||
|
|
||
| // AuthorizeUser checks if the authenticated user is in the allowed users list | ||
| func (la *LDAPAuthNZ) AuthorizeUser(username string) error { | ||
| return la.authorizeUser(username) | ||
| } | ||
|
|
||
| func extractCredentials(req *http.Request) (string, string, error) { | ||
| authHeader := req.Header.Get("Authorization") | ||
| if authHeader == "" { | ||
| return "", "", fmt.Errorf("missing Authorization header") | ||
| } | ||
|
|
||
| if !strings.HasPrefix(authHeader, "Basic ") { | ||
| return "", "", fmt.Errorf("unsupported authorization type") | ||
| } | ||
|
|
||
| encoded := strings.TrimPrefix(authHeader, "Basic ") | ||
| decoded, err := base64.StdEncoding.DecodeString(encoded) | ||
| if err != nil { | ||
| return "", "", fmt.Errorf("invalid base64 encoding: %w", err) | ||
| } | ||
|
|
||
| credentials := strings.SplitN(string(decoded), ":", 2) | ||
| if len(credentials) != 2 { | ||
| return "", "", fmt.Errorf("invalid credentials format") | ||
| } | ||
|
|
||
| return credentials[0], credentials[1], nil | ||
| } | ||
|
|
||
| // authenticateLDAP performs LDAP authentication | ||
| func (la *LDAPAuthNZ) authenticateLDAP(username, password string) (string, error) { | ||
| conn, err := la.connectLDAP() | ||
| if err != nil { | ||
| return "", fmt.Errorf("failed to connect to LDAP server: %w", err) | ||
| } | ||
| defer conn.Close() | ||
|
|
||
| if la.config.LdapBindDN != "" { | ||
| err = conn.Bind(la.config.LdapBindDN, la.config.LdapBindPassword) | ||
| if err != nil { | ||
| return "", fmt.Errorf("LDAP service account bind failed") | ||
| } | ||
| } | ||
|
|
||
| userDN, err := la.searchUser(conn, username) | ||
| if err != nil { | ||
| return username, fmt.Errorf("user search failed: %w", err) | ||
| } | ||
|
|
||
| // Authenticate user by binding with their credentials | ||
| err = conn.Bind(userDN, password) | ||
| if err != nil { | ||
| return username, fmt.Errorf("authentication failed") | ||
| } | ||
|
|
||
| zap.S().Infow("user authenticated successfully", "username", username) | ||
| return username, nil | ||
| } | ||
|
|
||
| // connectLDAP establishes connection to LDAP server | ||
| func (la *LDAPAuthNZ) connectLDAP() (*ldap.Conn, error) { | ||
| var scheme string | ||
| if la.config.LdapTLS { | ||
| scheme = "ldaps" | ||
| } else { | ||
| scheme = "ldap" | ||
| } | ||
|
|
||
| ldapURL := fmt.Sprintf("%s://%s:%d", scheme, la.config.LdapServer, la.config.LdapPort) | ||
|
|
||
| var conn *ldap.Conn | ||
| var err error | ||
|
|
||
| if la.config.LdapTLS { | ||
| tlsConfig := &tls.Config{ | ||
| ServerName: la.config.LdapServer, | ||
| } | ||
| conn, err = ldap.DialURL(ldapURL, ldap.DialWithTLSConfig(tlsConfig)) | ||
| } else { | ||
| conn, err = ldap.DialURL(ldapURL) | ||
| } | ||
|
|
||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| return conn, nil | ||
| } | ||
|
|
||
| // searchUser searches for user in LDAP directory | ||
| func (la *LDAPAuthNZ) searchUser(conn *ldap.Conn, username string) (string, error) { | ||
| filter := fmt.Sprintf("(&(%s=%s)%s)", | ||
| la.config.LdapUserAttribute, | ||
| ldap.EscapeFilter(username), | ||
| la.config.LdapUserFilter) | ||
|
|
||
| searchRequest := ldap.NewSearchRequest( | ||
| la.config.LdapBaseDN, | ||
| ldap.ScopeWholeSubtree, | ||
| ldap.NeverDerefAliases, | ||
| la.config.LdapSearchSizeLimit, | ||
| la.config.LdapSearchTimeLimit, | ||
| false, | ||
| filter, | ||
| la.config.LdapReturnAttributes, | ||
| nil, | ||
| ) | ||
|
|
||
| result, err := conn.Search(searchRequest) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| if len(result.Entries) == 0 { | ||
| return "", fmt.Errorf("user not found") | ||
| } | ||
|
|
||
| if len(result.Entries) > 1 { | ||
| return "", fmt.Errorf("multiple users found") | ||
| } | ||
|
|
||
| return result.Entries[0].DN, nil | ||
| } | ||
|
|
||
| // RequireAuth is a middleware that sends 401 with WWW-Authenticate header | ||
| func (la *LDAPAuthNZ) RequireAuth(w http.ResponseWriter) { | ||
| w.Header().Set("WWW-Authenticate", `Basic realm="LDAP Authentication"`) | ||
| w.WriteHeader(http.StatusUnauthorized) | ||
| w.Write([]byte("Unauthorized")) | ||
| } | ||
|
|
||
| // authorizeUser checks if the authenticated user is in the allowed users list | ||
| func (la *LDAPAuthNZ) authorizeUser(username string) error { | ||
| if !la.config.AuthorizationEnabled { | ||
| return nil | ||
| } | ||
|
|
||
| if len(la.config.AllowedUsers) == 0 { | ||
| return nil | ||
| } | ||
|
|
||
| for _, allowedUser := range la.config.AllowedUsers { | ||
| if strings.TrimSpace(allowedUser) == username { | ||
| zap.S().Debugw("user authorized", "username", username) | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| return fmt.Errorf("user not authorized") | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we keep connection open globally (check concurrency support)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
same as jupyterlab version - concurrency not built in