restapi.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. // JWTs in the Authorization header are usually prefixed with "Bearer " which is not part of the JWT token.
  45. username, usergroup = parseJwt(strings.TrimPrefix(req.Header.Get(cfg.AuthJwtHeader), "Bearer "))
  46. provider = "jwt-header"
  47. }
  48. if cfg.AuthJwtCookieName != "" {
  49. username, usergroup = parseJwtCookie(req)
  50. provider = "jwt-cookie"
  51. }
  52. if cfg.AuthHttpHeaderUsername != "" && username == "" {
  53. username, usergroup = parseHttpHeaderForAuth(req)
  54. provider = "http-header"
  55. }
  56. if len(cfg.AuthOAuth2Providers) > 0 && username == "" {
  57. username, usergroup, sid = parseOAuth2Cookie(req)
  58. provider = "oauth2"
  59. }
  60. if cfg.AuthLocalUsers.Enabled && username == "" {
  61. username, usergroup, sid = parseLocalUserCookie(req)
  62. provider = "local"
  63. }
  64. md := metadata.New(map[string]string{
  65. "username": username,
  66. "usergroup": usergroup,
  67. "provider": provider,
  68. "sid": sid,
  69. })
  70. log.Tracef("api request metadata: %+v", md)
  71. return md
  72. }
  73. func forwardResponseHandler(ctx context.Context, w http.ResponseWriter, msg protoreflect.ProtoMessage) error {
  74. md, ok := runtime.ServerMetadataFromContext(ctx)
  75. if !ok {
  76. log.Warn("Could not get ServerMetadata from context")
  77. return nil
  78. }
  79. forwardResponseHandlerLoginLocalUser(md.HeaderMD, w)
  80. forwardResponseHandlerLogout(md.HeaderMD, w)
  81. return nil
  82. }
  83. func forwardResponseHandlerLogout(md metadata.MD, w http.ResponseWriter) {
  84. if getMetadataKeyOrEmpty(md, "logout-provider") != "" {
  85. sid := getMetadataKeyOrEmpty(md, "logout-sid")
  86. delete(registeredStates, sid)
  87. http.SetCookie(
  88. w,
  89. &http.Cookie{
  90. Name: "olivetin-sid-oauth",
  91. MaxAge: 31556952, // 1 year
  92. Value: "",
  93. HttpOnly: true,
  94. Path: "/",
  95. },
  96. )
  97. deleteLocalUserSession("local", sid)
  98. http.SetCookie(
  99. w,
  100. &http.Cookie{
  101. Name: "olivetin-sid-local",
  102. MaxAge: 31556952, // 1 year
  103. Value: "",
  104. HttpOnly: true,
  105. Path: "/",
  106. },
  107. )
  108. w.Header().Set("Content-Type", "text/html")
  109. // We cannot send a HTTP redirect here, because we don't have access to req.
  110. w.Write([]byte("<script>window.location.href = '/';</script>"))
  111. }
  112. }
  113. func getMetadataKeyOrEmpty(md metadata.MD, key string) string {
  114. mdValues := md.Get(key)
  115. if len(mdValues) > 0 {
  116. return mdValues[0]
  117. }
  118. return ""
  119. }
  120. func SetGlobalRestConfig(config *config.Config) {
  121. cfg = config
  122. }
  123. func startRestAPIServer(globalConfig *config.Config) error {
  124. cfg = globalConfig
  125. loadUserSessions()
  126. log.WithFields(log.Fields{
  127. "address": cfg.ListenAddressRestActions,
  128. }).Info("Starting REST API")
  129. mux := newMux()
  130. return http.ListenAndServe(cfg.ListenAddressRestActions, cors.AllowCors(mux))
  131. }
  132. func newMux() *runtime.ServeMux {
  133. // The MarshalOptions set some important compatibility settings for the webui. See below.
  134. mux := runtime.NewServeMux(
  135. runtime.WithMetadata(parseRequestMetadata),
  136. runtime.WithForwardResponseOption(forwardResponseHandler),
  137. runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.HTTPBodyMarshaler{
  138. Marshaler: &runtime.JSONPb{
  139. MarshalOptions: protojson.MarshalOptions{
  140. UseProtoNames: false, // eg: canExec for js instead of can_exec from protobuf
  141. EmitUnpopulated: true, // Emit empty fields so that javascript does not get "undefined" when accessing fields with empty values.
  142. },
  143. },
  144. }),
  145. )
  146. ctx := context.Background()
  147. opts := []grpc.DialOption{grpc.WithInsecure()}
  148. err := apiv1.RegisterOliveTinApiServiceHandlerFromEndpoint(ctx, mux, cfg.ListenAddressGrpcActions, opts)
  149. if err != nil {
  150. log.Panicf("Could not register REST API Handler %v", err)
  151. }
  152. return mux
  153. }