Skip to content
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

[feat] Add X-Remote-User header #135

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .tmuxinator.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ windows:
- database:
root: ./
panes:
- pgcli postgres://taskcafe:taskcafe_test@localhost:8855/taskcafe
- pgcli postgres://taskcafe:taskcafe_test@localhost:8865/taskcafe
1 change: 1 addition & 0 deletions conf/taskcafe.example.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
[server]
hostname = '0.0.0.0:3333'
remote_user_header = ""

[email_notifications]
enabled = true
Expand Down
9 changes: 9 additions & 0 deletions docs/remote-auth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Remote authorize
If you need to authenticate user with some proxy, you should use
```toml
[server]
remote_user_header = "X-Remote-User"
```
With this option Taskcafe will take username from
`X-Remote-User` HTTP header and will not check its password.
You can use any header you want.
1 change: 1 addition & 0 deletions internal/commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ func Execute() {
viper.SetDefault("database.password", "taskcafe_test")
viper.SetDefault("database.port", "5432")
viper.SetDefault("security.token_expiration", "15m")
viper.SetDefault("server.remote_user_header", "")

viper.SetDefault("queue.broker", "amqp://guest:guest@localhost:5672/")
viper.SetDefault("queue.store", "memcache://localhost:11211")
Expand Down
25 changes: 17 additions & 8 deletions internal/commands/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,24 @@ func newWebCmd() *cobra.Command {
log.Warn("server.secret is not set, generating a random secret")
secret = uuid.New().String()
}

security, err := utils.GetSecurityConfig(viper.GetString("security.token_expiration"), []byte(secret))
r, _ := route.NewRouter(db, utils.EmailConfig{
From: viper.GetString("smtp.from"),
Host: viper.GetString("smtp.host"),
Port: viper.GetInt("smtp.port"),
Username: viper.GetString("smtp.username"),
Password: viper.GetString("smtp.password"),
InsecureSkipVerify: viper.GetBool("smtp.skip_verify"),
}, security)
if err != nil {
log.Error(err)
}
security.UserAuthHeader = viper.GetString("server.remote_user_header")

r, _ := route.NewRouter(db, route.Config{
Email: utils.EmailConfig{
From: viper.GetString("smtp.from"),
Host: viper.GetString("smtp.host"),
Port: viper.GetInt("smtp.port"),
Username: viper.GetString("smtp.username"),
Password: viper.GetString("smtp.password"),
InsecureSkipVerify: viper.GetBool("smtp.skip_verify"),
},
Security: security,
})
log.WithFields(log.Fields{"url": viper.GetString("server.hostname")}).Info("starting server")
return http.ListenAndServe(viper.GetString("server.hostname"), r)
},
Expand Down
47 changes: 47 additions & 0 deletions internal/route/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,15 @@ func (h *TaskcafeHandler) LogoutHandler(w http.ResponseWriter, r *http.Request)

// LoginHandler creates a new refresh & access token for the user if given the correct credentials
func (h *TaskcafeHandler) LoginHandler(w http.ResponseWriter, r *http.Request) {
if h.SecurityConfig.IsRemoteAuth() {
h.headerAuthenticate(w, r)
return
}

h.credentialsHandler(w, r)
}

func (h *TaskcafeHandler) credentialsHandler(w http.ResponseWriter, r *http.Request) {
var requestData LoginRequestData
err := json.NewDecoder(r.Body).Decode(&requestData)
if err != nil {
Expand Down Expand Up @@ -139,9 +148,47 @@ func (h *TaskcafeHandler) LoginHandler(w http.ResponseWriter, r *http.Request) {
authCreatedAt := time.Now().UTC()
authExpiresAt := authCreatedAt.AddDate(0, 0, 1)
authToken, err := h.repo.CreateAuthToken(r.Context(), db.CreateAuthTokenParams{user.UserID, authCreatedAt, authExpiresAt})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
// TODO: should we return here?
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JordanKnott is this a feature?

Copy link
Owner

@JordanKnott JordanKnott Oct 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you're talking about not returning early on an error, it is not

}

w.Header().Set("Content-type", "application/json")
http.SetCookie(w, &http.Cookie{
Name: "authToken",
Value: authToken.TokenID.String(),
Expires: authExpiresAt,
Path: "/",
HttpOnly: true,
})
json.NewEncoder(w).Encode(LoginResponseData{Complete: true, UserID: authToken.UserID.String()})
}

func (h *TaskcafeHandler) headerAuthenticate(w http.ResponseWriter, r *http.Request) {
xRemoteUser := r.Header.Get(h.SecurityConfig.UserAuthHeader)
user, err := h.repo.GetUserAccountByUsername(r.Context(), xRemoteUser)
if err != nil {
log.WithFields(log.Fields{
"username": xRemoteUser,
}).Warn("user account not found")
w.WriteHeader(http.StatusUnauthorized)
return
}

if !user.Active {
log.WithFields(log.Fields{
"username": user.Username,
}).Warn("attempt to login with inactive user")
w.WriteHeader(http.StatusUnauthorized)
return
}

authCreatedAt := time.Now().UTC()
authExpiresAt := authCreatedAt.AddDate(0, 0, 1)
authToken, err := h.repo.CreateAuthToken(r.Context(), db.CreateAuthTokenParams{user.UserID, authCreatedAt, authExpiresAt})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}

w.Header().Set("Content-type", "application/json")
Expand Down
11 changes: 8 additions & 3 deletions internal/route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,13 @@ type TaskcafeHandler struct {
SecurityConfig utils.SecurityConfig
}

type Config struct {
Email utils.EmailConfig
Security utils.SecurityConfig
}

// NewRouter creates a new router for chi
func NewRouter(dbConnection *sqlx.DB, emailConfig utils.EmailConfig, securityConfig utils.SecurityConfig) (chi.Router, error) {
func NewRouter(dbConnection *sqlx.DB, cfg Config) (chi.Router, error) {
formatter := new(log.TextFormatter)
formatter.TimestampFormat = "02-01-2006 15:04:05"
formatter.FullTimestamp = true
Expand All @@ -93,7 +98,7 @@ func NewRouter(dbConnection *sqlx.DB, emailConfig utils.EmailConfig, securityCon
}))

repository := db.NewRepository(dbConnection)
taskcafeHandler := TaskcafeHandler{*repository, securityConfig}
taskcafeHandler := TaskcafeHandler{*repository, cfg.Security}

var imgServer = http.FileServer(http.Dir("./uploads/"))
r.Group(func(mux chi.Router) {
Expand All @@ -108,7 +113,7 @@ func NewRouter(dbConnection *sqlx.DB, emailConfig utils.EmailConfig, securityCon
r.Group(func(mux chi.Router) {
mux.Use(auth.Middleware)
mux.Post("/users/me/avatar", taskcafeHandler.ProfileImageUpload)
mux.Handle("/graphql", graph.NewHandler(*repository, emailConfig))
mux.Handle("/graphql", graph.NewHandler(*repository, cfg.Email))
})

frontend := FrontendHandler{staticPath: "build", indexPath: "index.html"}
Expand Down
5 changes: 5 additions & 0 deletions internal/utils/security.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ import (
type SecurityConfig struct {
AccessTokenExpiration time.Duration
Secret []byte
UserAuthHeader string
}

func (c SecurityConfig) IsRemoteAuth() bool {
return c.UserAuthHeader != ""
}

func GetSecurityConfig(accessTokenExp string, secret []byte) (SecurityConfig, error) {
Expand Down