Middleware implements the middleware interface
(next http.Handler)
| 180 | |
| 181 | // Middleware implements the middleware interface |
| 182 | func (amw *instanceMiddleware) Middleware(next http.Handler) http.Handler { |
| 183 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 184 | // nolint:golangci-lint,godox |
| 185 | // TODO: Log error details when authentication fails |
| 186 | ctx := r.Context() |
| 187 | authorizationHeader := r.Header.Get("authorization") |
| 188 | if authorizationHeader == "" { |
| 189 | invalidAuthResponse(ctx, w) |
| 190 | return |
| 191 | } |
| 192 | |
| 193 | bearerToken := strings.Split(authorizationHeader, " ") |
| 194 | if len(bearerToken) != 2 { |
| 195 | invalidAuthResponse(ctx, w) |
| 196 | return |
| 197 | } |
| 198 | |
| 199 | claims := &InstanceJWTClaims{} |
| 200 | token, err := jwt.ParseWithClaims(bearerToken[1], claims, func(token *jwt.Token) (interface{}, error) { |
| 201 | if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { |
| 202 | return nil, fmt.Errorf("invalid signing method") |
| 203 | } |
| 204 | return []byte(amw.cfg.Secret), nil |
| 205 | }) |
| 206 | if err != nil { |
| 207 | invalidAuthResponse(ctx, w) |
| 208 | return |
| 209 | } |
| 210 | |
| 211 | if !token.Valid { |
| 212 | invalidAuthResponse(ctx, w) |
| 213 | return |
| 214 | } |
| 215 | if claims.IsAgent { |
| 216 | invalidAuthResponse(ctx, w) |
| 217 | return |
| 218 | } |
| 219 | |
| 220 | ctx, err = amw.claimsToContext(ctx, claims) |
| 221 | if err != nil { |
| 222 | invalidAuthResponse(ctx, w) |
| 223 | return |
| 224 | } |
| 225 | ctx = SetInstanceAuthToken(ctx, bearerToken[1]) |
| 226 | |
| 227 | if InstanceID(ctx) == "" { |
| 228 | invalidAuthResponse(ctx, w) |
| 229 | return |
| 230 | } |
| 231 | |
| 232 | runnerStatus := InstanceRunnerStatus(ctx) |
| 233 | if runnerStatus != params.RunnerInstalling && runnerStatus != params.RunnerPending { |
| 234 | // Instances that have finished installing can no longer authenticate to the API |
| 235 | invalidAuthResponse(ctx, w) |
| 236 | return |
| 237 | } |
| 238 | |
| 239 | instanceParams, err := InstanceParams(ctx) |
nothing calls this directly
no test coverage detected