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

WIP Topic/support nginx auth request #43

Closed
wants to merge 3 commits into from
Closed
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
9 changes: 6 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,19 @@ EXECUTEABLE := whawty-auth
all: build
.PHONY: vet format ui build clean distclean

format:
$(GOCMD) fmt ./...

vet:
$(GOCMD) vet ./...

format:
$(GOCMD) fmt ./...
test: vet
$(GOCMD) test ./...

ui:
$(GOCMD) generate ./ui

build: ui
build: test ui
$(GOCMD) build -o $(EXECUTEABLE) ./cmd/whawty-auth

dev:
Expand Down
51 changes: 49 additions & 2 deletions cmd/whawty-auth/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -367,14 +367,43 @@ func cmdRun(c *cli.Context) error {

webAddrs := c.StringSlice("web-addr")
saslPaths := c.StringSlice("sock")
ssoAuthAddrs := c.StringSlice("sso-auth-addr")
ssoLoginAddrs := c.StringSlice("sso-login-addr")

var wg sync.WaitGroup
var sessions *webSessionFactory
if len(ssoAuthAddrs) > 0 || len(ssoLoginAddrs) > 0 || len(webAddrs) > 0 {
var err error
if sessions, err = NewWebSessionFactory(600 * time.Second); err != nil { // TODO: hardcoded value
return err
}
}
for _, ssoAuth := range ssoAuthAddrs {
a := ssoAuth
wg.Add(1)
go func() {
defer wg.Done()
if err := runSSOAuthAddr(a, s.GetInterface(), sessions); err != nil {
fmt.Printf("warning running sso login interface(%s) failed: %s\n", a, err)
}
}()
}
for _, ssoLogin := range ssoLoginAddrs {
a := ssoLogin
wg.Add(1)
go func() {
defer wg.Done()
if err := runSSOLoginAddr(a, s.GetInterface(), sessions); err != nil {
fmt.Printf("warning running sso auth interface(%s) failed: %s\n", a, err)
}
}()
}
for _, webAddr := range webAddrs {
a := webAddr
wg.Add(1)
go func() {
defer wg.Done()
if err := runWebAddr(a, s.GetInterface()); err != nil {
if err := runWebAddr(a, s.GetInterface(), sessions); err != nil {
fmt.Printf("warning running web interface(%s) failed: %s\n", a, err)
}
}()
Expand Down Expand Up @@ -411,6 +440,7 @@ func cmdRunSa(c *cli.Context) error {
}

var wg sync.WaitGroup
var sessions *webSessionFactory
for idx, listener := range listeners {
switch listener.(type) {
case *net.UnixListener:
Expand All @@ -425,11 +455,18 @@ func cmdRunSa(c *cli.Context) error {
}()
case *net.TCPListener:
fmt.Printf("listener[%d]: is a TCP socket (-> HTTP)\n", idx)
if sessions == nil {
sessions, err = NewWebSessionFactory(10 * time.Minute) // TODO
if err != nil {
fmt.Printf("warning: running web-api failed: web session factory failed: %v\n", err)
continue
}
}
wg.Add(1)
ln := listener.(*net.TCPListener)
go func() {
defer wg.Done()
if err := runWebListener(ln, s.GetInterface()); err != nil {
if err := runWebListener(ln, s.GetInterface(), sessions); err != nil {
fmt.Printf("error running web-api: %s", err)
}
}()
Expand Down Expand Up @@ -552,6 +589,16 @@ func main() {
Usage: "address to listen on for web API",
EnvVar: "WHAWTY_AUTH_WEB_ADDR",
},
cli.StringSliceFlag{
Name: "sso-auth-addr",
Usage: "address to listen on for nginx auth_request queries",
EnvVar: "WHAWTY_SSO_AUTH_ADDR",
},
cli.StringSliceFlag{
Name: "sso-login-addr",
Usage: "address to listen on for form-based login to auth-request",
EnvVar: "WHAWTY_SSO_LOGIN_ADDR",
},
},
Action: cmdRun,
},
Expand Down
189 changes: 189 additions & 0 deletions cmd/whawty-auth/sso_api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
//
// Copyright (c) 2016 whawty contributors (see AUTHORS file)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of whawty.auth nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

package main

import (
"fmt"
"html"
"net"
"net/http"
_ "net/http/pprof"
"strings"
"time"
)

func handleSSOReturnLoginForm(w http.ResponseWriter, r *http.Request) {
baseURI := r.Header.Get("X-BaseURI")
if baseURI == "" {
baseURI = "/"
}

rip := r.Header.Get("X-Real-IP")
redir := r.URL.Query().Get("redir")
wdl.Printf("sso: got request for FORM LOGIN for SSO to %q from %q via %s", redir, rip, r.RemoteAddr)

w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf(`<!DOCTYPE html>
<meta charset="utf-8" />
<title>Login to Realm %q at %q</title>
<form action="%s?redir=%s" method="post">
<label for=username>Username:</label>
<input name=username required><p>
<label for=password>Password:</label>
<input type=password name=password required><p>
<button type=submit>Login (and return to %s)</button>
</form>`, baseURI, "Our Realm", r.Host, html.EscapeString(redir), html.EscapeString(redir))))
}

func handleSSOPostLogin(store *Store, sessions *webSessionFactory, w http.ResponseWriter, r *http.Request) {
rip := r.Header.Get("X-Real-IP")
wdl.Printf("sso: got LOGIN for SSO request from %q via %s", rip, r.RemoteAddr)

user := r.PostFormValue("username")
password := r.PostFormValue("password")

if user == "" || password == "" {
http.Error(w, "Bad Request\nMissing at least one of: username, password", http.StatusBadRequest)
return
}

ok, isAdmin, _, err := store.Authenticate(user, password)
if err != nil || !ok {
http.Error(w, "Authentication failed", http.StatusUnauthorized)
return
}

status, _, session := sessions.Generate(user, isAdmin)
if status != http.StatusOK {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}

splitter := strings.Index(r.Host, ":")
if splitter == -1 {
splitter = len(r.Host)
}
domain := r.Host[:splitter]
cookie := http.Cookie{
Name: "sso", // TODO
Value: session,
Expires: time.Now().Add(10 * time.Minute), // TODO
Secure: true, // TODO
Domain: domain,
Path: "/",
}
http.SetCookie(w, &cookie)

redirect := r.URL.Query().Get("redir")
if redirect == "" {
w.WriteHeader(http.StatusOK)
w.Write([]byte("login successful"))
return
}
http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
}

func handleSSOLogin(store *Store, sessions *webSessionFactory, w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
handleSSOReturnLoginForm(w, r)
return
case http.MethodPost:
handleSSOPostLogin(store, sessions, w, r)
return
default:
http.Error(w, "Bad Request", http.StatusBadRequest)
}
}

func handleSSOAuth(store *Store, sessions *webSessionFactory, w http.ResponseWriter, r *http.Request) {
host := r.Header.Get("Host")
uri := r.Header.Get("X-Original-URI")
rip := r.Header.Get("X-Real-IP")
wdl.Printf("sso: got SSO AUTHENTICATE request for %s%s from %q via %s", host, uri, rip, r.RemoteAddr)

session, err := r.Cookie("sso")
if err != nil || session.Value == "" {
http.Error(w, "No authentication", http.StatusUnauthorized)
return
}

status, _, user, _ := sessions.Check(session.Value)
if status != http.StatusOK {
// nginx config must redirect to login for 401 for this to work as intended
http.Error(w, "Authentication failed", http.StatusUnauthorized)
return
}

w.Header().Set("User", user)
w.WriteHeader(http.StatusOK)
}

func runSSOLoginListener(listener *net.TCPListener, store *Store, sessions *webSessionFactory) (err error) {
mux := http.NewServeMux()
mux.Handle("/", webHandler{store, sessions, handleSSOLogin})

server := &http.Server{Handler: mux, ReadTimeout: 60 * time.Second, WriteTimeout: 60 * time.Second}
wl.Printf("sso-login: listening on '%s'", listener.Addr())
return server.Serve(tcpKeepAliveListener{listener})
}

func runSSOLoginAddr(addr string, store *Store, sessions *webSessionFactory) (err error) {
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return runSSOLoginListener(ln.(*net.TCPListener), store, sessions)
}

func runSSOAuthListener(listener *net.TCPListener, store *Store, sessions *webSessionFactory) (err error) {
mux := http.NewServeMux()
mux.Handle("/", webHandler{store, sessions, handleSSOAuth})

server := &http.Server{Handler: mux, ReadTimeout: 60 * time.Second, WriteTimeout: 60 * time.Second}
wl.Printf("sso-auth: listening on '%s'", listener.Addr())
return server.Serve(tcpKeepAliveListener{listener})
}

func runSSOAuthAddr(addr string, store *Store, sessions *webSessionFactory) (err error) {
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return runSSOAuthListener(ln.(*net.TCPListener), store, sessions)
}
42 changes: 29 additions & 13 deletions cmd/whawty-auth/web_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@ package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
_ "net/http/pprof"
"strings"
"time"

storeLib "github.com/whawty/auth/store"
Expand Down Expand Up @@ -477,12 +479,7 @@ func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
return tc, nil
}

func runWebApi(listener *net.TCPListener, store *Store) (err error) {
var sessions *webSessionFactory
if sessions, err = NewWebSessionFactory(600 * time.Second); err != nil { // TODO: hardcoded value
return err
}

func runWebListener(listener *net.TCPListener, store *Store, sessions *webSessionFactory) (err error) {
mux := http.NewServeMux()
mux.Handle("/api/authenticate", webHandler{store, sessions, handleWebAuthenticate})
mux.Handle("/api/add", webHandler{store, sessions, handleWebAdd})
Expand All @@ -492,32 +489,51 @@ func runWebApi(listener *net.TCPListener, store *Store) (err error) {
mux.Handle("/api/list", webHandler{store, sessions, handleWebList})
mux.Handle("/api/list-full", webHandler{store, sessions, handleWebListFull})

mux.Handle("/admin/js/admin.js", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
baseURI := r.Header.Get("X-BaseURI")
if baseURI == "" {
baseURI = "/"
}
f, err := ui.Assets.Open("js/admin.js")
if err != nil {
panic("invalid path to compile-time asset specified")
}
content, _ := ioutil.ReadAll(f)
content = []byte(strings.Replace(
string(content),
`var auth_basepath = "/api/";`,
fmt.Sprintf(`var auth_basepath = "%sapi/";`, baseURI),
1))
w.Header().Add("Content-Type", "applicatin/javascript")
w.WriteHeader(http.StatusOK)
w.Write(content)
}))
mux.Handle("/admin/", http.StripPrefix("/admin/", http.FileServer(ui.Assets)))

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
http.Redirect(w, r, "/admin/", http.StatusTemporaryRedirect)
baseURI := r.Header.Get("X-BaseURI")
if baseURI == "" {
baseURI = "/"
}
http.Redirect(w, r, fmt.Sprintf("%sadmin/", baseURI), http.StatusTemporaryRedirect)
})

wl.Printf("web-api: listening on '%s'", listener.Addr())
server := &http.Server{Handler: mux, ReadTimeout: 60 * time.Second, WriteTimeout: 60 * time.Second}
return server.Serve(tcpKeepAliveListener{listener})
}

func runWebAddr(addr string, store *Store) (err error) {
func runWebAddr(addr string, store *Store, sessions *webSessionFactory) (err error) {
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return runWebApi(ln.(*net.TCPListener), store)
}

func runWebListener(listener *net.TCPListener, store *Store) (err error) {
return runWebApi(listener, store)
return runWebListener(ln.(*net.TCPListener), store, sessions)
}
Loading