MCPcopy Create free account
hub / github.com/cloudbase/garm / Middleware

Method Middleware

auth/instance_middleware.go:182–271  ·  view source on GitHub ↗

Middleware implements the middleware interface

(next http.Handler)

Source from the content-addressed store, hash-verified

180
181// Middleware implements the middleware interface
182func (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)

Callers

nothing calls this directly

Calls 9

claimsToContextMethod · 0.95
invalidAuthResponseFunction · 0.85
SetInstanceAuthTokenFunction · 0.85
InstanceIDFunction · 0.85
InstanceRunnerStatusFunction · 0.85
InstanceParamsFunction · 0.85
InstanceNameFunction · 0.85
GetMethod · 0.45
WithContextMethod · 0.45

Tested by

no test coverage detected