mirror of
https://github.com/mudler/LocalAI.git
synced 2026-05-24 08:38:02 -04:00
fix(auth): expand tryAuthenticate godoc and cover Bearer-session branch
Documents all three context-keys side effects (auth_source, auth_apikey, _auth_session) plus the split of responsibilities with the parent Middleware. Adds a test for the Bearer-as-session-token classification so future regressions there fail loudly. Refs: #9862 Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
This commit is contained in:
@@ -438,8 +438,19 @@ func RequireQuota(db *gorm.DB) echo.MiddlewareFunc {
|
||||
}
|
||||
|
||||
// tryAuthenticate attempts to authenticate the request using the database.
|
||||
// On success it returns the user and, as a side effect, populates the
|
||||
// auth_source and (for named-key paths) auth_apikey context values.
|
||||
//
|
||||
// On success it returns the user and, as a side effect, sets the following
|
||||
// values on the Echo context:
|
||||
// - contextKeySource ("auth_source"): always set, one of UsageSourceWeb /
|
||||
// UsageSourceAPIKey. UsageSourceLegacy is set elsewhere by the parent
|
||||
// Middleware when a legacy env key matches.
|
||||
// - contextKeyAPIKey ("auth_apikey"): set to the resolved *UserAPIKey for
|
||||
// named-key branches (Bearer, x-api-key, xi-api-key, token cookie).
|
||||
// - "_auth_session": session record, used by Middleware to drive cookie
|
||||
// rotation. Only set on the session-cookie branch.
|
||||
//
|
||||
// contextKeyUser and contextKeyRole are populated by the parent Middleware
|
||||
// after this function returns.
|
||||
func tryAuthenticate(c echo.Context, db *gorm.DB, appConfig *config.ApplicationConfig) *User {
|
||||
hmacSecret := appConfig.Auth.APIKeyHMACSecret
|
||||
|
||||
|
||||
@@ -341,6 +341,23 @@ var _ = Describe("Auth Middleware", func() {
|
||||
Expect(p.key).To(BeNil())
|
||||
})
|
||||
|
||||
It("Bearer session token sets source=web, apikey=nil", func() {
|
||||
db := testDB()
|
||||
appConfig := config.NewApplicationConfig()
|
||||
user := createTestUser(db, "alice@example.com", auth.RoleUser, auth.ProviderLocal)
|
||||
token := createTestSession(db, user.ID)
|
||||
|
||||
var p probe
|
||||
app := probeApp(db, appConfig, &p)
|
||||
rec := doRequest(app, http.MethodGet, "/probe", withBearerToken(token))
|
||||
|
||||
Expect(rec.Code).To(Equal(http.StatusOK))
|
||||
Expect(p.user).ToNot(BeNil())
|
||||
Expect(p.user.ID).To(Equal(user.ID))
|
||||
Expect(p.source).To(Equal(auth.UsageSourceWeb))
|
||||
Expect(p.key).To(BeNil())
|
||||
})
|
||||
|
||||
It("Bearer API key sets source=apikey and exposes the resolved *UserAPIKey", func() {
|
||||
db := testDB()
|
||||
appConfig := config.NewApplicationConfig()
|
||||
|
||||
Reference in New Issue
Block a user