55package private
66
77import (
8+ "crypto/subtle"
89 "net/http"
910 "strings"
1011
@@ -18,22 +19,23 @@ import (
1819 chi_middleware "github.com/go-chi/chi/v5/middleware"
1920)
2021
21- // CheckInternalToken check internal token is set
22- func CheckInternalToken (next http.Handler ) http.Handler {
22+ func authInternal (next http.Handler ) http.Handler {
2323 return http .HandlerFunc (func (w http.ResponseWriter , req * http.Request ) {
24- tokens := req .Header .Get ("Authorization" )
25- fields := strings .SplitN (tokens , " " , 2 )
2624 if setting .InternalToken == "" {
2725 log .Warn (`The INTERNAL_TOKEN setting is missing from the configuration file: %q, internal API can't work.` , setting .CustomConf )
2826 http .Error (w , http .StatusText (http .StatusForbidden ), http .StatusForbidden )
2927 return
3028 }
31- if len (fields ) != 2 || fields [0 ] != "Bearer" || fields [1 ] != setting .InternalToken {
29+
30+ tokens := req .Header .Get ("X-Gitea-Internal-Auth" ) // TODO: use something like JWT or HMAC to avoid passing the token in the clear
31+ after , found := strings .CutPrefix (tokens , "Bearer " )
32+ authSucceeded := found && subtle .ConstantTimeCompare ([]byte (after ), []byte (setting .InternalToken )) == 1
33+ if ! authSucceeded {
3234 log .Debug ("Forbidden attempt to access internal url: Authorization header: %s" , tokens )
3335 http .Error (w , http .StatusText (http .StatusForbidden ), http .StatusForbidden )
34- } else {
35- next .ServeHTTP (w , req )
36+ return
3637 }
38+ next .ServeHTTP (w , req )
3739 })
3840}
3941
@@ -51,7 +53,7 @@ func bind[T any](_ T) any {
5153func Routes () * web.Route {
5254 r := web .NewRoute ()
5355 r .Use (context .PrivateContexter ())
54- r .Use (CheckInternalToken )
56+ r .Use (authInternal )
5557 // Log the real ip address of the request from SSH is really helpful for diagnosing sometimes.
5658 // Since internal API will be sent only from Gitea sub commands and it's under control (checked by InternalToken), we can trust the headers.
5759 r .Use (chi_middleware .RealIP )
0 commit comments