restapi.go 5.1 KB

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