fleet/server/service/middleware/auth/http_auth.go
Victor Lyuboslavsky c88cc953fb
Refactor endpoint_utils for modularization (#36484)
Resolves #37192

Separating generic endpoint_utils middleware logic from domain-specific
business logic. New bounded contexts would share the generic logic and
implement their own domain-specific logic. The two approaches used in
this PR are:
- Use common `platform` types
- Use interfaces

In the next PR we will move `endpointer_utils`, `authzcheck` and
`ratelimit` into `platform` directory.

# Checklist for submitter

- [x] Added changes file

## Testing

- [x] Added/updated tests
- [x] QA'd all new/changed functionality manually



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Refactor**
* Restructured internal error handling and context management to support
bounded context architecture.
* Improved error context collection and telemetry observability through
a provider-based mechanism.
* Decoupled licensing and authentication concerns into interfaces for
better modularity.

* **Chores**
* Updated internal package dependencies to align with new architectural
boundaries.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2025-12-31 09:12:00 -06:00

43 lines
1.4 KiB
Go

package auth
import (
"context"
"net/http"
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
"github.com/fleetdm/fleet/v4/server/contexts/logging"
"github.com/fleetdm/fleet/v4/server/contexts/token"
"github.com/fleetdm/fleet/v4/server/contexts/viewer"
"github.com/fleetdm/fleet/v4/server/fleet"
kithttp "github.com/go-kit/kit/transport/http"
)
// SetRequestsContexts updates the request with necessary context values for a request
func SetRequestsContexts(svc fleet.Service) kithttp.RequestFunc {
return func(ctx context.Context, r *http.Request) context.Context {
bearer := token.FromHTTPRequest(r)
ctx = token.NewContext(ctx, bearer)
if bearer != "" {
v, err := AuthViewer(ctx, string(bearer), svc)
if err == nil {
ctx = viewer.NewContext(ctx, *v)
// Register viewer as error context provider for ctxerr enrichment
ctx = ctxerr.AddErrorContextProvider(ctx, v)
// Register viewer as user emailer for logging
ctx = logging.WithUserEmailer(ctx, v)
}
}
ctx = logging.NewContext(ctx, &logging.LoggingContext{})
ctx = logging.WithStartTime(ctx)
return ctx
}
}
func SetRequestsContextMiddleware(svc fleet.Service, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := kithttp.PopulateRequestContext(r.Context(), r)
ctx = SetRequestsContexts(svc)(ctx, r)
next.ServeHTTP(w, r.WithContext(ctx))
})
}