restapi.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package httpservers
  2. import (
  3. "context"
  4. "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
  5. log "github.com/sirupsen/logrus"
  6. "google.golang.org/grpc"
  7. "google.golang.org/grpc/metadata"
  8. "google.golang.org/protobuf/encoding/protojson"
  9. "google.golang.org/protobuf/reflect/protoreflect"
  10. "net/http"
  11. "strings"
  12. apiv1 "github.com/OliveTin/OliveTin/gen/grpc/olivetin/api/v1"
  13. config "github.com/OliveTin/OliveTin/internal/config"
  14. cors "github.com/OliveTin/OliveTin/internal/cors"
  15. )
  16. var (
  17. cfg *config.Config
  18. )
  19. func parseHttpHeaderForAuth(req *http.Request) (string, string) {
  20. username, ok := req.Header[cfg.AuthHttpHeaderUsername]
  21. if !ok {
  22. log.Warnf("Config has AuthHttpHeaderUsername set to %v, but it was not found", cfg.AuthHttpHeaderUsername)
  23. return "", ""
  24. }
  25. if cfg.AuthHttpHeaderUserGroup != "" {
  26. usergroup, ok := req.Header[cfg.AuthHttpHeaderUserGroup]
  27. if ok {
  28. log.Debugf("HTTP Header Auth found a username and usergroup")
  29. return username[0], usergroup[0]
  30. } else {
  31. log.Warnf("Config has AuthHttpHeaderUserGroup set to %v, but it was not found", cfg.AuthHttpHeaderUserGroup)
  32. }
  33. }
  34. log.Debugf("HTTP Header Auth found a username, but usergroup is not being used")
  35. return username[0], ""
  36. }
  37. //gocyclo:ignore
  38. func parseRequestMetadata(ctx context.Context, req *http.Request) metadata.MD {
  39. username := ""
  40. usergroup := ""
  41. provider := "unknown"
  42. sid := ""
  43. if cfg.AuthJwtHeader != "" {
  44. username, usergroup = parseJwtHeader(req)
  45. provider = "jwt-header"
  46. }
  47. if cfg.AuthJwtCookieName != "" {
  48. username, usergroup = parseJwtCookie(req)
  49. provider = "jwt-cookie"
  50. }
  51. if cfg.AuthHttpHeaderUsername != "" && username == "" {
  52. username, usergroup = parseHttpHeaderForAuth(req)
  53. provider = "http-header"
  54. }
  55. if len(cfg.AuthOAuth2Providers) > 0 && username == "" {
  56. username, usergroup, sid = parseOAuth2Cookie(req)
  57. provider = "oauth2"
  58. }
  59. if cfg.AuthLocalUsers.Enabled && username == "" {
  60. username, usergroup, sid = parseLocalUserCookie(req)
  61. provider = "local"
  62. }
  63. md := metadata.New(map[string]string{
  64. "username": username,
  65. "usergroup": usergroup,
  66. "provider": provider,
  67. "sid": sid,
  68. })
  69. log.Tracef("api request metadata: %+v", md)
  70. return md
  71. }
  72. func parseJwtHeader(req *http.Request) (string, string) {
  73. // JWTs in the Authorization header are usually prefixed with "Bearer " which is not part of the JWT token.
  74. return parseJwt(strings.TrimPrefix(req.Header.Get(cfg.AuthJwtHeader), "Bearer "))
  75. }
  76. func forwardResponseHandler(ctx context.Context, w http.ResponseWriter, msg protoreflect.ProtoMessage) error {
  77. md, ok := runtime.ServerMetadataFromContext(ctx)
  78. if !ok {
  79. log.Warn("Could not get ServerMetadata from context")
  80. return nil
  81. }
  82. forwardResponseHandlerLoginLocalUser(md.HeaderMD, w)
  83. forwardResponseHandlerLogout(md.HeaderMD, w)
  84. return nil
  85. }
  86. func forwardResponseHandlerLogout(md metadata.MD, w http.ResponseWriter) {
  87. if getMetadataKeyOrEmpty(md, "logout-provider") != "" {
  88. sid := getMetadataKeyOrEmpty(md, "logout-sid")
  89. delete(registeredStates, sid)
  90. http.SetCookie(
  91. w,
  92. &http.Cookie{
  93. Name: "olivetin-sid-oauth",
  94. MaxAge: 31556952, // 1 year
  95. Value: "",
  96. HttpOnly: true,
  97. Path: "/",
  98. },
  99. )
  100. deleteLocalUserSession("local", sid)
  101. http.SetCookie(
  102. w,
  103. &http.Cookie{
  104. Name: "olivetin-sid-local",
  105. MaxAge: 31556952, // 1 year
  106. Value: "",
  107. HttpOnly: true,
  108. Path: "/",
  109. },
  110. )
  111. w.Header().Set("Content-Type", "text/html")
  112. // We cannot send a HTTP redirect here, because we don't have access to req.
  113. w.Write([]byte("<script>window.location.href = '/';</script>"))
  114. }
  115. }
  116. func getMetadataKeyOrEmpty(md metadata.MD, key string) string {
  117. mdValues := md.Get(key)
  118. if len(mdValues) > 0 {
  119. return mdValues[0]
  120. }
  121. return ""
  122. }
  123. func SetGlobalRestConfig(config *config.Config) {
  124. cfg = config
  125. }
  126. func startRestAPIServer(globalConfig *config.Config) error {
  127. cfg = globalConfig
  128. loadUserSessions()
  129. log.WithFields(log.Fields{
  130. "address": cfg.ListenAddressRestActions,
  131. }).Info("Starting REST API")
  132. mux := newMux()
  133. return http.ListenAndServe(cfg.ListenAddressRestActions, cors.AllowCors(mux))
  134. }
  135. func newMux() *runtime.ServeMux {
  136. // The MarshalOptions set some important compatibility settings for the webui. See below.
  137. mux := runtime.NewServeMux(
  138. runtime.WithMetadata(parseRequestMetadata),
  139. runtime.WithForwardResponseOption(forwardResponseHandler),
  140. runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.HTTPBodyMarshaler{
  141. Marshaler: &runtime.JSONPb{
  142. MarshalOptions: protojson.MarshalOptions{
  143. UseProtoNames: false, // eg: canExec for js instead of can_exec from protobuf
  144. EmitUnpopulated: true, // Emit empty fields so that javascript does not get "undefined" when accessing fields with empty values.
  145. },
  146. },
  147. }),
  148. )
  149. ctx := context.Background()
  150. opts := []grpc.DialOption{grpc.WithInsecure()}
  151. err := apiv1.RegisterOliveTinApiServiceHandlerFromEndpoint(ctx, mux, cfg.ListenAddressGrpcActions, opts)
  152. if err != nil {
  153. log.Panicf("Could not register REST API Handler %v", err)
  154. }
  155. return mux
  156. }