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

feat:allow authentication using proxy request header #860

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ Most configuration can be set directly using environment variables or flags. The
| `SHIORI_HTTP_IDLE_TIMEOUT` | 10s | No | Maximum amount of time to wait for the next request |
| `SHIORI_HTTP_DISABLE_KEEP_ALIVE` | true | No | Disable HTTP keep-alive connections |
| `SHIORI_HTTP_DISABLE_PARSE_MULTIPART_FORM` | true | No | Disable pre-parsing of multipart form |
| `SHIORI_TRUSTED_PROXIES` | "" | No | oidc trust proxy ip address |
| `SHIORI_REVERSE_PROXY_AUTH_USER` | "" | No | user id key of oidc auth header, ie. Remote-User |

### Storage Configuration

Expand Down
16 changes: 9 additions & 7 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,15 @@ func readDotEnv(logger *logrus.Logger) map[string]string {
}

type HttpConfig struct {
Enabled bool `env:"HTTP_ENABLED,default=True"`
Port int `env:"HTTP_PORT,default=8080"`
Address string `env:"HTTP_ADDRESS,default=:"`
RootPath string `env:"HTTP_ROOT_PATH,default=/"`
AccessLog bool `env:"HTTP_ACCESS_LOG,default=True"`
ServeWebUI bool `env:"HTTP_SERVE_WEB_UI,default=True"`
SecretKey []byte `env:"HTTP_SECRET_KEY"`
Enabled bool `env:"HTTP_ENABLED,default=True"`
Port int `env:"HTTP_PORT,default=8080"`
Address string `env:"HTTP_ADDRESS,default=:"`
RootPath string `env:"HTTP_ROOT_PATH,default=/"`
AccessLog bool `env:"HTTP_ACCESS_LOG,default=True"`
ServeWebUI bool `env:"HTTP_SERVE_WEB_UI,default=True"`
SecretKey []byte `env:"HTTP_SECRET_KEY"`
TrustedProxies []string `env:"TRUSTED_PROXIES"`
ReverseProxyAuthUser string `env:"REVERSE_PROXY_AUTH_USER"`
// Fiber Specific
BodyLimit int `env:"HTTP_BODY_LIMIT,default=1024"`
ReadTimeout time.Duration `env:"HTTP_READ_TIMEOUT,default=10s"`
Expand Down
9 changes: 5 additions & 4 deletions internal/dependencies/dependencies.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ import (
)

type Domains struct {
Archiver model.ArchiverDomain
Auth model.AccountsDomain
Bookmarks model.BookmarksDomain
Storage model.StorageDomain
Archiver model.ArchiverDomain
Auth model.AccountsDomain
Bookmarks model.BookmarksDomain
Storage model.StorageDomain
LegacyLogin model.LegacyLoginHandler
}

type Dependencies struct {
Expand Down
57 changes: 57 additions & 0 deletions internal/http/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import (
"net/http"
"strings"
"time"

"github.com/gin-gonic/gin"
"github.com/go-shiori/shiori/internal/dependencies"
Expand All @@ -20,6 +21,9 @@
if token == "" {
token = getTokenFromCookie(c)
}
if token == "" {
token = getTokenFromAuthHeader(c, deps)
}

account, err := deps.Domains.Auth.CheckToken(c, token)
if err != nil {
Expand All @@ -42,6 +46,59 @@
}
}

// getAuth user from oauth proxy, if any
func getTokenFromAuthHeader(c *gin.Context, deps *dependencies.Dependencies) string {
if deps.Config.Http.ReverseProxyAuthUser == "" {
deps.Log.Debugf("auth proxy: reverse-proxy-auth-user not set")
return ""
}
authUser := c.GetHeader(deps.Config.Http.ReverseProxyAuthUser)
if authUser == "" {
deps.Log.Debugf("auth proxy: can not get user header from proxy")
return ""

Check warning on line 58 in internal/http/middleware/auth.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/auth.go#L55-L58

Added lines #L55 - L58 were not covered by tests
}
remoteAddr := c.ClientIP()
deps.Log.Debugf("auth proxy: got auth user (%s), client ip (%s)", authUser, remoteAddr)
cidrs, err := newCIDRs(deps.Config.Http.TrustedProxies)
if err != nil {
deps.Log.Errorf("auth proxy: trusted proxy config error (%v)", err)
return ""

Check warning on line 65 in internal/http/middleware/auth.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/auth.go#L60-L65

Added lines #L60 - L65 were not covered by tests
}
canTrustProxy := false
if len(deps.Config.Http.TrustedProxies) == 0 || cidrs.ContainStringIP(remoteAddr) {
canTrustProxy = true

Check warning on line 69 in internal/http/middleware/auth.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/auth.go#L67-L69

Added lines #L67 - L69 were not covered by tests
}
if canTrustProxy {
account, exit, err := deps.Database.GetAccount(c, authUser)
if err == nil && exit {
token, err := deps.Domains.Auth.CreateTokenForAccount(&account, time.Now().Add(time.Hour*24*365))
if err != nil {
deps.Log.Errorf("auth proxy: create token error %v", err)
return ""

Check warning on line 77 in internal/http/middleware/auth.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/auth.go#L71-L77

Added lines #L71 - L77 were not covered by tests
}
sessionId, err := deps.Domains.LegacyLogin(account, time.Hour*24*30)
if err != nil {
deps.Log.Errorf("auth proxy: create session error %v", err)
return ""

Check warning on line 82 in internal/http/middleware/auth.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/auth.go#L79-L82

Added lines #L79 - L82 were not covered by tests
}
deps.Log.Debugf("auth proxy: write session %s token %s", sessionId, token)
sessionCookie := &http.Cookie{Name: "session-id", Value: sessionId}
http.SetCookie(c.Writer, sessionCookie)
c.Request.AddCookie(sessionCookie)
tokenCookie := &http.Cookie{Name: "token", Value: token}
http.SetCookie(c.Writer, tokenCookie)
c.Request.AddCookie(tokenCookie)

Check warning on line 90 in internal/http/middleware/auth.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/auth.go#L84-L90

Added lines #L84 - L90 were not covered by tests

return token
} else {
deps.Log.Warnf("auth proxy: no such user (%s) or error %v", authUser, err)

Check warning on line 94 in internal/http/middleware/auth.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/auth.go#L92-L94

Added lines #L92 - L94 were not covered by tests
PterX marked this conversation as resolved.
Show resolved Hide resolved
}
} else if authUser != "" {
deps.Log.Warnf("auth proxy: invalid auth request from %s", remoteAddr)

Check warning on line 97 in internal/http/middleware/auth.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/auth.go#L96-L97

Added lines #L96 - L97 were not covered by tests
}
return ""

Check warning on line 99 in internal/http/middleware/auth.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/auth.go#L99

Added line #L99 was not covered by tests
}

// getTokenFromHeader returns the token from the Authorization header, if any.
func getTokenFromHeader(c *gin.Context) string {
authorization := c.GetHeader(model.AuthorizationHeader)
Expand Down
51 changes: 51 additions & 0 deletions internal/http/middleware/cidrs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package middleware

import (
"net"
"strings"
)

type CIDRs struct {
elements []*net.IPNet
}

func newCIDRs(addresses []string) (*CIDRs, error) {
cidr := make([]*net.IPNet, 0, len(addresses))
for _, addr := range addresses {
if !strings.Contains(addr, "/") {
ip := net.ParseIP(addr)
if ip == nil {
return nil, &net.ParseError{Type: "IP address", Text: addr}

Check warning on line 18 in internal/http/middleware/cidrs.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/cidrs.go#L12-L18

Added lines #L12 - L18 were not covered by tests
}
if ip.To4() == nil {
addr += "/128"
} else {
addr += "/32"

Check warning on line 23 in internal/http/middleware/cidrs.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/cidrs.go#L20-L23

Added lines #L20 - L23 were not covered by tests
}
}
_, cidrNet, err := net.ParseCIDR(addr)
if err != nil {
return nil, err

Check warning on line 28 in internal/http/middleware/cidrs.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/cidrs.go#L26-L28

Added lines #L26 - L28 were not covered by tests
}
cidr = append(cidr, cidrNet)

Check warning on line 30 in internal/http/middleware/cidrs.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/cidrs.go#L30

Added line #L30 was not covered by tests
}
return &CIDRs{elements: cidr}, nil

Check warning on line 32 in internal/http/middleware/cidrs.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/cidrs.go#L32

Added line #L32 was not covered by tests
}

func (c *CIDRs) Len() int {
return len(c.elements)

Check warning on line 36 in internal/http/middleware/cidrs.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/cidrs.go#L35-L36

Added lines #L35 - L36 were not covered by tests
}

func (c *CIDRs) ContainIP(ip net.IP) bool {
for _, el := range c.elements {
if el.Contains(ip) {
return true

Check warning on line 42 in internal/http/middleware/cidrs.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/cidrs.go#L39-L42

Added lines #L39 - L42 were not covered by tests
}
}

return false

Check warning on line 46 in internal/http/middleware/cidrs.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/cidrs.go#L46

Added line #L46 was not covered by tests
}

func (c *CIDRs) ContainStringIP(ip string) bool {
return c.ContainIP(net.ParseIP(ip))

Check warning on line 50 in internal/http/middleware/cidrs.go

View check run for this annotation

Codecov / codecov/patch

internal/http/middleware/cidrs.go#L49-L50

Added lines #L49 - L50 were not covered by tests
}
2 changes: 2 additions & 0 deletions internal/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@
// package.
legacyRoutes := routes.NewLegacyAPIRoutes(s.logger, deps, cfg)
legacyRoutes.Setup(s.engine)
// used for auth header save session
deps.Domains.LegacyLogin = legacyRoutes.HandleLogin

Check warning on line 61 in internal/http/server.go

View check run for this annotation

Codecov / codecov/patch

internal/http/server.go#L61

Added line #L61 was not covered by tests

s.handle("/system", routes.NewSystemRoutes(s.logger))
s.handle("/bookmark", routes.NewBookmarkRoutes(s.logger, deps))
Expand Down
25 changes: 24 additions & 1 deletion internal/view/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,32 @@
username: username,
owner: owner,
};
}
},
loadToken() {
function parseJWT(token) {
try {
return JSON.parse(atob(token.split('.')[1]));
} catch (e) {
return null;
}
}
function getCookie(cname){
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
}
return "";
}
// Save account data
var token = getCookie("token");
localStorage.setItem("shiori-token", token);
localStorage.setItem("shiori-account", JSON.stringify(parseJWT(token).account));
}
},
mounted() {
this.loadToken();
// Load setting
this.loadSetting();
this.loadAccount();
Expand Down
10 changes: 10 additions & 0 deletions internal/webserver/handler-api.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@

// Make sure session still valid
err := h.validateSession(r)
if err != nil {
c := &http.Cookie{
Name: "token",
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,

Check warning on line 72 in internal/webserver/handler-api.go

View check run for this annotation

Codecov / codecov/patch

internal/webserver/handler-api.go#L66-L72

Added lines #L66 - L72 were not covered by tests
}
http.SetCookie(w, c)

Check warning on line 74 in internal/webserver/handler-api.go

View check run for this annotation

Codecov / codecov/patch

internal/webserver/handler-api.go#L74

Added line #L74 was not covered by tests
}
checkError(err)

// Get URL queries
Expand Down
31 changes: 18 additions & 13 deletions internal/webserver/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,28 +111,33 @@
return fmt.Errorf("session has been expired")
}

account, err := h.dependencies.Domains.Auth.CheckToken(r.Context(), authParts[1])
if err != nil {
return fmt.Errorf("session has been expired")
}
// authelia maybe return an null AuthorizationHeader header, ignore exception
if authParts[1] != "null" {

Check warning on line 115 in internal/webserver/handler.go

View check run for this annotation

Codecov / codecov/patch

internal/webserver/handler.go#L115

Added line #L115 was not covered by tests

if r.Method != "" && r.Method != "GET" && !account.Owner {
return fmt.Errorf("account level is not sufficient")
}
account, err := h.dependencies.Domains.Auth.CheckToken(r.Context(), authParts[1])
if err != nil {
return fmt.Errorf("session has been expired")

Check warning on line 119 in internal/webserver/handler.go

View check run for this annotation

Codecov / codecov/patch

internal/webserver/handler.go#L117-L119

Added lines #L117 - L119 were not covered by tests
}

if r.Method != "" && r.Method != "GET" && !account.Owner {
return fmt.Errorf("account level is not sufficient")

Check warning on line 123 in internal/webserver/handler.go

View check run for this annotation

Codecov / codecov/patch

internal/webserver/handler.go#L122-L123

Added lines #L122 - L123 were not covered by tests
}

h.dependencies.Log.WithFields(logrus.Fields{
"username": account.Username,
"method": r.Method,
"path": r.URL.Path,
}).Info("allowing legacy api access using JWT token")
h.dependencies.Log.WithFields(logrus.Fields{
"username": account.Username,
"method": r.Method,
"path": r.URL.Path,
}).Info("allowing legacy api access using JWT token")

Check warning on line 130 in internal/webserver/handler.go

View check run for this annotation

Codecov / codecov/patch

internal/webserver/handler.go#L126-L130

Added lines #L126 - L130 were not covered by tests

return nil
return nil

Check warning on line 132 in internal/webserver/handler.go

View check run for this annotation

Codecov / codecov/patch

internal/webserver/handler.go#L132

Added line #L132 was not covered by tests
}
}

sessionID := h.GetSessionID(r)
if sessionID == "" {
return fmt.Errorf("session is not exist")
}
h.dependencies.Log.Debugf("get session id is %s", sessionID)

Check warning on line 140 in internal/webserver/handler.go

View check run for this annotation

Codecov / codecov/patch

internal/webserver/handler.go#L140

Added line #L140 was not covered by tests

// Make sure session is not expired yet
val, found := h.SessionCache.Get(sessionID)
Expand Down
Loading