diff --git a/app/ipasso/envEndpoint.go b/app/ipasso/envEndpoint.go index 4b8783c..aea5ba6 100644 --- a/app/ipasso/envEndpoint.go +++ b/app/ipasso/envEndpoint.go @@ -20,6 +20,12 @@ func init() { }) } +type envdocArgs struct { + Headers map[string]string + ProcessEnv map[string]string + ReqURL string +} + func dumpEnv(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") diff --git a/app/ipasso/main.go b/app/ipasso/main.go index 07451de..897b189 100644 --- a/app/ipasso/main.go +++ b/app/ipasso/main.go @@ -1,24 +1,17 @@ package main import ( - "bytes" - "encoding/json" "errors" "flag" "fmt" - "git.thequux.com/thequux/ipasso/resources" "git.thequux.com/thequux/ipasso/sso-proxy/backend" "git.thequux.com/thequux/ipasso/util/startup" - "github.com/CloudyKit/jet/v6" "github.com/julienschmidt/httprouter" - "gitlab.com/jamietanna/content-negotiation-go" "go.uber.org/zap" "log" "net" - "net/http" "net/http/fcgi" "os" - "strconv" ) var ( @@ -58,89 +51,3 @@ func main() { l.Info("Listening", zap.Stringer("addr", listener.Addr())) log.Fatal(fcgi.Serve(listener, router)) } - -type envdocArgs struct { - Headers map[string]string - ProcessEnv map[string]string - ReqURL string -} - -// Try to continue negotiation via a www-authenticate header, if this is an error page. -func continueNegotate(w http.ResponseWriter, r *http.Request) bool { - procEnv := fcgi.ProcessEnv(r) - l := zap.L().Named("req") - l.Debug("Received request", zap.Any("env", procEnv)) - - rStatus, ok := procEnv["REDIRECT_STATUS"] - if ok && rStatus == "401" { - w.Header().Set("WWW-Authenticate", "Negotiate") - w.WriteHeader(401) - return true - } - return false -} - -type RespErr struct { - Err string - Status string -} - -func ReportError(w http.ResponseWriter, err error) { - w.Header().Set("Content-Type", "text/json") - w.WriteHeader(http.StatusInternalServerError) - js, err0 := json.Marshal(RespErr{Err: err.Error(), Status: "ERROR"}) - if err0 != nil { - panic(err0) - } - _, _ = w.Write(js) -} - -var negotiator = contentnegotiation.NewNegotiator("text/html", "text/plain", "application/json") - -func RenderPage(w http.ResponseWriter, req *http.Request, template string, data interface{}) { - ctype, _, err := negotiator.Negotiate(req.Header.Get("Accept")) - if err != nil { - templateLogger.Warn("Negotiation failed", - zap.String("accept", req.Header.Get("Accept")), - zap.Error(err), - ) - ReportError(w, err) - } - - w.Header().Set("Content-Type", ctype.String()) - - var result []byte - var jetTemplate *jet.Template - - if ctype.String() == "text/html" { - template = template + ".html" - jetTemplate, err = resources.Templates.HtmlTemplate(template) - } else if ctype.String() == "text/plain" { - template = template + ".txt" - jetTemplate, err = resources.Templates.TextTemplate(template) - } else if ctype.String() == "application/json" { - jetTemplate = nil - result, err = json.MarshalIndent(data, "", " ") - } else { - templateLogger.Warn("Negotiation returned something unexpected", zap.Stringer("negotiated", &ctype)) - err = errors.New("unexpected negotiation result") - } - - if err == nil && jetTemplate != nil && len(result) == 0 { - var builder bytes.Buffer - err := jetTemplate.Execute(&builder, nil, data) - if err != nil { - templateLogger.Warn("Failed to render template", zap.String("tmpl", template), zap.Error(err)) - } else { - result = builder.Bytes() - } - } - if err == nil { - w.Header().Set("Content-Type", ctype.String()) - w.Header().Set("Content-Length", strconv.FormatInt(int64(len(result)), 10)) - w.WriteHeader(200) - _, _ = w.Write(result) - } else { - ReportError(w, err) - } -} diff --git a/app/ipasso/renderCommon.go b/app/ipasso/renderCommon.go new file mode 100644 index 0000000..5832e63 --- /dev/null +++ b/app/ipasso/renderCommon.go @@ -0,0 +1,101 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "git.thequux.com/thequux/ipasso/resources" + "github.com/CloudyKit/jet/v6" + contentnegotiation "gitlab.com/jamietanna/content-negotiation-go" + "go.uber.org/zap" + "net/http" + "net/http/fcgi" + "strconv" +) + +// Try to continue negotiation via a www-authenticate header, if this is an error page. +func continueNegotate(w http.ResponseWriter, r *http.Request) bool { + procEnv := fcgi.ProcessEnv(r) + l := zap.L().Named("req") + l.Debug("Received request", zap.Any("env", procEnv)) + + rStatus, ok := procEnv["REDIRECT_STATUS"] + if ok && rStatus == "401" { + w.Header().Set("WWW-Authenticate", "Negotiate") + w.WriteHeader(401) + return true + } + return false +} + +type RespErr struct { + Err string + Status string +} + +func ReportError(w http.ResponseWriter, err error) { + w.Header().Set("Content-Type", "text/json") + w.WriteHeader(http.StatusInternalServerError) + js, err0 := json.Marshal(RespErr{Err: err.Error(), Status: "ERROR"}) + if err0 != nil { + panic(err0) + } + _, _ = w.Write(js) +} + +var ctypes = [resources.ATComboCount]contentnegotiation.Negotiator{ + contentnegotiation.NewNegotiator("application/json"), + contentnegotiation.NewNegotiator("text/html", "application/json", "text/html"), + contentnegotiation.NewNegotiator("text/plain", "application/json"), + contentnegotiation.NewNegotiator("text/html", "text/plain", "application/json"), +} + +//var negotiator = contentnegotiation.NewNegotiator("text/html", "text/plain", "application/json") + +func RenderPage(w http.ResponseWriter, req *http.Request, template string, data interface{}) { + act := resources.Templates.GetContentTypes(template) + negotiator := ctypes[act] + ctype, _, err := negotiator.Negotiate(req.Header.Get("Accept")) + if err != nil { + w.Header().Set("Content-Length", "0") + w.WriteHeader(http.StatusUnsupportedMediaType) + return + } + + w.Header().Set("Content-Type", ctype.String()) + + var result []byte + var jetTemplate *jet.Template + + if ctype.String() == "text/html" { + //template = template + ".html" + jetTemplate, err = resources.Templates.HtmlTemplate(template) + } else if ctype.String() == "text/plain" { + //template = template + ".txt" + jetTemplate, err = resources.Templates.TextTemplate(template) + } else if ctype.String() == "application/json" { + jetTemplate = nil + result, err = json.MarshalIndent(data, "", " ") + } else { + templateLogger.Warn("Negotiation returned something unexpected", zap.Stringer("negotiated", &ctype)) + err = errors.New("unexpected negotiation result") + } + + if err == nil && jetTemplate != nil && len(result) == 0 { + var builder bytes.Buffer + err := jetTemplate.Execute(&builder, nil, data) + if err != nil { + templateLogger.Warn("Failed to render template", zap.String("tmpl", template), zap.Error(err)) + } else { + result = builder.Bytes() + } + } + if err == nil { + w.Header().Set("Content-Type", ctype.String()) + w.Header().Set("Content-Length", strconv.FormatInt(int64(len(result)), 10)) + w.WriteHeader(200) + _, _ = w.Write(result) + } else { + ReportError(w, err) + } +} diff --git a/go.mod b/go.mod index 3cda89e..b509703 100644 --- a/go.mod +++ b/go.mod @@ -18,6 +18,7 @@ require ( github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53 // indirect github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect github.com/google/uuid v1.3.1 // indirect github.com/hashicorp/go-uuid v1.0.3 // indirect @@ -26,7 +27,9 @@ require ( github.com/jcmturner/gofork v1.7.6 // indirect github.com/jcmturner/goidentity/v6 v6.0.1 // indirect github.com/jcmturner/rpc/v2 v2.0.3 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/stretchr/testify v1.8.4 // indirect go.uber.org/multierr v1.10.0 // indirect golang.org/x/crypto v0.13.0 // indirect - golang.org/x/net v0.10.0 // indirect + golang.org/x/net v0.15.0 // indirect ) diff --git a/go.sum b/go.sum index dbc15ad..6cf4eaf 100644 --- a/go.sum +++ b/go.sum @@ -7,8 +7,9 @@ github.com/CloudyKit/jet/v6 v6.2.0/go.mod h1:d3ypHeIRNo2+XyqnGA8s+aphtcVpjP5hPwP github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74 h1:Kk6a4nehpJ3UuJRqlA3JxYxBZEqCeOmATOvrbT4p9RA= github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-asn1-ber/asn1-ber v1.5.4/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= github.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA= github.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= @@ -37,16 +38,18 @@ github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZ github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= gitlab.com/jamietanna/content-negotiation-go v0.2.0 h1:vT0OLEPQ6DYRG3/1F7joXSNjVQHGivJ6+JzODlJfjWw= gitlab.com/jamietanna/content-negotiation-go v0.2.0/go.mod h1:n4ZZ8/X5TstnjYRnjEtR/fC7MCTe+aRKM7PQlLBH3PQ= @@ -70,8 +73,9 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= -golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.15.0 h1:ugBLEUaxABaB5AJqW9enI0ACdci2RUd4eP51NTBvuJ8= +golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= diff --git a/resources/resources.go b/resources/resources.go index 7519446..c8b97be 100644 --- a/resources/resources.go +++ b/resources/resources.go @@ -12,6 +12,7 @@ import ( "net/http" "os" "path" + "reflect" "strings" ) @@ -58,7 +59,7 @@ func init() { l.Fatal("Unable to find templates") } - Templates = loadTemplates(templateFS, *externalResources == "") + Templates = loadTemplates(templateFS, *externalResources != "") StaticFiles, err = fs.Sub(Resources, "static") if err != nil { l.Fatal("Cannot find static files", zap.Error(err)) @@ -98,9 +99,19 @@ func extractResources(dst string) { }) } +type AvailableTemplates int + +const ( + ATHtml AvailableTemplates = 1 << iota + ATText + ATComboCount +) + type TemplateSource struct { - htmlCache *jet.Set - textCache *jet.Set + htmlCache *jet.Set + textCache *jet.Set + isDevMode bool + availableContentTypes map[string]AvailableTemplates } func loadTemplates(src fs.FS, devMode bool) TemplateSource { @@ -112,17 +123,63 @@ func loadTemplates(src fs.FS, devMode bool) TemplateSource { } loader := genFsLoader{fs: src} - return TemplateSource{ - htmlCache: jet.NewSet(loader, devModeOpt), - textCache: jet.NewSet(loader, devModeOpt, jet.WithSafeWriter(nil)), + res := TemplateSource{ + isDevMode: devMode, + htmlCache: jet.NewSet(loader, devModeOpt, jet.WithTemplateNameExtensions([]string{".html", ".html.jet"})), + textCache: jet.NewSet(loader, devModeOpt, jet.WithTemplateNameExtensions([]string{".txt", ".txt.jet"}), jet.WithSafeWriter(nil)), + availableContentTypes: make(map[string]AvailableTemplates), } + + res.htmlCache.AddGlobal("TemplateMode", "html") + res.textCache.AddGlobal("TemplateMode", "text") + + return res } -func (ts TemplateSource) HtmlTemplate(name string) (*jet.Template, error) { +// Add a global variable available to all templates +func (ts *TemplateSource) AddGlobalVar(name string, value interface{}) { + ts.textCache.AddGlobal(name, value) + ts.htmlCache.AddGlobal(name, value) +} + +// Add a global function available to HTML templates +func (ts *TemplateSource) AddHtmlFunction(name string, value func(arguments jet.Arguments) reflect.Value) { + ts.htmlCache.AddGlobalFunc(name, value) +} + +// Adds a global function available to text templates +func (ts *TemplateSource) AddTextFunction(name string, value func(arguments jet.Arguments) reflect.Value) { + ts.htmlCache.AddGlobalFunc(name, value) +} + +// Adds a global function available to all templates. Equivalent to calling AddHtmlFunction and AddTextFunction +func (ts *TemplateSource) AddFunction(name string, value func(arguments jet.Arguments) reflect.Value) { + ts.AddHtmlFunction(name, value) + ts.AddTextFunction(name, value) +} + +func (ts *TemplateSource) GetContentTypes(name string) AvailableTemplates { + if result, ok := ts.availableContentTypes[name]; ok { + return result + } + var result AvailableTemplates + if _, err := ts.HtmlTemplate(name); err == nil { + result = result | ATHtml + } + if _, err := ts.TextTemplate(name); err == nil { + result = result | ATText + } + if !ts.isDevMode { + ts.availableContentTypes[name] = result + } + return result +} + +func (ts *TemplateSource) HtmlTemplate(name string) (*jet.Template, error) { return ts.htmlCache.GetTemplate(name) } -func (ts TemplateSource) TextTemplate(name string) (*jet.Template, error) { +func (ts *TemplateSource) TextTemplate(name string) (*jet.Template, error) { return ts.textCache.GetTemplate(name) } diff --git a/resources/static/login/index.html b/resources/static/login/index.html new file mode 100644 index 0000000..ff377a7 --- /dev/null +++ b/resources/static/login/index.html @@ -0,0 +1,27 @@ + + + + + SSO Login + + +
+ + + + + + + + + + + + + +
+ +
+
+ + \ No newline at end of file diff --git a/util/startup/startup.go b/util/startup/startup.go index 18e17df..e6c164d 100644 --- a/util/startup/startup.go +++ b/util/startup/startup.go @@ -4,11 +4,14 @@ import "github.com/julienschmidt/httprouter" // Pre-defined queues... var ( + // Configure loggers Logger Phase - // Phase + // Post-process flags, applying computed defaults. PostFlags Phase - Startup Phase - Routes ParameterizedPhase[*httprouter.Router] + // Make external connections + Startup Phase + // Gather HTTP routes + Routes ParameterizedPhase[*httprouter.Router] ) type Phase struct {