From 7c20cc92fa2c2b64adbe1b97cae19d711daf0494 Mon Sep 17 00:00:00 2001 From: hgaol Date: Mon, 23 Nov 2026 13:53:37 +0000 Subject: [PATCH 1/3] feat(auth): add scoped personal access tokens for existing users Add user-owned expiring and revocable credentials, strict Bearer authentication, semantic route scopes, current account resolution, recent-authentication checks, account lifecycle hooks, and default-off admin controls. Include account-settings management, HTTP documentation, and end-to-end coverage for two eligible users creating content and voting through PATs. --- Makefile | 4 +- README.md | 6 + cmd/personal_access_token_integration_test.go | 273 ++++++++ cmd/wire_gen.go | 16 +- docs/docs.go | 323 ++++++++++ docs/personal-access-tokens.md | 141 +++++ docs/swagger.json | 323 ++++++++++ docs/swagger.yaml | 197 ++++++ go.mod | 2 +- go.sum | 6 +- i18n/en_US.yaml | 64 +- internal/base/middleware/auth.go | 61 +- .../middleware/personal_access_token_auth.go | 149 +++++ .../personal_access_token_auth_test.go | 144 +++++ internal/base/middleware/provider.go | 1 + .../base/middleware/visit_img_auth_test.go | 2 +- internal/base/reason/personal_access_token.go | 25 + internal/base/translator/provider_test.go | 47 ++ internal/controller/controller.go | 1 + .../personal_access_token_controller.go | 193 ++++++ .../personal_access_token_controller_test.go | 35 ++ internal/controller/user_controller.go | 50 ++ internal/entity/auth_user_entity.go | 13 +- .../entity/personal_access_token_entity.go | 40 ++ internal/migrations/init.go | 8 +- internal/migrations/init_data.go | 1 + internal/migrations/migrations.go | 1 + internal/migrations/v36.go | 31 + internal/repo/auth/auth.go | 35 ++ .../personal_access_token_repo.go | 84 +++ internal/repo/provider.go | 2 + .../personal_access_token_repo_test.go | 78 +++ internal/repo/repo_test/repo_main_test.go | 2 +- internal/router/answer_api_router.go | 10 + .../schema/personal_access_token_schema.go | 66 ++ internal/schema/siteinfo_schema.go | 24 +- internal/schema/siteinfo_schema_test.go | 31 + internal/schema/user_schema.go | 13 +- internal/service/auth/auth.go | 27 + internal/service/content/user_service.go | 25 +- .../service/personal_access_token/scope.go | 100 +++ .../personal_access_token/scope_test.go | 58 ++ .../service/personal_access_token/service.go | 288 +++++++++ .../personal_access_token/service_test.go | 163 +++++ internal/service/provider.go | 2 + .../siteinfo_common/siteinfo_service.go | 5 +- internal/service/user_admin/user_backyard.go | 67 +- ui/package.json | 4 +- ui/pnpm-lock.yaml | 589 +++++++++++++++++- ui/src/common/interface.ts | 31 + ui/src/pages/Admin/Security/index.tsx | 34 + .../Account/components/ModifyPass/index.tsx | 25 + .../PersonalAccessTokens/index.test.tsx | 85 +++ .../Settings/PersonalAccessTokens/index.tsx | 361 +++++++++++ .../Users/Settings/components/Nav/index.tsx | 3 + ui/src/router/routes.ts | 4 + ui/src/services/client/index.ts | 1 + .../services/client/personalAccessTokens.ts | 44 ++ ui/src/stores/siteSecurity.ts | 6 + ui/src/utils/request.ts | 11 +- 60 files changed, 4362 insertions(+), 73 deletions(-) create mode 100644 cmd/personal_access_token_integration_test.go create mode 100644 docs/personal-access-tokens.md create mode 100644 internal/base/middleware/personal_access_token_auth.go create mode 100644 internal/base/middleware/personal_access_token_auth_test.go create mode 100644 internal/base/reason/personal_access_token.go create mode 100644 internal/base/translator/provider_test.go create mode 100644 internal/controller/personal_access_token_controller.go create mode 100644 internal/controller/personal_access_token_controller_test.go create mode 100644 internal/entity/personal_access_token_entity.go create mode 100644 internal/migrations/v36.go create mode 100644 internal/repo/personal_access_token/personal_access_token_repo.go create mode 100644 internal/repo/repo_test/personal_access_token_repo_test.go create mode 100644 internal/schema/personal_access_token_schema.go create mode 100644 internal/service/personal_access_token/scope.go create mode 100644 internal/service/personal_access_token/scope_test.go create mode 100644 internal/service/personal_access_token/service.go create mode 100644 internal/service/personal_access_token/service_test.go create mode 100644 ui/src/pages/Users/Settings/PersonalAccessTokens/index.test.tsx create mode 100644 ui/src/pages/Users/Settings/PersonalAccessTokens/index.tsx create mode 100644 ui/src/services/client/personalAccessTokens.ts diff --git a/Makefile b/Makefile index af1fe3188..3655b6875 100644 --- a/Makefile +++ b/Makefile @@ -31,10 +31,10 @@ universal: generate generate: @$(GO) get github.com/swaggo/swag/cmd/swag@v1.16.3 - @$(GO) get github.com/google/wire/cmd/wire@v0.5.0 + @$(GO) get github.com/google/wire/cmd/wire@v0.7.0 @$(GO) get go.uber.org/mock/mockgen@v0.6.0 @$(GO) install github.com/swaggo/swag/cmd/swag@v1.16.3 - @$(GO) install github.com/google/wire/cmd/wire@v0.5.0 + @$(GO) install github.com/google/wire/cmd/wire@v0.7.0 @$(GO) install go.uber.org/mock/mockgen@v0.6.0 @$(GO) generate ./... @$(GO) mod tidy diff --git a/README.md b/README.md index 0d958e007..2cb423707 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,12 @@ We value your feedback and suggestions to improve our documentation. If you have You can also check out the [plugins here](https://answer.apache.org/plugins). +### Personal access tokens + +Administrators can enable **Personal access tokens** under **Admin → Security**. Users can create scoped, expiring tokens from **Settings → Personal access tokens** to use existing REST endpoints as their own account. + +See [Personal access tokens](docs/personal-access-tokens.md) for setup, scopes, security behavior, and HTTP examples. + ## Building from Source ### Prerequisites diff --git a/cmd/personal_access_token_integration_test.go b/cmd/personal_access_token_integration_test.go new file mode 100644 index 000000000..71c3702b7 --- /dev/null +++ b/cmd/personal_access_token_integration_test.go @@ -0,0 +1,273 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package answercmd + +import ( + "bytes" + "context" + "encoding/json" + "net" + "net/http" + "net/url" + "os" + "os/exec" + "path/filepath" + "strconv" + "testing" + "time" + + bundles "github.com/apache/answer/i18n" + "github.com/apache/answer/internal/base/conf" + "github.com/apache/answer/internal/base/data" + serverconfig "github.com/apache/answer/internal/base/server" + "github.com/apache/answer/internal/base/translator" + "github.com/apache/answer/internal/entity" + "github.com/apache/answer/internal/migrations" + "github.com/apache/answer/internal/router" + "github.com/apache/answer/internal/schema" + pat "github.com/apache/answer/internal/service/personal_access_token" + "github.com/apache/answer/internal/service/service_config" + "github.com/stretchr/testify/require" + "golang.org/x/crypto/bcrypt" + "gopkg.in/yaml.v3" +) + +// TestPATHTTPServerProcess runs the real application in an isolated test process. +func TestPATHTTPServerProcess(t *testing.T) { + if os.Getenv("ANSWER_PAT_TEST_PROCESS") != "1" { + return + } + dir := os.Getenv("ANSWER_PAT_TEST_DATA") + logPath = filepath.Join(dir, "logs") + os.Args = []string{"answer", "run", "-C", dir} + Main() +} + +func TestPersonalAccessTokenHTTPWorkflow(t *testing.T) { + api := newPATHTTPFixture(t) + admin := api.login(t, "admin@example.test") + member := api.login(t, "member@example.test") + var security schema.SiteSecurityReq + api.request(t, http.MethodGet, "/answer/admin/api/siteinfo/security", admin, nil, http.StatusOK, &security) + require.False(t, security.PersonalAccessTokensEnabled) + + create := func(session string, scopes []string, status int) schema.PersonalAccessTokenCreateResp { + t.Helper() + var result schema.PersonalAccessTokenCreateResp + api.request(t, http.MethodPost, "/answer/api/v1/personal-access-tokens", session, schema.PersonalAccessTokenCreateReq{ + Name: "http-fixture", Scopes: scopes, ExpiresAt: time.Now().Add(time.Hour).Unix(), + }, status, &result) + return result + } + scopes := []string{pat.ScopeQuestionRead, pat.ScopeQuestionCreate, pat.ScopeAnswerRead, pat.ScopeAnswerCreate, pat.ScopeVoteWrite} + create(member, scopes, http.StatusForbidden) + security.PersonalAccessTokensEnabled = true + api.request(t, http.MethodPut, "/answer/admin/api/siteinfo/security", admin, security, http.StatusOK, nil) + adminPAT := create(admin, scopes, http.StatusOK) + memberPAT := create(member, scopes, http.StatusOK) + readPAT := create(admin, []string{pat.ScopeQuestionRead}, http.StatusOK) + adminBearer, memberBearer := "Bearer "+adminPAT.Token, "Bearer "+memberPAT.Token + for bearer, owner := range map[string]string{adminBearer: "1", memberBearer: "2"} { + var current schema.PersonalAccessTokenCurrentResp + api.request(t, http.MethodGet, "/answer/api/v1/personal-access-tokens/current", bearer, nil, http.StatusOK, ¤t) + require.Equal(t, owner, current.User.ID) + } + + var question struct { + ID string `json:"id"` + } + questionBody := map[string]any{ + "title": "How does delegated PAT access preserve account permissions?", + "content": "An eligible fixture user creates this question using its own scoped personal access token.", + "tags": []map[string]string{{"slug_name": "pat-fixture", "display_name": "PAT fixture"}}, + } + api.request(t, http.MethodPost, "/answer/api/v1/question", "Bearer "+readPAT.Token, questionBody, http.StatusForbidden, nil) + api.request(t, http.MethodPost, "/answer/api/v1/question", memberBearer, questionBody, http.StatusOK, &question) + require.NotEmpty(t, question.ID) + var answer schema.GetAnswerInfoResp + api.request(t, http.MethodPost, "/answer/api/v1/answer", adminBearer, map[string]string{ + "question_id": question.ID, "content": "The token limits routes while the existing account permissions continue to govern the action.", + }, http.StatusOK, &answer) + require.NotNil(t, answer.Info) + + // Each owner can vote on the other user's content, then retract the vote. + for direction, count := range map[string]int{"up": 1, "down": -1} { + for bearer, objectID := range map[string]string{adminBearer: question.ID, memberBearer: answer.Info.ID} { + var vote schema.VoteResp + api.request(t, http.MethodPost, "/answer/api/v1/vote/"+direction, bearer, + map[string]any{"object_id": objectID, "is_cancel": false}, http.StatusOK, &vote) + require.EqualValues(t, count, vote.Votes) + api.request(t, http.MethodPost, "/answer/api/v1/vote/"+direction, bearer, + map[string]any{"object_id": objectID, "is_cancel": true}, http.StatusOK, &vote) + require.Zero(t, vote.Votes) + } + } + api.request(t, http.MethodPost, "/answer/api/v1/vote/up", memberBearer, + map[string]string{"object_id": question.ID}, http.StatusBadRequest, nil) + api.request(t, http.MethodGet, "/answer/api/v1/personal-access-tokens", adminBearer, nil, http.StatusForbidden, nil) + api.request(t, http.MethodGet, "/answer/api/v1/question/info?id="+question.ID, memberPAT.Token, nil, http.StatusUnauthorized, nil) + api.request(t, http.MethodGet, "/answer/api/v1/question/info?id="+question.ID+"&Authorization="+url.QueryEscape(memberPAT.Token), "", nil, http.StatusUnauthorized, nil) + + // A session belonging to another user cannot revoke this owner's PAT. + revokePath := "/answer/api/v1/personal-access-tokens?id=" + strconv.FormatInt(memberPAT.ID, 10) + api.request(t, http.MethodDelete, revokePath, admin, nil, http.StatusOK, nil) + api.request(t, http.MethodGet, "/answer/api/v1/personal-access-tokens/current", memberBearer, nil, http.StatusOK, nil) + security.PersonalAccessTokensEnabled = false + api.request(t, http.MethodPut, "/answer/admin/api/siteinfo/security", admin, security, http.StatusOK, nil) + for _, bearer := range []string{adminBearer, memberBearer} { + api.request(t, http.MethodGet, "/answer/api/v1/personal-access-tokens/current", bearer, nil, http.StatusForbidden, nil) + } + security.PersonalAccessTokensEnabled = true + api.request(t, http.MethodPut, "/answer/admin/api/siteinfo/security", admin, security, http.StatusOK, nil) + api.request(t, http.MethodGet, "/answer/api/v1/personal-access-tokens/current", memberBearer, nil, http.StatusOK, nil) + api.request(t, http.MethodDelete, revokePath, member, nil, http.StatusOK, nil) + api.request(t, http.MethodGet, "/answer/api/v1/personal-access-tokens/current", memberBearer, nil, http.StatusUnauthorized, nil) + security.PersonalAccessTokensEnabled = false + api.request(t, http.MethodPut, "/answer/admin/api/siteinfo/security", admin, security, http.StatusOK, nil) + security.PersonalAccessTokensEnabled = true + api.request(t, http.MethodPut, "/answer/admin/api/siteinfo/security", admin, security, http.StatusOK, nil) + api.request(t, http.MethodGet, "/answer/api/v1/personal-access-tokens/current", memberBearer, nil, http.StatusUnauthorized, nil) + api.request(t, http.MethodGet, "/answer/api/v1/personal-access-tokens/current", adminBearer, nil, http.StatusOK, nil) +} + +type patHTTPFixture struct { + url string + client *http.Client +} + +const patFixturePassword = "fixture-password-only" + +func (f *patHTTPFixture) login(t *testing.T, email string) string { + t.Helper() + var result schema.UserLoginResp + f.request(t, http.MethodPost, "/answer/api/v1/user/login/email", "", map[string]string{ + "e_mail": email, "pass": patFixturePassword, + }, http.StatusOK, &result) + f.request(t, http.MethodPost, "/answer/api/v1/user/reauthenticate", result.AccessToken, + map[string]string{"password": patFixturePassword}, http.StatusOK, nil) + return result.AccessToken +} + +func (f *patHTTPFixture) request(t *testing.T, method, path, token string, body any, status int, out any) { + t.Helper() + var payload bytes.Buffer + if body != nil { + require.NoError(t, json.NewEncoder(&payload).Encode(body)) + } + request, err := http.NewRequestWithContext(t.Context(), method, f.url+path, &payload) + require.NoError(t, err) + if body != nil { + request.Header.Set("Content-Type", "application/json") + } + request.Header.Set("Authorization", token) + response, err := f.client.Do(request) + require.NoError(t, err) + defer func() { require.NoError(t, response.Body.Close()) }() + var envelope struct { + Reason string `json:"reason"` + Data json.RawMessage `json:"data"` + } + require.NoError(t, json.NewDecoder(response.Body).Decode(&envelope)) + require.Equal(t, status, response.StatusCode, "%s %s: %s", method, path, envelope.Reason) + if out != nil && status == http.StatusOK { + require.NoError(t, json.Unmarshal(envelope.Data, out)) + } +} + +func newPATHTTPFixture(t *testing.T) *patHTTPFixture { + t.Helper() + dir := t.TempDir() + for _, name := range []string{"conf", "cache", "i18n", "uploads", "logs"} { + require.NoError(t, os.MkdirAll(filepath.Join(dir, name), 0o700)) + } + entries, err := bundles.I18n.ReadDir(".") + require.NoError(t, err) + for _, entry := range entries { + if entry.IsDir() || filepath.Ext(entry.Name()) != ".yaml" { + continue + } + content, readErr := bundles.I18n.ReadFile(entry.Name()) + require.NoError(t, readErr) + require.NoError(t, os.WriteFile(filepath.Join(dir, "i18n", entry.Name()), content, 0o600)) + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + address := listener.Addr().String() + require.NoError(t, listener.Close()) + dbConfig := &data.Database{Driver: "sqlite3", Connection: filepath.Join(dir, "answer.db")} + db, err := data.NewDB(false, dbConfig) + require.NoError(t, err) + require.NoError(t, migrations.NewMentor(t.Context(), db, &migrations.InitNeedUserInputData{ + Language: "en_US", SiteName: "PAT fixture", SiteURL: "http://" + address, + ContactEmail: "admin@example.test", AdminName: "pat-admin", + AdminEmail: "admin@example.test", AdminPassword: patFixturePassword, + ExternalContentDisplay: "always_display", + }).InitDB()) + password, err := bcrypt.GenerateFromPassword([]byte(patFixturePassword), bcrypt.MinCost) + require.NoError(t, err) + _, err = db.Insert(&entity.User{ID: "2", Username: "pat-member", DisplayName: "PAT member", + EMail: "member@example.test", Pass: string(password), MailStatus: entity.EmailStatusAvailable, + Status: entity.UserStatusAvailable, Rank: 10000}) + require.NoError(t, err) + _, err = db.Insert(&entity.UserRoleRel{UserID: "2", RoleID: 1}) + require.NoError(t, err) + _, err = db.Insert(&entity.Tag{ID: "10030000000009999", SlugName: "pat-fixture", DisplayName: "PAT fixture", + UserID: "1", Status: entity.TagStatusAvailable, Recommend: true}) + require.NoError(t, err) + require.NoError(t, db.Close()) + config, err := yaml.Marshal(&conf.AllConfig{ + Server: &conf.Server{HTTP: &serverconfig.HTTP{Addr: address}}, + Data: &conf.Data{Database: dbConfig, Cache: &data.CacheConf{FilePath: filepath.Join(dir, "cache", "cache.db")}}, + I18n: &translator.I18n{BundleDir: filepath.Join(dir, "i18n")}, + Swaggerui: &router.SwaggerConfig{}, UI: &serverconfig.UI{}, + ServiceConfig: &service_config.ServiceConfig{UploadPath: filepath.Join(dir, "uploads"), + CleanOrphanUploadsPeriodHours: 48, PurgeDeletedFilesPeriodDays: 30}, + }) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(dir, "conf", "config.yaml"), config, 0o600)) + ctx, cancel := context.WithCancel(t.Context()) + process := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestPATHTTPServerProcess$") + process.Env = append(os.Environ(), "ANSWER_PAT_TEST_PROCESS=1", "ANSWER_PAT_TEST_DATA="+dir, + "SITE_ADDR=", "SWAGGER_HOST=", "SWAGGER_ADDRESS_PORT=", "ANSWER_TEMPLATE_PATH=") + logFile, err := os.Create(filepath.Join(dir, "server.log")) + require.NoError(t, err) + process.Stdout, process.Stderr = logFile, logFile + require.NoError(t, process.Start()) + t.Cleanup(func() { + cancel() + _ = process.Wait() + require.NoError(t, logFile.Close()) + if t.Failed() { + logs, readErr := os.ReadFile(logFile.Name()) + require.NoError(t, readErr) + t.Log(string(logs)) + } + }) + fixture := &patHTTPFixture{url: "http://" + address, client: &http.Client{Timeout: 5 * time.Second}} + require.Eventually(t, func() bool { + response, requestErr := fixture.client.Get(fixture.url + "/healthz") + if requestErr != nil { + return false + } + _ = response.Body.Close() + return response.StatusCode == http.StatusOK + }, 20*time.Second, 100*time.Millisecond) + return fixture +} diff --git a/cmd/wire_gen.go b/cmd/wire_gen.go index 66e162784..1e34dac8c 100644 --- a/cmd/wire_gen.go +++ b/cmd/wire_gen.go @@ -22,7 +22,7 @@ // Code generated by Wire. DO NOT EDIT. -//go:generate go run github.com/google/wire/cmd/wire +//go:generate go run -mod=mod github.com/google/wire/cmd/wire package answercmd @@ -54,6 +54,7 @@ import ( "github.com/apache/answer/internal/repo/limit" "github.com/apache/answer/internal/repo/meta" notification2 "github.com/apache/answer/internal/repo/notification" + "github.com/apache/answer/internal/repo/personal_access_token" "github.com/apache/answer/internal/repo/plugin_config" "github.com/apache/answer/internal/repo/question" "github.com/apache/answer/internal/repo/rank" @@ -100,6 +101,7 @@ import ( "github.com/apache/answer/internal/service/notification" "github.com/apache/answer/internal/service/notification_common" "github.com/apache/answer/internal/service/object_info" + personal_access_token2 "github.com/apache/answer/internal/service/personal_access_token" "github.com/apache/answer/internal/service/plugin_common" "github.com/apache/answer/internal/service/question_common" rank2 "github.com/apache/answer/internal/service/rank" @@ -191,7 +193,9 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, eventqueueService := eventqueue.NewService() fileRecordRepo := file_record.NewFileRecordRepo(dataData) fileRecordService := file_record2.NewFileRecordService(fileRecordRepo, revisionRepo, serviceConf, siteInfoCommonService, userCommon) - userService := content.NewUserService(userRepo, userActiveActivityRepo, activityRepo, emailService, authService, siteInfoCommonService, userRoleRelService, userCommon, userExternalLoginService, userNotificationConfigRepo, userNotificationConfigService, questionCommon, eventqueueService, fileRecordService) + repository := personal_access_token.NewRepository(dataData) + personal_access_tokenService := personal_access_token2.NewService(repository) + userService := content.NewUserService(userRepo, userActiveActivityRepo, activityRepo, emailService, authService, siteInfoCommonService, userRoleRelService, userCommon, userExternalLoginService, userNotificationConfigRepo, userNotificationConfigService, questionCommon, eventqueueService, fileRecordService, personal_access_tokenService) captchaRepo := captcha.NewCaptchaRepo(dataData) captchaService := action.NewCaptchaService(captchaRepo) userController := controller.NewUserController(authService, userService, captchaService, emailService, siteInfoCommonService, userNotificationConfigService) @@ -244,7 +248,7 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, notificationRepo := notification2.NewNotificationRepo(dataData) pluginUserConfigRepo := plugin_config.NewPluginUserConfigRepo(dataData) badgeAwardRepo := badge_award.NewBadgeAwardRepo(dataData, uniqueIDRepo) - userAdminService := user_admin.NewUserAdminService(userAdminRepo, userRoleRelService, authService, userCommon, userActiveActivityRepo, siteInfoCommonService, emailService, questionRepo, answerRepo, commentCommonRepo, userExternalLoginRepo, notificationRepo, pluginUserConfigRepo, badgeAwardRepo, apiKeyRepo) + userAdminService := user_admin.NewUserAdminService(userAdminRepo, userRoleRelService, authService, userCommon, userActiveActivityRepo, siteInfoCommonService, emailService, questionRepo, answerRepo, commentCommonRepo, userExternalLoginRepo, notificationRepo, pluginUserConfigRepo, badgeAwardRepo, apiKeyRepo, personal_access_tokenService) userAdminController := controller_admin.NewUserAdminController(userAdminService) reasonRepo := reason.NewReasonRepo(configService) reasonService := reason2.NewReasonService(reasonRepo) @@ -293,10 +297,12 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, aiController := controller.NewAIController(searchService, siteInfoCommonService, tagCommonService, questionCommon, commentRepo, userCommon, answerRepo, mcpController, aiConversationService, featureToggleService) aiConversationController := controller.NewAIConversationController(aiConversationService, featureToggleService) aiConversationAdminController := controller_admin.NewAIConversationAdminController(aiConversationService, featureToggleService) - answerAPIRouter := router.NewAnswerAPIRouter(langController, userController, commentController, reportController, voteController, tagController, followController, collectionController, questionController, answerController, searchController, revisionController, rankController, userAdminController, reasonController, themeController, siteInfoController, controllerSiteInfoController, notificationController, dashboardController, uploadController, activityController, roleController, pluginController, permissionController, userPluginController, reviewController, metaController, badgeController, controller_adminBadgeController, adminAPIKeyController, aiController, aiConversationController, aiConversationAdminController, mcpController) + personalAccessTokenController := controller.NewPersonalAccessTokenController(personal_access_tokenService, siteInfoCommonService, userCommon) + answerAPIRouter := router.NewAnswerAPIRouter(langController, userController, commentController, reportController, voteController, tagController, followController, collectionController, questionController, answerController, searchController, revisionController, rankController, userAdminController, reasonController, themeController, siteInfoController, controllerSiteInfoController, notificationController, dashboardController, uploadController, activityController, roleController, pluginController, permissionController, userPluginController, reviewController, metaController, badgeController, controller_adminBadgeController, adminAPIKeyController, aiController, aiConversationController, aiConversationAdminController, mcpController, personalAccessTokenController) swaggerRouter := router.NewSwaggerRouter(swaggerConf) uiRouter := router.NewUIRouter(controllerSiteInfoController, siteInfoCommonService) - authUserMiddleware := middleware.NewAuthUserMiddleware(authService, siteInfoCommonService) + patRequestAuthorizer := middleware.NewPATRequestAuthorizer(personal_access_tokenService, authService, siteInfoCommonService) + authUserMiddleware := middleware.NewAuthUserMiddleware(authService, siteInfoCommonService, patRequestAuthorizer) avatarMiddleware := middleware.NewAvatarMiddleware(serviceConf, uploaderService) shortIDMiddleware := middleware.NewShortIDMiddleware(siteInfoCommonService) templateRenderController := templaterender.NewTemplateRenderController(questionService, userService, tagService, answerService, commentService, siteInfoCommonService, questionRepo) diff --git a/docs/docs.go b/docs/docs.go index be366e41f..22244307f 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -4684,6 +4684,145 @@ const docTemplate = `{ } } }, + "/answer/api/v1/personal-access-tokens": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "tags": [ + "Personal Access Token" + ], + "summary": "List personal access tokens", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/handler.RespBody" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/schema.PersonalAccessTokenInfo" + } + } + } + } + ] + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "tags": [ + "Personal Access Token" + ], + "summary": "Create a personal access token", + "parameters": [ + { + "description": "personal access token", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/schema.PersonalAccessTokenCreateReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/handler.RespBody" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/schema.PersonalAccessTokenCreateResp" + } + } + } + ] + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "tags": [ + "Personal Access Token" + ], + "summary": "Revoke a personal access token", + "parameters": [ + { + "type": "integer", + "description": "personal access token id", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/handler.RespBody" + } + } + } + } + }, + "/answer/api/v1/personal-access-tokens/current": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "tags": [ + "Personal Access Token" + ], + "summary": "Inspect the current personal access token", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/handler.RespBody" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/schema.PersonalAccessTokenCurrentResp" + } + } + } + ] + } + } + } + } + }, "/answer/api/v1/personal/answer/page": { "get": { "security": [ @@ -7953,6 +8092,38 @@ const docTemplate = `{ } } }, + "/answer/api/v1/user/reauthenticate": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "tags": [ + "User" + ], + "summary": "Reauthenticate the current user", + "parameters": [ + { + "description": "reauthentication", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/schema.UserReauthenticateReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/handler.RespBody" + } + } + } + } + }, "/answer/api/v1/user/register/email": { "post": { "description": "UserRegisterByEmail", @@ -10941,6 +11112,122 @@ const docTemplate = `{ } } }, + "schema.PersonalAccessTokenCreateReq": { + "type": "object", + "required": [ + "expires_at", + "name", + "scopes" + ], + "properties": { + "expires_at": { + "type": "integer" + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "scopes": { + "type": "array", + "minItems": 1, + "items": { + "type": "string" + } + } + } + }, + "schema.PersonalAccessTokenCreateResp": { + "type": "object", + "properties": { + "created_at": { + "type": "integer" + }, + "expires_at": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "revoked_at": { + "type": "integer" + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + } + }, + "status": { + "type": "string" + }, + "token": { + "type": "string" + }, + "token_suffix": { + "type": "string" + } + } + }, + "schema.PersonalAccessTokenCurrentResp": { + "type": "object", + "properties": { + "token": { + "$ref": "#/definitions/schema.PersonalAccessTokenInfo" + }, + "user": { + "$ref": "#/definitions/schema.PersonalAccessTokenUserInfo" + } + } + }, + "schema.PersonalAccessTokenInfo": { + "type": "object", + "properties": { + "created_at": { + "type": "integer" + }, + "expires_at": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "revoked_at": { + "type": "integer" + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + } + }, + "status": { + "type": "string" + }, + "token_suffix": { + "type": "string" + } + } + }, + "schema.PersonalAccessTokenUserInfo": { + "type": "object", + "properties": { + "display_name": { + "type": "string" + }, + "id": { + "type": "string" + }, + "username": { + "type": "string" + } + } + }, "schema.PostRenderReq": { "type": "object", "properties": { @@ -12250,6 +12537,14 @@ const docTemplate = `{ }, "login_required": { "type": "boolean" + }, + "pat_reauthentication_window_minutes": { + "type": "integer", + "maximum": 120, + "minimum": 5 + }, + "personal_access_tokens_enabled": { + "type": "boolean" } } }, @@ -12271,6 +12566,14 @@ const docTemplate = `{ }, "login_required": { "type": "boolean" + }, + "pat_reauthentication_window_minutes": { + "type": "integer", + "maximum": 120, + "minimum": 5 + }, + "personal_access_tokens_enabled": { + "type": "boolean" } } }, @@ -13316,6 +13619,9 @@ const docTemplate = `{ "type": "string", "maxLength": 32, "minLength": 8 + }, + "revoke_personal_access_tokens": { + "type": "boolean" } } }, @@ -13384,6 +13690,23 @@ const docTemplate = `{ } } }, + "schema.UserReauthenticateReq": { + "type": "object", + "required": [ + "password" + ], + "properties": { + "captcha_code": { + "type": "string" + }, + "captcha_id": { + "type": "string" + }, + "password": { + "type": "string" + } + } + }, "schema.UserRegisterReq": { "type": "object", "required": [ diff --git a/docs/personal-access-tokens.md b/docs/personal-access-tokens.md new file mode 100644 index 000000000..1504af821 --- /dev/null +++ b/docs/personal-access-tokens.md @@ -0,0 +1,141 @@ + + +# Personal access tokens + +A personal access token (PAT) lets an HTTP client act as an existing Answer +user. The token's scopes limit the operations it can request. The user's +current permissions, reputation, account status, visibility rules, rate +limits, CAPTCHA requirements, and moderation policies still apply. + +Effective authority is the intersection of token scopes, current account +permissions, and instance policy. Administrator-managed instance API keys +remain a separate credential type. + +## Enable and create + +1. As an administrator, open **Admin → Security** and enable **Personal access + tokens**. The feature is disabled by default. +2. Set the reauthentication window if needed: the default is 60 minutes and + the supported range is 5–120 minutes. +3. As the token owner, open **Settings → Personal access tokens**. +4. Choose **Create token**, enter a name, explicitly select scopes, and choose + an expiration. Scopes are not preselected and do not imply one another. +5. Confirm the current password if recent authentication is required. Users + authenticating through an external identity provider can sign out and sign + in again through that provider. +6. Copy the secret from its one-time display. The complete secret cannot be + retrieved later; the server stores its SHA-256 digest and a display suffix. + +Expiration is mandatory and must be no more than 365 days in the future. + +| Scope | Permits | +| --- | --- | +| `question.read` | Question reads and related tag discovery | +| `question.create` | Question creation and supporting tag discovery | +| `answer.read` | Answer reads | +| `answer.create` | Answer creation | +| `vote.write` | Upvotes, downvotes, and vote retraction | + +Search requires both `question.read` and `answer.read`. A create scope does +not include the corresponding read scope. Routes outside the PAT allowlist +are denied even when the owner is an administrator. + +## Use an existing REST endpoint + +The supported transport is `Authorization: Bearer answer_pat_…`. Use your +instance's HTTPS URL and read the secret into a variable: + +```bash +export ANSWER_URL=https://answer.example.com +read -rsp 'Personal access token: ' ANSWER_PAT +echo + +curl --fail-with-body --silent --show-error \ + -H "Authorization: Bearer $ANSWER_PAT" \ + "$ANSWER_URL/answer/api/v1/personal-access-tokens/current" +``` + +Self-inspection returns the owner and token metadata, including scopes and +expiry. It does not return the complete secret. A bare token header or a +token supplied through the `Authorization` query parameter is rejected. + +For the following examples, select the matching create/read/vote scopes. +Choose an existing tag on the instance in place of `support`. + +```bash +curl --fail-with-body --silent --show-error \ + -H "Authorization: Bearer $ANSWER_PAT" \ + -H 'Content-Type: application/json' \ + -d '{"title":"How should we organize shared project knowledge?","content":"Which practices work well for maintaining useful questions and answers?","tags":[{"slug_name":"support","display_name":"support"}]}' \ + "$ANSWER_URL/answer/api/v1/question" +``` + +Use the returned question ID to post an answer: + +```bash +export QUESTION_ID='' +curl --fail-with-body --silent --show-error \ + -H "Authorization: Bearer $ANSWER_PAT" \ + -H 'Content-Type: application/json' \ + -d "{\"question_id\":\"$QUESTION_ID\",\"content\":\"Search before posting, write focused questions, and keep accepted answers current.\"}" \ + "$ANSWER_URL/answer/api/v1/answer" +``` + +For voting, choose an object owned by a different user. The owner must have +the required account permission and reputation: + +```bash +export OBJECT_ID='' +curl --fail-with-body --silent --show-error \ + -H "Authorization: Bearer $ANSWER_PAT" \ + -H 'Content-Type: application/json' \ + -d "{\"object_id\":\"$OBJECT_ID\",\"is_cancel\":false}" \ + "$ANSWER_URL/answer/api/v1/vote/up" +``` + +Use `is_cancel: true` to retract that vote. Use `/vote/down` for a downvote. +Content can enter the normal review flow, and requests can require CAPTCHA. + +## Revoke or disable + +Owners can list and revoke their own tokens in account settings. Revocation +is immediate and permanent. Expiry is also terminal. Disabling PAT support +blocks existing PAT authentication and new token creation; owners can still +revoke tokens. Re-enabling support resumes access only for tokens that remain +unexpired and unrevoked. + +Deleting an account or recovering its password revokes its PATs. The normal +password-change flow also offers a choice to revoke PATs. Current suspension, +verification, role, and external-user status continue to constrain access. + +Token management requires a browser login session; a PAT cannot create, list, +or revoke tokens. The management endpoints are: + +| Method | Path | Credential | +| --- | --- | --- | +| POST | `/answer/api/v1/user/reauthenticate` | Browser session | +| GET / POST / DELETE | `/answer/api/v1/personal-access-tokens` | Browser session | +| GET | `/answer/api/v1/personal-access-tokens/current` | PAT | + +OpenAPI describes request and response fields. Missing scope returns HTTP +403 with reason `error.personal_access_token.insufficient_scope`; disabled +access returns HTTP 403 with reason `error.feature.disabled`. Invalid, +expired, or revoked credentials return HTTP 401. Account and content policy +errors retain their existing server reasons and status codes. diff --git a/docs/swagger.json b/docs/swagger.json index 603ac04c4..c080d7164 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -4657,6 +4657,145 @@ } } }, + "/answer/api/v1/personal-access-tokens": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "tags": [ + "Personal Access Token" + ], + "summary": "List personal access tokens", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/handler.RespBody" + }, + { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/schema.PersonalAccessTokenInfo" + } + } + } + } + ] + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "tags": [ + "Personal Access Token" + ], + "summary": "Create a personal access token", + "parameters": [ + { + "description": "personal access token", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/schema.PersonalAccessTokenCreateReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/handler.RespBody" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/schema.PersonalAccessTokenCreateResp" + } + } + } + ] + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "tags": [ + "Personal Access Token" + ], + "summary": "Revoke a personal access token", + "parameters": [ + { + "type": "integer", + "description": "personal access token id", + "name": "id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/handler.RespBody" + } + } + } + } + }, + "/answer/api/v1/personal-access-tokens/current": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "tags": [ + "Personal Access Token" + ], + "summary": "Inspect the current personal access token", + "responses": { + "200": { + "description": "OK", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/handler.RespBody" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/schema.PersonalAccessTokenCurrentResp" + } + } + } + ] + } + } + } + } + }, "/answer/api/v1/personal/answer/page": { "get": { "security": [ @@ -7926,6 +8065,38 @@ } } }, + "/answer/api/v1/user/reauthenticate": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "tags": [ + "User" + ], + "summary": "Reauthenticate the current user", + "parameters": [ + { + "description": "reauthentication", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/schema.UserReauthenticateReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/handler.RespBody" + } + } + } + } + }, "/answer/api/v1/user/register/email": { "post": { "description": "UserRegisterByEmail", @@ -10914,6 +11085,122 @@ } } }, + "schema.PersonalAccessTokenCreateReq": { + "type": "object", + "required": [ + "expires_at", + "name", + "scopes" + ], + "properties": { + "expires_at": { + "type": "integer" + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "scopes": { + "type": "array", + "minItems": 1, + "items": { + "type": "string" + } + } + } + }, + "schema.PersonalAccessTokenCreateResp": { + "type": "object", + "properties": { + "created_at": { + "type": "integer" + }, + "expires_at": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "revoked_at": { + "type": "integer" + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + } + }, + "status": { + "type": "string" + }, + "token": { + "type": "string" + }, + "token_suffix": { + "type": "string" + } + } + }, + "schema.PersonalAccessTokenCurrentResp": { + "type": "object", + "properties": { + "token": { + "$ref": "#/definitions/schema.PersonalAccessTokenInfo" + }, + "user": { + "$ref": "#/definitions/schema.PersonalAccessTokenUserInfo" + } + } + }, + "schema.PersonalAccessTokenInfo": { + "type": "object", + "properties": { + "created_at": { + "type": "integer" + }, + "expires_at": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "revoked_at": { + "type": "integer" + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + } + }, + "status": { + "type": "string" + }, + "token_suffix": { + "type": "string" + } + } + }, + "schema.PersonalAccessTokenUserInfo": { + "type": "object", + "properties": { + "display_name": { + "type": "string" + }, + "id": { + "type": "string" + }, + "username": { + "type": "string" + } + } + }, "schema.PostRenderReq": { "type": "object", "properties": { @@ -12223,6 +12510,14 @@ }, "login_required": { "type": "boolean" + }, + "pat_reauthentication_window_minutes": { + "type": "integer", + "maximum": 120, + "minimum": 5 + }, + "personal_access_tokens_enabled": { + "type": "boolean" } } }, @@ -12244,6 +12539,14 @@ }, "login_required": { "type": "boolean" + }, + "pat_reauthentication_window_minutes": { + "type": "integer", + "maximum": 120, + "minimum": 5 + }, + "personal_access_tokens_enabled": { + "type": "boolean" } } }, @@ -13289,6 +13592,9 @@ "type": "string", "maxLength": 32, "minLength": 8 + }, + "revoke_personal_access_tokens": { + "type": "boolean" } } }, @@ -13357,6 +13663,23 @@ } } }, + "schema.UserReauthenticateReq": { + "type": "object", + "required": [ + "password" + ], + "properties": { + "captcha_code": { + "type": "string" + }, + "captcha_id": { + "type": "string" + }, + "password": { + "type": "string" + } + } + }, "schema.UserRegisterReq": { "type": "object", "required": [ diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 79c476c94..8c7d6aa1c 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1721,6 +1721,83 @@ definitions: type: type: string type: object + schema.PersonalAccessTokenCreateReq: + properties: + expires_at: + type: integer + name: + maxLength: 100 + type: string + scopes: + items: + type: string + minItems: 1 + type: array + required: + - expires_at + - name + - scopes + type: object + schema.PersonalAccessTokenCreateResp: + properties: + created_at: + type: integer + expires_at: + type: integer + id: + type: integer + name: + type: string + revoked_at: + type: integer + scopes: + items: + type: string + type: array + status: + type: string + token: + type: string + token_suffix: + type: string + type: object + schema.PersonalAccessTokenCurrentResp: + properties: + token: + $ref: '#/definitions/schema.PersonalAccessTokenInfo' + user: + $ref: '#/definitions/schema.PersonalAccessTokenUserInfo' + type: object + schema.PersonalAccessTokenInfo: + properties: + created_at: + type: integer + expires_at: + type: integer + id: + type: integer + name: + type: string + revoked_at: + type: integer + scopes: + items: + type: string + type: array + status: + type: string + token_suffix: + type: string + type: object + schema.PersonalAccessTokenUserInfo: + properties: + display_name: + type: string + id: + type: string + username: + type: string + type: object schema.PostRenderReq: properties: content: @@ -2617,6 +2694,12 @@ definitions: type: string login_required: type: boolean + pat_reauthentication_window_minutes: + maximum: 120 + minimum: 5 + type: integer + personal_access_tokens_enabled: + type: boolean required: - external_content_display type: object @@ -2631,6 +2714,12 @@ definitions: type: string login_required: type: boolean + pat_reauthentication_window_minutes: + maximum: 120 + minimum: 5 + type: integer + personal_access_tokens_enabled: + type: boolean required: - external_content_display type: object @@ -3359,6 +3448,8 @@ definitions: maxLength: 32 minLength: 8 type: string + revoke_personal_access_tokens: + type: boolean required: - pass type: object @@ -3407,6 +3498,17 @@ definitions: - code - pass type: object + schema.UserReauthenticateReq: + properties: + captcha_code: + type: string + captcha_id: + type: string + password: + type: string + required: + - password + type: object schema.UserRegisterReq: properties: captcha_code: @@ -6274,6 +6376,82 @@ paths: summary: check user permission tags: - Permission + /answer/api/v1/personal-access-tokens: + delete: + parameters: + - description: personal access token id + in: query + name: id + required: true + type: integer + responses: + "200": + description: OK + schema: + $ref: '#/definitions/handler.RespBody' + security: + - ApiKeyAuth: [] + summary: Revoke a personal access token + tags: + - Personal Access Token + get: + responses: + "200": + description: OK + schema: + allOf: + - $ref: '#/definitions/handler.RespBody' + - properties: + data: + items: + $ref: '#/definitions/schema.PersonalAccessTokenInfo' + type: array + type: object + security: + - ApiKeyAuth: [] + summary: List personal access tokens + tags: + - Personal Access Token + post: + parameters: + - description: personal access token + in: body + name: data + required: true + schema: + $ref: '#/definitions/schema.PersonalAccessTokenCreateReq' + responses: + "200": + description: OK + schema: + allOf: + - $ref: '#/definitions/handler.RespBody' + - properties: + data: + $ref: '#/definitions/schema.PersonalAccessTokenCreateResp' + type: object + security: + - ApiKeyAuth: [] + summary: Create a personal access token + tags: + - Personal Access Token + /answer/api/v1/personal-access-tokens/current: + get: + responses: + "200": + description: OK + schema: + allOf: + - $ref: '#/definitions/handler.RespBody' + - properties: + data: + $ref: '#/definitions/schema.PersonalAccessTokenCurrentResp' + type: object + security: + - ApiKeyAuth: [] + summary: Inspect the current personal access token + tags: + - Personal Access Token /answer/api/v1/personal/answer/page: get: consumes: @@ -8239,6 +8417,25 @@ paths: summary: get user ranking tags: - User + /answer/api/v1/user/reauthenticate: + post: + parameters: + - description: reauthentication + in: body + name: data + required: true + schema: + $ref: '#/definitions/schema.UserReauthenticateReq' + responses: + "200": + description: OK + schema: + $ref: '#/definitions/handler.RespBody' + security: + - ApiKeyAuth: [] + summary: Reauthenticate the current user + tags: + - User /answer/api/v1/user/register/email: post: consumes: diff --git a/go.mod b/go.mod index 7b68c180c..7da8dfe93 100644 --- a/go.mod +++ b/go.mod @@ -34,7 +34,7 @@ require ( github.com/go-sql-driver/mysql v1.8.1 github.com/goccy/go-json v0.10.3 github.com/google/uuid v1.6.0 - github.com/google/wire v0.5.0 + github.com/google/wire v0.7.0 github.com/grokify/html-strip-tags-go v0.1.0 github.com/jinzhu/copier v0.4.0 github.com/jinzhu/now v1.1.5 diff --git a/go.sum b/go.sum index 1001f1da0..33b9735ac 100644 --- a/go.sum +++ b/go.sum @@ -257,13 +257,12 @@ github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwg github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= -github.com/google/subcommands v1.0.1/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/wire v0.5.0 h1:I7ELFeVBr3yfPIcc8+MWvrjk+3VjbcSzoXm3JVa+jD8= -github.com/google/wire v0.5.0/go.mod h1:ngWDr9Qvq3yZA10YrxfyGELY/AFWGVpy9c1LTRi1EoU= +github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4= +github.com/google/wire v0.7.0/go.mod h1:n6YbUQD9cPKTnHXEBN2DXlOp/mVADhVErcMFb0v3J18= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= @@ -829,7 +828,6 @@ golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3 golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190422233926-fe54fb35175b/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= diff --git a/i18n/en_US.yaml b/i18n/en_US.yaml index a1ad44397..cc4cc2a5b 100644 --- a/i18n/en_US.yaml +++ b/i18n/en_US.yaml @@ -155,6 +155,14 @@ backend: password: space_invalid: other: Password cannot contain spaces. + personal_access_token: + insufficient_scope: + other: The personal access token does not have the required scope. + reauthentication_required: + other: Please authenticate again before creating a personal access token. + feature: + disabled: + other: This feature is disabled. admin: cannot_update_their_password: other: You cannot modify your password. @@ -337,9 +345,6 @@ backend: other: Unsupported file format. source_unsupported: other: Unsupported upload source. - feature: - disabled: - other: This feature is disabled. site_info: config_not_found: other: Site config not found. @@ -1336,6 +1341,7 @@ ui: notification: Notifications account: Account interface: Interface + personal_access_tokens: Personal access tokens profile: heading: Profile btn_name: Save @@ -1404,11 +1410,55 @@ ui: label: New password pass_confirm: label: Confirm new password + revoke_personal_access_tokens: Revoke all personal access tokens interface: heading: Interface lang: label: Interface language text: User interface language. It will change when you refresh the page. + personal_access_tokens: + heading: Personal access tokens + description_text: Create scoped credentials for command-line tools and delegated automation. + disabled: Personal access tokens are disabled by an administrator. Existing tokens cannot authenticate, but you can still revoke them. + create: Create token + create_failed: Failed to create the personal access token. + name: Name + token: Token + scopes: Scopes + expiration: Expiration + expires: Expires + status: Status + show_inactive: Show expired and revoked tokens + revoke: Revoke + revoke_confirm: Are you sure you want to revoke this token? + created_title: Personal access token created + created_warning: Copy this token now. It will not be shown again. + copy: Copy token + days: "{{count}} days" + custom_expiration: Custom date + reauthenticate: Confirm your identity + reauthenticate_failed: Authentication failed. + reauthenticate_external: Sign out and sign in again with your external identity provider, then retry. + password: Current password + continue: Continue + scope_group: + question: Question + answer: Answer + vote: Vote + scope: + question: + read: Read questions + create: Create questions + answer: + read: Read answers + create: Create answers + vote: + write: Cast and retract votes + token_status: + active: Active + expired: Expired + revoked: Revoked + temporarily_unavailable: Disabled by administrator my_logins: title: My logins label: Log in or sign up on this site using these accounts. @@ -2267,6 +2317,14 @@ ui: title: Password login label: Allow email and password login text: "WARNING: If turn off, you may be unable to log in if you have not previously configured other login method." + security: + page_title: Security + personal_access_tokens: + label: Enable personal access tokens + text: Allow users to create scoped credentials for command-line tools and delegated automation. + pat_reauthentication_window: + label: Reauthentication window (minutes) + text: Require users to authenticate again before creating a token when this period has elapsed. Allowed range is 5–120 minutes. installed_plugins: title: Installed Plugins plugin_link: Plugins extend and expand the functionality. You may find plugins in the <1>Plugin Repository. diff --git a/internal/base/middleware/auth.go b/internal/base/middleware/auth.go index bb4cf2554..3c4db55d6 100644 --- a/internal/base/middleware/auth.go +++ b/internal/base/middleware/auth.go @@ -44,21 +44,32 @@ var ctxUUIDKey = "ctxUuidKey" type AuthUserMiddleware struct { authService *auth.AuthService siteInfoCommonService siteinfo_common.SiteInfoCommonService + patAuthorizer *PATRequestAuthorizer } // NewAuthUserMiddleware new auth user middleware func NewAuthUserMiddleware( authService *auth.AuthService, - siteInfoCommonService siteinfo_common.SiteInfoCommonService) *AuthUserMiddleware { + siteInfoCommonService siteinfo_common.SiteInfoCommonService, + patAuthorizer *PATRequestAuthorizer, +) *AuthUserMiddleware { return &AuthUserMiddleware{ authService: authService, siteInfoCommonService: siteInfoCommonService, + patAuthorizer: patAuthorizer, } } // Auth get token and auth user, set user info to context if user is already login func (am *AuthUserMiddleware) Auth() gin.HandlerFunc { return func(ctx *gin.Context) { + if handled, userInfo := am.patAuthorizer.Resolve(ctx); handled { + if userInfo != nil { + ctx.Set(ctxUUIDKey, userInfo) + ctx.Next() + } + return + } token := ExtractToken(ctx) if len(token) == 0 { ctx.Next() @@ -110,6 +121,19 @@ func (am *AuthUserMiddleware) EjectUserBySiteInfo() gin.HandlerFunc { // MustAuthWithoutAccountAvailable auth user info, any login user can access though user is not active. func (am *AuthUserMiddleware) MustAuthWithoutAccountAvailable() gin.HandlerFunc { return func(ctx *gin.Context) { + if handled, userInfo := am.patAuthorizer.Resolve(ctx); handled { + if userInfo == nil { + return + } + if userInfo.UserStatus == entity.UserStatusDeleted { + handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) + ctx.Abort() + return + } + ctx.Set(ctxUUIDKey, userInfo) + ctx.Next() + return + } token := ExtractToken(ctx) if len(token) == 0 { handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) @@ -139,6 +163,17 @@ func (am *AuthUserMiddleware) MustAuthWithoutAccountAvailable() gin.HandlerFunc // MustAuthAndAccountAvailable auth user info and check user status, only allow active user access. func (am *AuthUserMiddleware) MustAuthAndAccountAvailable() gin.HandlerFunc { return func(ctx *gin.Context) { + if handled, userInfo := am.patAuthorizer.Resolve(ctx); handled { + if userInfo == nil { + return + } + if !checkAvailableAccount(ctx, userInfo) { + return + } + ctx.Set(ctxUUIDKey, userInfo) + ctx.Next() + return + } token := ExtractToken(ctx) if len(token) == 0 { handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) @@ -177,8 +212,32 @@ func (am *AuthUserMiddleware) MustAuthAndAccountAvailable() gin.HandlerFunc { } } +func checkAvailableAccount(ctx *gin.Context, userInfo *entity.UserCacheInfo) bool { + if userInfo.EmailStatus != entity.EmailStatusAvailable { + handler.HandleResponse(ctx, errors.Forbidden(reason.EmailNeedToBeVerified), + &schema.ForbiddenResp{Type: schema.ForbiddenReasonTypeInactive}) + ctx.Abort() + return false + } + if userInfo.UserStatus == entity.UserStatusSuspended { + handler.HandleResponse(ctx, errors.Forbidden(reason.UserSuspended), + &schema.ForbiddenResp{Type: schema.ForbiddenReasonTypeUserSuspended}) + ctx.Abort() + return false + } + if userInfo.UserStatus == entity.UserStatusDeleted { + handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) + ctx.Abort() + return false + } + return true +} + func (am *AuthUserMiddleware) AdminAuth() gin.HandlerFunc { return func(ctx *gin.Context) { + if handled, _ := am.patAuthorizer.Resolve(ctx); handled { + return + } token := ExtractToken(ctx) if len(token) == 0 { handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) diff --git a/internal/base/middleware/personal_access_token_auth.go b/internal/base/middleware/personal_access_token_auth.go new file mode 100644 index 000000000..c42611490 --- /dev/null +++ b/internal/base/middleware/personal_access_token_auth.go @@ -0,0 +1,149 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package middleware + +import ( + "context" + "strings" + + "github.com/apache/answer/internal/base/handler" + "github.com/apache/answer/internal/base/reason" + "github.com/apache/answer/internal/entity" + "github.com/apache/answer/internal/schema" + "github.com/apache/answer/internal/service/auth" + pat "github.com/apache/answer/internal/service/personal_access_token" + "github.com/apache/answer/internal/service/siteinfo_common" + "github.com/gin-gonic/gin" + "github.com/segmentfault/pacman/errors" +) + +const ctxPATKey = "ctxPersonalAccessToken" + +type patAuthenticator interface { + Authenticate(ctx context.Context, rawToken string) (*pat.AuthenticatedToken, error) +} + +type patUserLoader interface { + GetUserCacheInfoByUserID(ctx context.Context, userID string) (*entity.UserCacheInfo, error) +} + +type patSecurityLoader interface { + GetSiteSecurity(ctx context.Context) (*schema.SiteSecurityResp, error) +} + +// PATRequestAuthorizer authenticates PAT requests and applies their route scopes. +type PATRequestAuthorizer struct { + tokens patAuthenticator + users patUserLoader + security patSecurityLoader +} + +func NewPATRequestAuthorizer( + tokens *pat.Service, + users *auth.AuthService, + security siteinfo_common.SiteInfoCommonService, +) *PATRequestAuthorizer { + return newPATRequestAuthorizer(tokens, users, security) +} + +func newPATRequestAuthorizer( + tokens patAuthenticator, + users patUserLoader, + security patSecurityLoader, +) *PATRequestAuthorizer { + return &PATRequestAuthorizer{tokens: tokens, users: users, security: security} +} + +// Resolve reports whether the request presented a PAT. A non-nil user means the PAT passed authentication and scope checks. +func (a *PATRequestAuthorizer) Resolve(ctx *gin.Context) (handled bool, user *entity.UserCacheInfo) { + rawToken, candidate, validTransport := extractPAT(ctx) + if !candidate { + return false, nil + } + if !validTransport { + handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) + ctx.Abort() + return true, nil + } + + tokenInfo, err := a.tokens.Authenticate(ctx, rawToken) + if err != nil { + handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) + ctx.Abort() + return true, nil + } + + security, err := a.security.GetSiteSecurity(ctx) + if err != nil { + handler.HandleResponse(ctx, err, nil) + ctx.Abort() + return true, nil + } + if !security.PersonalAccessTokensEnabled { + handler.HandleResponse(ctx, errors.Forbidden(reason.ErrFeatureDisabled), gin.H{"feature": "personal_access_tokens"}) + ctx.Abort() + return true, nil + } + + allowed, required := pat.AuthorizeRoute(ctx.Request.Method, ctx.FullPath(), tokenInfo.Scopes) + if !allowed { + handler.HandleResponse(ctx, errors.Forbidden(reason.PersonalAccessTokenInsufficientScope), gin.H{"required_scopes": required}) + ctx.Abort() + return true, nil + } + + userInfo, err := a.users.GetUserCacheInfoByUserID(ctx, tokenInfo.UserID) + if err != nil || userInfo == nil { + handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) + ctx.Abort() + return true, nil + } + ctx.Set(ctxPATKey, tokenInfo) + return true, userInfo +} + +func GetPATFromContext(ctx *gin.Context) *pat.AuthenticatedToken { + value, exists := ctx.Get(ctxPATKey) + if !exists { + return nil + } + token, _ := value.(*pat.AuthenticatedToken) + return token +} + +func extractPAT(ctx *gin.Context) (rawToken string, candidate bool, validTransport bool) { + queryToken := ctx.Query("Authorization") + if strings.HasPrefix(queryToken, pat.TokenPrefix) || strings.HasPrefix(strings.TrimPrefix(queryToken, "Bearer "), pat.TokenPrefix) { + return "", true, false + } + + header := strings.TrimSpace(ctx.GetHeader("Authorization")) + if strings.HasPrefix(header, pat.TokenPrefix) { + return "", true, false + } + parts := strings.Fields(header) + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { + return "", false, false + } + if !strings.HasPrefix(parts[1], pat.TokenPrefix) { + return "", false, false + } + return parts[1], true, true +} diff --git a/internal/base/middleware/personal_access_token_auth_test.go b/internal/base/middleware/personal_access_token_auth_test.go new file mode 100644 index 000000000..bbd61eba8 --- /dev/null +++ b/internal/base/middleware/personal_access_token_auth_test.go @@ -0,0 +1,144 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package middleware + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/apache/answer/internal/entity" + "github.com/apache/answer/internal/schema" + pat "github.com/apache/answer/internal/service/personal_access_token" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestPersonalAccessTokenRequestAuthorization(t *testing.T) { + gin.SetMode(gin.TestMode) + now := time.Date(2026, time.September, 13, 12, 0, 0, 0, time.UTC) + repo := &middlewarePATRepository{} + service := pat.NewServiceWithOptions(repo, + pat.WithClock(func() time.Time { return now }), + pat.WithSecretGenerator(func() (string, error) { return "0123456789abcdefghijklmnopqrstuvwxyzAB", nil }), + ) + created, err := service.Create(context.Background(), pat.CreateInput{ + UserID: "42", Name: "agent", Scopes: []string{pat.ScopeQuestionRead}, ExpiresAt: now.Add(time.Hour), + }) + require.NoError(t, err) + + authorizer := newPATRequestAuthorizer(service, middlewarePATUserLoader{}, middlewarePATSecurityLoader{enabled: true}) + router := gin.New() + router.GET("/answer/api/v1/question/info", func(ctx *gin.Context) { + if handled, user := authorizer.Resolve(ctx); handled { + if user != nil { + ctx.Status(http.StatusNoContent) + } + return + } + ctx.Status(http.StatusNoContent) + }) + router.GET("/answer/api/v1/answer/info", func(ctx *gin.Context) { + if handled, user := authorizer.Resolve(ctx); handled { + if user != nil { + ctx.Status(http.StatusNoContent) + } + return + } + ctx.Status(http.StatusNoContent) + }) + + t.Run("valid scope establishes owner", func(t *testing.T) { + response := performPATRequest(router, "/answer/api/v1/question/info", "Bearer "+created.Token) + require.Equal(t, http.StatusNoContent, response.Code) + }) + + t.Run("missing scope is forbidden", func(t *testing.T) { + response := performPATRequest(router, "/answer/api/v1/answer/info", "Bearer "+created.Token) + require.Equal(t, http.StatusForbidden, response.Code) + var body map[string]any + require.NoError(t, json.Unmarshal(response.Body.Bytes(), &body)) + require.Equal(t, "error.personal_access_token.insufficient_scope", body["reason"]) + }) + + t.Run("bare PAT is rejected", func(t *testing.T) { + response := performPATRequest(router, "/answer/api/v1/question/info", created.Token) + require.Equal(t, http.StatusUnauthorized, response.Code) + }) +} + +func performPATRequest(router http.Handler, path, authorization string) *httptest.ResponseRecorder { + request := httptest.NewRequest(http.MethodGet, path, nil) + request.Header.Set("Authorization", authorization) + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + return response +} + +type middlewarePATRepository struct { + token *entity.PersonalAccessToken +} + +func (r *middlewarePATRepository) Create(_ context.Context, token *entity.PersonalAccessToken) error { + copy := *token + copy.ID = 1 + token.ID = 1 + r.token = © + return nil +} + +func (r *middlewarePATRepository) FindByHash(_ context.Context, hash string) (*entity.PersonalAccessToken, bool, error) { + if r.token == nil || r.token.TokenHash != hash { + return nil, false, nil + } + copy := *r.token + return ©, true, nil +} + +func (*middlewarePATRepository) ListByUserID(context.Context, string) ([]*entity.PersonalAccessToken, error) { + return nil, nil +} + +func (*middlewarePATRepository) Revoke(context.Context, string, int64, time.Time) (bool, error) { + return false, nil +} + +func (*middlewarePATRepository) RevokeAllByUserID(context.Context, string, time.Time) error { + return nil +} + +type middlewarePATUserLoader struct{} + +func (middlewarePATUserLoader) GetUserCacheInfoByUserID(context.Context, string) (*entity.UserCacheInfo, error) { + return &entity.UserCacheInfo{ + UserID: "42", UserStatus: entity.UserStatusAvailable, EmailStatus: entity.EmailStatusAvailable, RoleID: 1, + }, nil +} + +type middlewarePATSecurityLoader struct { + enabled bool +} + +func (s middlewarePATSecurityLoader) GetSiteSecurity(context.Context) (*schema.SiteSecurityResp, error) { + return &schema.SiteSecurityResp{PersonalAccessTokensEnabled: s.enabled}, nil +} diff --git a/internal/base/middleware/provider.go b/internal/base/middleware/provider.go index d9a2f8f78..fbbfc2e5a 100644 --- a/internal/base/middleware/provider.go +++ b/internal/base/middleware/provider.go @@ -25,6 +25,7 @@ import ( // ProviderSetMiddleware is providers. var ProviderSetMiddleware = wire.NewSet( + NewPATRequestAuthorizer, NewAuthUserMiddleware, NewAvatarMiddleware, NewShortIDMiddleware, diff --git a/internal/base/middleware/visit_img_auth_test.go b/internal/base/middleware/visit_img_auth_test.go index 7d1858ce2..8d6069d55 100644 --- a/internal/base/middleware/visit_img_auth_test.go +++ b/internal/base/middleware/visit_img_auth_test.go @@ -77,7 +77,7 @@ func TestVisitAuthRejectsRevokedAndSuspendedSessions(t *testing.T) { gin.SetMode(gin.TestMode) engine := gin.New() siteInfo := siteinfo_common.NewSiteInfoCommonService(visitAuthTestSiteInfoRepo{}) - authMiddleware := NewAuthUserMiddleware(service, siteInfo) + authMiddleware := NewAuthUserMiddleware(service, siteInfo, nil) engine.Use(authMiddleware.VisitAuth()) engine.StaticFile("/uploads/post/private.txt", filePath) req := httptest.NewRequest(http.MethodGet, "/uploads/post/private.txt", nil) diff --git a/internal/base/reason/personal_access_token.go b/internal/base/reason/personal_access_token.go new file mode 100644 index 000000000..d8a8e569e --- /dev/null +++ b/internal/base/reason/personal_access_token.go @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package reason + +const ( + PersonalAccessTokenInsufficientScope = "error.personal_access_token.insufficient_scope" + PersonalAccessTokenReauthenticationRequired = "error.personal_access_token.reauthentication_required" +) diff --git a/internal/base/translator/provider_test.go b/internal/base/translator/provider_test.go new file mode 100644 index 000000000..36ed6e4b4 --- /dev/null +++ b/internal/base/translator/provider_test.go @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package translator + +import ( + "os" + "path/filepath" + "testing" + + bundles "github.com/apache/answer/i18n" + "github.com/segmentfault/pacman/i18n" + "github.com/stretchr/testify/require" +) + +func TestNewTranslatorLoadsBundledEnglish(t *testing.T) { + // Reserved message keys such as "description" beside nested UI labels can + // make go-i18n reject the entire English bundle and panic on translation. + dir := t.TempDir() + for _, name := range []string{"en_US.yaml", "i18n.yaml"} { + content, err := bundles.I18n.ReadFile(name) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(dir, name), content, 0o600)) + } + + tr, err := NewTranslator(&I18n{BundleDir: dir}) + require.NoError(t, err) + require.NotPanics(t, func() { + require.Equal(t, "Email", tr.Tr(i18n.DefaultLanguage, "email")) + }) +} diff --git a/internal/controller/controller.go b/internal/controller/controller.go index c31763bea..a3e000dbc 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -55,6 +55,7 @@ var ProviderSetController = wire.NewSet( NewRenderController, NewSidebarController, NewMCPController, + NewPersonalAccessTokenController, NewAIController, NewAIConversationController, ) diff --git a/internal/controller/personal_access_token_controller.go b/internal/controller/personal_access_token_controller.go new file mode 100644 index 000000000..a9fd096e2 --- /dev/null +++ b/internal/controller/personal_access_token_controller.go @@ -0,0 +1,193 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package controller + +import ( + "errors" + "time" + + "github.com/apache/answer/internal/base/handler" + "github.com/apache/answer/internal/base/middleware" + "github.com/apache/answer/internal/base/reason" + "github.com/apache/answer/internal/schema" + pat "github.com/apache/answer/internal/service/personal_access_token" + "github.com/apache/answer/internal/service/siteinfo_common" + usercommon "github.com/apache/answer/internal/service/user_common" + "github.com/gin-gonic/gin" + pacmanerrors "github.com/segmentfault/pacman/errors" +) + +type PersonalAccessTokenController struct { + tokens *pat.Service + siteInfo siteinfo_common.SiteInfoCommonService + userCommon *usercommon.UserCommon +} + +func NewPersonalAccessTokenController( + tokens *pat.Service, + siteInfo siteinfo_common.SiteInfoCommonService, + userCommon *usercommon.UserCommon, +) *PersonalAccessTokenController { + return &PersonalAccessTokenController{tokens: tokens, siteInfo: siteInfo, userCommon: userCommon} +} + +// List returns the current user's Personal Access Tokens. +// @Summary List personal access tokens +// @Tags Personal Access Token +// @Security ApiKeyAuth +// @Success 200 {object} handler.RespBody{data=[]schema.PersonalAccessTokenInfo} +// @Router /answer/api/v1/personal-access-tokens [get] +func (c *PersonalAccessTokenController) List(ctx *gin.Context) { + userID := middleware.GetLoginUserIDFromContext(ctx) + items, err := c.tokens.List(ctx, userID) + if err != nil { + handler.HandleResponse(ctx, err, nil) + return + } + security, err := c.siteInfo.GetSiteSecurity(ctx) + if err != nil { + handler.HandleResponse(ctx, err, nil) + return + } + resp := make([]schema.PersonalAccessTokenInfo, 0, len(items)) + for _, item := range items { + converted := convertPATInfo(item) + if !security.PersonalAccessTokensEnabled && converted.Status == string(pat.StatusActive) { + converted.Status = "temporarily_unavailable" + } + resp = append(resp, converted) + } + handler.HandleResponse(ctx, nil, resp) +} + +// Create creates a Personal Access Token and returns its secret once. +// @Summary Create a personal access token +// @Tags Personal Access Token +// @Security ApiKeyAuth +// @Param data body schema.PersonalAccessTokenCreateReq true "personal access token" +// @Success 200 {object} handler.RespBody{data=schema.PersonalAccessTokenCreateResp} +// @Router /answer/api/v1/personal-access-tokens [post] +func (c *PersonalAccessTokenController) Create(ctx *gin.Context) { + request := &schema.PersonalAccessTokenCreateReq{} + if handler.BindAndCheck(ctx, request) { + return + } + userInfo := middleware.GetUserInfoFromContext(ctx) + if userInfo == nil { + handler.HandleResponse(ctx, pacmanerrors.Unauthorized(reason.UnauthorizedError), nil) + return + } + security, err := c.siteInfo.GetSiteSecurity(ctx) + if err != nil { + handler.HandleResponse(ctx, err, nil) + return + } + if !security.PersonalAccessTokensEnabled { + handler.HandleResponse(ctx, pacmanerrors.Forbidden(reason.ErrFeatureDisabled), gin.H{"feature": "personal_access_tokens"}) + return + } + if !isPATAuthenticationRecent(userInfo.AuthenticatedAt, time.Now(), security.PATReauthenticationWindow()) { + handler.HandleResponse(ctx, pacmanerrors.Forbidden(reason.PersonalAccessTokenReauthenticationRequired), nil) + return + } + + created, err := c.tokens.Create(ctx, pat.CreateInput{ + UserID: userInfo.UserID, Name: request.Name, Scopes: request.Scopes, + ExpiresAt: time.Unix(request.ExpiresAt, 0), + }) + if errors.Is(err, pat.ErrInvalidScope) || errors.Is(err, pat.ErrInvalidExpiry) { + handler.HandleResponse(ctx, pacmanerrors.BadRequest(reason.RequestFormatError), nil) + return + } + if err != nil { + handler.HandleResponse(ctx, err, nil) + return + } + resp := &schema.PersonalAccessTokenCreateResp{ + Token: created.Token, PersonalAccessTokenInfo: convertPATInfo(created.Info), + } + handler.HandleResponse(ctx, nil, resp) +} + +// Revoke permanently revokes one of the current user's Personal Access Tokens. +// @Summary Revoke a personal access token +// @Tags Personal Access Token +// @Security ApiKeyAuth +// @Param id query int true "personal access token id" +// @Success 200 {object} handler.RespBody +// @Router /answer/api/v1/personal-access-tokens [delete] +func (c *PersonalAccessTokenController) Revoke(ctx *gin.Context) { + request := &schema.PersonalAccessTokenRevokeReq{} + if handler.BindAndCheck(ctx, request) { + return + } + err := c.tokens.Revoke(ctx, middleware.GetLoginUserIDFromContext(ctx), request.ID) + handler.HandleResponse(ctx, err, nil) +} + +// Current returns metadata for the PAT authenticating the request. +// @Summary Inspect the current personal access token +// @Tags Personal Access Token +// @Security ApiKeyAuth +// @Success 200 {object} handler.RespBody{data=schema.PersonalAccessTokenCurrentResp} +// @Router /answer/api/v1/personal-access-tokens/current [get] +func (c *PersonalAccessTokenController) Current(ctx *gin.Context) { + token := middleware.GetPATFromContext(ctx) + if token == nil { + handler.HandleResponse(ctx, pacmanerrors.Unauthorized(reason.UnauthorizedError), nil) + return + } + user, exists, err := c.userCommon.GetUserBasicInfoByID(ctx, token.UserID) + if err != nil { + handler.HandleResponse(ctx, err, nil) + return + } + if !exists { + handler.HandleResponse(ctx, pacmanerrors.Unauthorized(reason.UnauthorizedError), nil) + return + } + resp := &schema.PersonalAccessTokenCurrentResp{ + User: schema.PersonalAccessTokenUserInfo{ID: user.ID, Username: user.Username, DisplayName: user.DisplayName}, + Token: schema.PersonalAccessTokenInfo{ + ID: token.ID, Name: token.Name, TokenSuffix: token.TokenSuffix, Scopes: token.Scopes, + CreatedAt: token.CreatedAt.Unix(), ExpiresAt: token.ExpiresAt.Unix(), Status: string(pat.StatusActive), + }, + } + handler.HandleResponse(ctx, nil, resp) +} + +func isPATAuthenticationRecent(authenticatedAt int64, now time.Time, windowMinutes int) bool { + if authenticatedAt <= 0 { + return false + } + elapsed := now.Sub(time.Unix(authenticatedAt, 0)) + return elapsed >= 0 && elapsed <= time.Duration(windowMinutes)*time.Minute +} + +func convertPATInfo(info pat.TokenInfo) schema.PersonalAccessTokenInfo { + result := schema.PersonalAccessTokenInfo{ + ID: info.ID, Name: info.Name, TokenSuffix: info.TokenSuffix, Scopes: info.Scopes, + CreatedAt: info.CreatedAt.Unix(), ExpiresAt: info.ExpiresAt.Unix(), Status: string(info.Status), + } + if !info.RevokedAt.IsZero() { + result.RevokedAt = info.RevokedAt.Unix() + } + return result +} diff --git a/internal/controller/personal_access_token_controller_test.go b/internal/controller/personal_access_token_controller_test.go new file mode 100644 index 000000000..f26b9ce2a --- /dev/null +++ b/internal/controller/personal_access_token_controller_test.go @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package controller + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestPATCreationRequiresAuthenticationWithinConfiguredWindow(t *testing.T) { + now := time.Date(2026, time.September, 14, 12, 0, 0, 0, time.UTC) + require.True(t, isPATAuthenticationRecent(now.Add(-60*time.Minute).Unix(), now, 60)) + require.False(t, isPATAuthenticationRecent(now.Add(-61*time.Minute).Unix(), now, 60)) + require.False(t, isPATAuthenticationRecent(0, now, 60)) + require.False(t, isPATAuthenticationRecent(now.Add(time.Minute).Unix(), now, 60)) +} diff --git a/internal/controller/user_controller.go b/internal/controller/user_controller.go index 531d88b45..6847f06cd 100644 --- a/internal/controller/user_controller.go +++ b/internal/controller/user_controller.go @@ -376,6 +376,56 @@ func (uc *UserController) UserVerifyEmailSend(ctx *gin.Context) { handler.HandleResponse(ctx, err, nil) } +// UserReauthenticate confirms a local password for sensitive account operations. +// @Summary Reauthenticate the current user +// @Tags User +// @Security ApiKeyAuth +// @Param data body schema.UserReauthenticateReq true "reauthentication" +// @Success 200 {object} handler.RespBody +// @Router /answer/api/v1/user/reauthenticate [post] +func (uc *UserController) UserReauthenticate(ctx *gin.Context) { + req := &schema.UserReauthenticateReq{} + if handler.BindAndCheck(ctx, req) { + return + } + req.UserID = middleware.GetLoginUserIDFromContext(ctx) + req.AccessToken = middleware.ExtractToken(ctx) + isAdmin := middleware.GetUserIsAdminModerator(ctx) + if !isAdmin { + captchaPass := uc.actionService.ActionRecordVerifyCaptcha(ctx, entity.CaptchaActionEditUserinfo, req.UserID, + req.CaptchaID, req.CaptchaCode) + if !captchaPass { + errFields := []*validator.FormErrorField{{ + ErrorField: "captcha_code", + ErrorMsg: translator.Tr(handler.GetLangByCtx(ctx), reason.CaptchaVerificationFailed), + }} + handler.HandleResponse(ctx, errors.BadRequest(reason.CaptchaVerificationFailed), errFields) + return + } + uc.actionService.ActionRecordAdd(ctx, entity.CaptchaActionEditUserinfo, req.UserID) + } + + valid, err := uc.userService.VerifyPassword(ctx, req.UserID, req.Password) + if err != nil { + handler.HandleResponse(ctx, err, nil) + return + } + if !valid { + errFields := []*validator.FormErrorField{{ + ErrorField: "password", + ErrorMsg: translator.Tr(handler.GetLangByCtx(ctx), reason.OldPasswordVerificationFailed), + }} + handler.HandleResponse(ctx, errors.BadRequest(reason.OldPasswordVerificationFailed), errFields) + return + } + if err := uc.authService.MarkReauthenticated(ctx, req.AccessToken); err != nil { + handler.HandleResponse(ctx, err, nil) + return + } + uc.actionService.ActionRecordDel(ctx, entity.CaptchaActionEditUserinfo, req.UserID) + handler.HandleResponse(ctx, nil, nil) +} + // UserModifyPassWord godoc // @Summary UserModifyPassWord // @Description UserModifyPassWord diff --git a/internal/entity/auth_user_entity.go b/internal/entity/auth_user_entity.go index 29a639d3a..dcef39073 100644 --- a/internal/entity/auth_user_entity.go +++ b/internal/entity/auth_user_entity.go @@ -21,10 +21,11 @@ package entity // UserCacheInfo User Cache Information type UserCacheInfo struct { - UserID string `json:"user_id"` - UserStatus int `json:"user_status"` - EmailStatus int `json:"email_status"` - RoleID int `json:"role_id"` - ExternalID string `json:"external_id"` - VisitToken string `json:"visit_token"` + UserID string `json:"user_id"` + UserStatus int `json:"user_status"` + EmailStatus int `json:"email_status"` + RoleID int `json:"role_id"` + ExternalID string `json:"external_id"` + VisitToken string `json:"visit_token"` + AuthenticatedAt int64 `json:"authenticated_at"` } diff --git a/internal/entity/personal_access_token_entity.go b/internal/entity/personal_access_token_entity.go new file mode 100644 index 000000000..7afadbcbf --- /dev/null +++ b/internal/entity/personal_access_token_entity.go @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package entity + +import "time" + +// PersonalAccessToken is a user-owned credential for delegated API access. +type PersonalAccessToken struct { + ID int64 `xorm:"not null pk autoincr BIGINT id"` + UserID string `xorm:"not null index BIGINT(20) user_id"` + Name string `xorm:"not null VARCHAR(100) name"` + TokenHash string `xorm:"not null unique CHAR(64) token_hash"` + TokenSuffix string `xorm:"not null CHAR(4) token_suffix"` + Scopes string `xorm:"not null TEXT scopes"` + CreatedAt time.Time `xorm:"created not null default CURRENT_TIMESTAMP TIMESTAMP created_at"` + ExpiresAt time.Time `xorm:"not null TIMESTAMP expires_at"` + RevokedAt time.Time `xorm:"TIMESTAMP revoked_at"` +} + +// TableName returns the PersonalAccessToken table name. +func (*PersonalAccessToken) TableName() string { + return "personal_access_token" +} diff --git a/internal/migrations/init.go b/internal/migrations/init.go index d5098dd0c..9cb2255d0 100644 --- a/internal/migrations/init.go +++ b/internal/migrations/init.go @@ -241,9 +241,11 @@ func (m *Mentor) initSiteInfoLoginConfig() { func (m *Mentor) initSiteInfoSecurityConfig() { securityConfig := map[string]any{ - "login_required": m.userData.LoginRequired, - "external_content_display": m.userData.ExternalContentDisplay, - "check_update": true, + "login_required": m.userData.LoginRequired, + "external_content_display": m.userData.ExternalContentDisplay, + "check_update": true, + "personal_access_tokens_enabled": false, + "pat_reauthentication_window_minutes": schema.DefaultPATReauthenticationWindowMinutes, } securityConfigDataBytes, _ := json.Marshal(securityConfig) _, m.err = m.engine.Context(m.ctx).Insert(&entity.SiteInfo{ diff --git a/internal/migrations/init_data.go b/internal/migrations/init_data.go index 5af41bbfc..0e9aa13a2 100644 --- a/internal/migrations/init_data.go +++ b/internal/migrations/init_data.go @@ -77,6 +77,7 @@ var ( &entity.FileRecord{}, &entity.PluginKVStorage{}, &entity.APIKey{}, + &entity.PersonalAccessToken{}, &entity.AIConversation{}, &entity.AIConversationRecord{}, } diff --git a/internal/migrations/migrations.go b/internal/migrations/migrations.go index 360f688af..13332ad1e 100644 --- a/internal/migrations/migrations.go +++ b/internal/migrations/migrations.go @@ -111,6 +111,7 @@ var migrations = []Migration{ NewMigration("v2.0.2", "add reasoning content to ai conversation record", addAIConversationReasoningContent, false), NewMigration("v2.0.3", "add require email verification login setting", addRequireEmailVerification, true), NewMigration("v2.0.4", "repair missing advanced site settings", repairAdvancedSiteInfo, true), + NewMigration("v2.0.5", "add personal access tokens", addPersonalAccessTokens, true), } func GetMigrations() []Migration { diff --git a/internal/migrations/v36.go b/internal/migrations/v36.go new file mode 100644 index 000000000..5ae129fce --- /dev/null +++ b/internal/migrations/v36.go @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package migrations + +import ( + "context" + + "github.com/apache/answer/internal/entity" + "xorm.io/xorm" +) + +func addPersonalAccessTokens(ctx context.Context, x *xorm.Engine) error { + return x.Context(ctx).Sync(new(entity.PersonalAccessToken)) +} diff --git a/internal/repo/auth/auth.go b/internal/repo/auth/auth.go index 7c957d784..a9e5ed270 100644 --- a/internal/repo/auth/auth.go +++ b/internal/repo/auth/auth.go @@ -208,6 +208,41 @@ func (ar *authRepo) AddUserTokenMapping(ctx context.Context, userID, accessToken } // RemoveUserTokens Log out all users under this user id +func (ar *authRepo) GetUserCacheInfoByUserID(ctx context.Context, userID string) (*entity.UserCacheInfo, bool, error) { + user := &entity.User{} + exists, err := ar.data.DB.Context(ctx).ID(userID).Get(user) + if err != nil { + return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + } + if !exists { + return nil, false, nil + } + + roleID := 1 + roleRel := &entity.UserRoleRel{} + if hasRole, roleErr := ar.data.DB.Context(ctx).Where("user_id = ?", userID).Get(roleRel); roleErr != nil { + return nil, false, errors.InternalServer(reason.DatabaseError).WithError(roleErr).WithStack() + } else if hasRole { + roleID = roleRel.RoleID + } + + externalID := "" + externalLogin := &entity.UserExternalLogin{} + if hasExternal, externalErr := ar.data.DB.Context(ctx).Where("user_id = ?", userID).Get(externalLogin); externalErr != nil { + return nil, false, errors.InternalServer(reason.DatabaseError).WithError(externalErr).WithStack() + } else if hasExternal { + externalID = externalLogin.ExternalID + } + + return &entity.UserCacheInfo{ + UserID: user.ID, + UserStatus: user.Status, + EmailStatus: user.MailStatus, + RoleID: roleID, + ExternalID: externalID, + }, true, nil +} + func (ar *authRepo) RemoveUserTokens(ctx context.Context, userID string, remainToken string) { key := constant.UserTokenMappingCacheKey + userID resp, _, err := ar.data.Cache.GetString(ctx, key) diff --git a/internal/repo/personal_access_token/personal_access_token_repo.go b/internal/repo/personal_access_token/personal_access_token_repo.go new file mode 100644 index 000000000..dd11df5d3 --- /dev/null +++ b/internal/repo/personal_access_token/personal_access_token_repo.go @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package personal_access_token + +import ( + "context" + "time" + + "github.com/apache/answer/internal/base/data" + "github.com/apache/answer/internal/base/reason" + "github.com/apache/answer/internal/entity" + personalaccesstoken "github.com/apache/answer/internal/service/personal_access_token" + "github.com/segmentfault/pacman/errors" + "xorm.io/builder" +) + +type repository struct { + data *data.Data +} + +func NewRepository(data *data.Data) personalaccesstoken.Repository { + return &repository{data: data} +} + +func (r *repository) Create(ctx context.Context, token *entity.PersonalAccessToken) error { + _, err := r.data.DB.Context(ctx).Insert(token) + return databaseError(err) +} + +func (r *repository) FindByHash(ctx context.Context, hash string) (*entity.PersonalAccessToken, bool, error) { + token := &entity.PersonalAccessToken{} + exists, err := r.data.DB.Context(ctx).Where(builder.Eq{"token_hash": hash}).Get(token) + return token, exists, databaseError(err) +} + +func (r *repository) ListByUserID(ctx context.Context, userID string) ([]*entity.PersonalAccessToken, error) { + tokens := make([]*entity.PersonalAccessToken, 0) + err := r.data.DB.Context(ctx).Where(builder.Eq{"user_id": userID}).Desc("created_at").Find(&tokens) + return tokens, databaseError(err) +} + +func (r *repository) Revoke(ctx context.Context, userID string, id int64, revokedAt time.Time) (bool, error) { + token := &entity.PersonalAccessToken{} + exists, err := r.data.DB.Context(ctx).Where(builder.Eq{"id": id, "user_id": userID}).Get(token) + if err != nil || !exists { + return exists, databaseError(err) + } + if !token.RevokedAt.IsZero() { + return true, nil + } + _, err = r.data.DB.Context(ctx).ID(id).Cols("revoked_at").Update(&entity.PersonalAccessToken{RevokedAt: revokedAt}) + return true, databaseError(err) +} + +func (r *repository) RevokeAllByUserID(ctx context.Context, userID string, revokedAt time.Time) error { + _, err := r.data.DB.Context(ctx). + Where("user_id = ? AND revoked_at IS NULL", userID). + Cols("revoked_at").Update(&entity.PersonalAccessToken{RevokedAt: revokedAt}) + return databaseError(err) +} + +func databaseError(err error) error { + if err == nil { + return nil + } + return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() +} diff --git a/internal/repo/provider.go b/internal/repo/provider.go index 510a94aaa..c22515740 100644 --- a/internal/repo/provider.go +++ b/internal/repo/provider.go @@ -39,6 +39,7 @@ import ( "github.com/apache/answer/internal/repo/limit" "github.com/apache/answer/internal/repo/meta" "github.com/apache/answer/internal/repo/notification" + "github.com/apache/answer/internal/repo/personal_access_token" "github.com/apache/answer/internal/repo/plugin_config" "github.com/apache/answer/internal/repo/question" "github.com/apache/answer/internal/repo/rank" @@ -112,5 +113,6 @@ var ProviderSetRepo = wire.NewSet( badge_award.NewBadgeAwardRepo, file_record.NewFileRecordRepo, api_key.NewAPIKeyRepo, + personal_access_token.NewRepository, ai_conversation.NewAIConversationRepo, ) diff --git a/internal/repo/repo_test/personal_access_token_repo_test.go b/internal/repo/repo_test/personal_access_token_repo_test.go new file mode 100644 index 000000000..613b9c40e --- /dev/null +++ b/internal/repo/repo_test/personal_access_token_repo_test.go @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package repo_test + +import ( + "context" + "testing" + "time" + + "github.com/apache/answer/internal/entity" + personalaccesstoken "github.com/apache/answer/internal/repo/personal_access_token" + "github.com/stretchr/testify/require" +) + +func TestPersonalAccessTokenRepositoryLifecycle(t *testing.T) { + ctx := context.Background() + repo := personalaccesstoken.NewRepository(testDataSource) + expiresAt := time.Now().UTC().Add(24 * time.Hour).Truncate(time.Second) + token := &entity.PersonalAccessToken{ + UserID: "1", Name: "agent", TokenHash: "hash-one", TokenSuffix: "last", + Scopes: `["question.read"]`, ExpiresAt: expiresAt, + } + + require.NoError(t, repo.Create(ctx, token)) + require.NotZero(t, token.ID) + + found, exists, err := repo.FindByHash(ctx, "hash-one") + require.NoError(t, err) + require.True(t, exists) + require.Equal(t, "1", found.UserID) + require.Equal(t, expiresAt.Unix(), found.ExpiresAt.Unix()) + + list, err := repo.ListByUserID(ctx, "1") + require.NoError(t, err) + require.Len(t, list, 1) + + revokedAt := time.Now().UTC().Truncate(time.Second) + revoked, err := repo.Revoke(ctx, "1", token.ID, revokedAt) + require.NoError(t, err) + require.True(t, revoked) + + found, exists, err = repo.FindByHash(ctx, "hash-one") + require.NoError(t, err) + require.True(t, exists) + require.Equal(t, revokedAt.Unix(), found.RevokedAt.Unix()) + + revoked, err = repo.Revoke(ctx, "2", token.ID, revokedAt) + require.NoError(t, err) + require.False(t, revoked) + + second := &entity.PersonalAccessToken{ + UserID: "2", Name: "second agent", TokenHash: "hash-two", TokenSuffix: "last", + Scopes: `["answer.read"]`, ExpiresAt: expiresAt, + } + require.NoError(t, repo.Create(ctx, second)) + require.NoError(t, repo.RevokeAllByUserID(ctx, "2", revokedAt)) + found, exists, err = repo.FindByHash(ctx, "hash-two") + require.NoError(t, err) + require.True(t, exists) + require.Equal(t, revokedAt.Unix(), found.RevokedAt.Unix()) +} diff --git a/internal/repo/repo_test/repo_main_test.go b/internal/repo/repo_test/repo_main_test.go index e2f40f276..41400b558 100644 --- a/internal/repo/repo_test/repo_main_test.go +++ b/internal/repo/repo_test/repo_main_test.go @@ -45,7 +45,7 @@ var ( ImageVersion: "10.4.7", ENV: []string{"MYSQL_ROOT_PASSWORD=root", "MYSQL_DATABASE=answer", "MYSQL_ROOT_HOST=%"}, PortID: "3306/tcp", - Connection: "root:root@(localhost:%s)/answer?parseTime=true", // port is not fixed, it will be got by port id + Connection: "root:root@(localhost:%s)/answer?charset=utf8mb4&parseTime=true", // port is not fixed, it will be got by port id } postgresDBSetting = TestDBSetting{ Driver: string(schemas.POSTGRES), diff --git a/internal/router/answer_api_router.go b/internal/router/answer_api_router.go index 8c401a09e..b920aa653 100644 --- a/internal/router/answer_api_router.go +++ b/internal/router/answer_api_router.go @@ -62,6 +62,7 @@ type AnswerAPIRouter struct { aiConversationController *controller.AIConversationController aiConversationAdminController *controller_admin.AIConversationAdminController mcpController *controller.MCPController + personalAccessTokenController *controller.PersonalAccessTokenController } func NewAnswerAPIRouter( @@ -100,6 +101,7 @@ func NewAnswerAPIRouter( aiConversationController *controller.AIConversationController, aiConversationAdminController *controller_admin.AIConversationAdminController, mcpController *controller.MCPController, + personalAccessTokenController *controller.PersonalAccessTokenController, ) *AnswerAPIRouter { return &AnswerAPIRouter{ langController: langController, @@ -137,6 +139,7 @@ func NewAnswerAPIRouter( aiConversationController: aiConversationController, aiConversationAdminController: aiConversationAdminController, mcpController: mcpController, + personalAccessTokenController: personalAccessTokenController, } } @@ -284,7 +287,14 @@ func (a *AnswerAPIRouter) RegisterAnswerAPIRouter(r *gin.RouterGroup) { r.DELETE("/answer", a.answerController.RemoveAnswer) r.POST("/answer/recover", a.answerController.RecoverAnswer) + // personal access tokens + r.GET("/personal-access-tokens", a.personalAccessTokenController.List) + r.POST("/personal-access-tokens", a.personalAccessTokenController.Create) + r.DELETE("/personal-access-tokens", a.personalAccessTokenController.Revoke) + r.GET("/personal-access-tokens/current", a.personalAccessTokenController.Current) + // user + r.POST("/user/reauthenticate", middleware.BanAPIForUserCenter, a.userController.UserReauthenticate) r.PUT("/user/password", middleware.BanAPIForUserCenter, a.userController.UserModifyPassWord) r.PUT("/user/info", a.userController.UserUpdateInfo) r.PUT("/user/interface", a.userController.UserUpdateInterface) diff --git a/internal/schema/personal_access_token_schema.go b/internal/schema/personal_access_token_schema.go new file mode 100644 index 000000000..e1e258fa7 --- /dev/null +++ b/internal/schema/personal_access_token_schema.go @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package schema + +// PersonalAccessTokenCreateReq creates a scoped user credential. +type PersonalAccessTokenCreateReq struct { + Name string `validate:"required,notblank,lte=100" json:"name"` + Scopes []string `validate:"required,min=1,dive,required" json:"scopes"` + ExpiresAt int64 `validate:"required" json:"expires_at"` +} + +type PersonalAccessTokenInfo struct { + ID int64 `json:"id"` + Name string `json:"name"` + TokenSuffix string `json:"token_suffix"` + Scopes []string `json:"scopes"` + CreatedAt int64 `json:"created_at"` + ExpiresAt int64 `json:"expires_at"` + RevokedAt int64 `json:"revoked_at,omitempty"` + Status string `json:"status"` +} + +type PersonalAccessTokenCreateResp struct { + Token string `json:"token"` + PersonalAccessTokenInfo +} + +type PersonalAccessTokenRevokeReq struct { + ID int64 `validate:"required" form:"id"` +} + +type PersonalAccessTokenCurrentResp struct { + User PersonalAccessTokenUserInfo `json:"user"` + Token PersonalAccessTokenInfo `json:"token"` +} + +type PersonalAccessTokenUserInfo struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` +} + +type UserReauthenticateReq struct { + Password string `validate:"required" json:"password"` + CaptchaID string `json:"captcha_id"` + CaptchaCode string `json:"captcha_code"` + UserID string `json:"-"` + AccessToken string `json:"-"` +} diff --git a/internal/schema/siteinfo_schema.go b/internal/schema/siteinfo_schema.go index 6b0b11e72..de4225812 100644 --- a/internal/schema/siteinfo_schema.go +++ b/internal/schema/siteinfo_schema.go @@ -174,15 +174,33 @@ type SitePoliciesReq struct { PrivacyPolicyParsedText string `json:"privacy_policy_parsed_text"` } +const DefaultPATReauthenticationWindowMinutes = 60 + type SiteSecurityReq struct { - LoginRequired bool `json:"login_required"` - ExternalContentDisplay string `validate:"required,oneof=always_display ask_before_display" json:"external_content_display"` - CheckUpdate bool `validate:"omitempty,sanitizer" form:"check_update" json:"check_update"` + LoginRequired bool `json:"login_required"` + ExternalContentDisplay string `validate:"required,oneof=always_display ask_before_display" json:"external_content_display"` + CheckUpdate bool `validate:"omitempty,sanitizer" form:"check_update" json:"check_update"` + PersonalAccessTokensEnabled bool `json:"personal_access_tokens_enabled"` + PATReauthenticationWindowMinutes int `validate:"omitempty,min=5,max=120" json:"pat_reauthentication_window_minutes"` +} + +func (s *SiteSecurityReq) PATReauthenticationWindow() int { + if s.PATReauthenticationWindowMinutes == 0 { + return DefaultPATReauthenticationWindowMinutes + } + return s.PATReauthenticationWindowMinutes } type SitePoliciesResp SitePoliciesReq type SiteSecurityResp SiteSecurityReq +func (s *SiteSecurityResp) PATReauthenticationWindow() int { + if s.PATReauthenticationWindowMinutes == 0 { + return DefaultPATReauthenticationWindowMinutes + } + return s.PATReauthenticationWindowMinutes +} + // GetSiteLegalInfoReq site site legal request type GetSiteLegalInfoReq struct { InfoType string `validate:"required,oneof=tos privacy" form:"info_type"` diff --git a/internal/schema/siteinfo_schema_test.go b/internal/schema/siteinfo_schema_test.go index e5413f4a9..a66a651e2 100644 --- a/internal/schema/siteinfo_schema_test.go +++ b/internal/schema/siteinfo_schema_test.go @@ -28,6 +28,37 @@ import ( "github.com/stretchr/testify/require" ) +func TestSiteSecurityPATReauthenticationWindow(t *testing.T) { + tests := []struct { + name string + minutes int + expectError bool + expected int + }{ + {name: "omitted uses default", minutes: 0, expected: 60}, + {name: "minimum", minutes: 5, expected: 5}, + {name: "maximum", minutes: 120, expected: 120}, + {name: "below minimum", minutes: 4, expectError: true}, + {name: "above maximum", minutes: 121, expectError: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req := &SiteSecurityReq{ + ExternalContentDisplay: "always_display", + PATReauthenticationWindowMinutes: tt.minutes, + } + _, err := validator.GetValidatorByLang(i18n.DefaultLanguage).Check(req) + if tt.expectError { + require.Error(t, err) + return + } + require.NoError(t, err) + require.Equal(t, tt.expected, req.PATReauthenticationWindow()) + }) + } +} + func TestSiteLoginReqRequireEmailVerificationValidation(t *testing.T) { tests := []struct { name string diff --git a/internal/schema/user_schema.go b/internal/schema/user_schema.go index 0683a5aff..5752fab7d 100644 --- a/internal/schema/user_schema.go +++ b/internal/schema/user_schema.go @@ -240,12 +240,13 @@ func (u *UserRegisterReq) Check() (errFields []*validator.FormErrorField, err er } type UserModifyPasswordReq struct { - OldPass string `validate:"omitempty,gte=8,lte=32" json:"old_pass"` - Pass string `validate:"required,gte=8,lte=32" json:"pass"` - CaptchaID string `json:"captcha_id"` - CaptchaCode string `json:"captcha_code"` - UserID string `json:"-"` - AccessToken string `json:"-"` + OldPass string `validate:"omitempty,gte=8,lte=32" json:"old_pass"` + Pass string `validate:"required,gte=8,lte=32" json:"pass"` + CaptchaID string `json:"captcha_id"` + CaptchaCode string `json:"captcha_code"` + UserID string `json:"-"` + AccessToken string `json:"-"` + RevokePersonalAccessTokens bool `json:"revoke_personal_access_tokens"` } func (u *UserModifyPasswordReq) Check() (errFields []*validator.FormErrorField, err error) { diff --git a/internal/service/auth/auth.go b/internal/service/auth/auth.go index ac86b7ab6..ec533afa9 100644 --- a/internal/service/auth/auth.go +++ b/internal/service/auth/auth.go @@ -21,6 +21,7 @@ package auth import ( "context" + "time" "github.com/apache/answer/internal/entity" "github.com/apache/answer/internal/service/apikey" @@ -43,6 +44,7 @@ type AuthRepo interface { RemoveAdminUserCacheInfo(ctx context.Context, accessToken string) (err error) AddUserTokenMapping(ctx context.Context, userID, accessToken string) (err error) RemoveUserTokens(ctx context.Context, userID string, remainToken string) + GetUserCacheInfoByUserID(ctx context.Context, userID string) (userInfo *entity.UserCacheInfo, exist bool, err error) } // AuthService kit service @@ -91,6 +93,9 @@ func (as *AuthService) GetUserCacheInfo(ctx context.Context, accessToken string) func (as *AuthService) SetUserCacheInfo(ctx context.Context, userInfo *entity.UserCacheInfo) ( accessToken string, visitToken string, err error) { + if userInfo.AuthenticatedAt == 0 { + userInfo.AuthenticatedAt = time.Now().Unix() + } accessToken = token.GenerateToken() visitToken = token.GenerateToken() err = as.authRepo.SetUserCacheInfo(ctx, accessToken, visitToken, userInfo) @@ -100,6 +105,28 @@ func (as *AuthService) SetUserCacheInfo(ctx context.Context, userInfo *entity.Us return accessToken, visitToken, err } +func (as *AuthService) GetUserCacheInfoByUserID(ctx context.Context, userID string) (*entity.UserCacheInfo, error) { + userInfo, exist, err := as.authRepo.GetUserCacheInfoByUserID(ctx, userID) + if err != nil || !exist { + return nil, err + } + if uc, ok := plugin.GetUserCenter(); ok && len(userInfo.ExternalID) > 0 { + if userStatus := uc.UserStatus(userInfo.ExternalID); userStatus != plugin.UserStatusAvailable { + userInfo.UserStatus = int(userStatus) + } + } + return userInfo, nil +} + +func (as *AuthService) MarkReauthenticated(ctx context.Context, accessToken string) error { + userInfo, err := as.GetUserCacheInfo(ctx, accessToken) + if err != nil || userInfo == nil { + return err + } + userInfo.AuthenticatedAt = time.Now().Unix() + return as.authRepo.SetUserCacheInfo(ctx, accessToken, userInfo.VisitToken, userInfo) +} + func (as *AuthService) CheckUserVisitToken(ctx context.Context, visitToken string) bool { accessToken, err := as.authRepo.GetUserVisitCacheInfo(ctx, visitToken) if err != nil || len(accessToken) == 0 { diff --git a/internal/service/content/user_service.go b/internal/service/content/user_service.go index f556fa173..e0aef9822 100644 --- a/internal/service/content/user_service.go +++ b/internal/service/content/user_service.go @@ -43,6 +43,7 @@ import ( "github.com/apache/answer/internal/service/auth" "github.com/apache/answer/internal/service/export" "github.com/apache/answer/internal/service/file_record" + personalaccesstoken "github.com/apache/answer/internal/service/personal_access_token" "github.com/apache/answer/internal/service/role" "github.com/apache/answer/internal/service/siteinfo_common" usercommon "github.com/apache/answer/internal/service/user_common" @@ -70,6 +71,7 @@ type UserService struct { questionService *questioncommon.QuestionCommon eventQueueService eventqueue.Service fileRecordService *file_record.FileRecordService + personalAccessTokenService *personalaccesstoken.Service } func NewUserService(userRepo usercommon.UserRepo, @@ -86,6 +88,7 @@ func NewUserService(userRepo usercommon.UserRepo, questionService *questioncommon.QuestionCommon, eventQueueService eventqueue.Service, fileRecordService *file_record.FileRecordService, + personalAccessTokenService *personalaccesstoken.Service, ) *UserService { return &UserService{ userCommonService: userCommonService, @@ -102,6 +105,7 @@ func NewUserService(userRepo usercommon.UserRepo, questionService: questionService, eventQueueService: eventQueueService, fileRecordService: fileRecordService, + personalAccessTokenService: personalAccessTokenService, } } @@ -267,11 +271,25 @@ func (us *UserService) UpdatePasswordWhenForgot(ctx context.Context, req *schema if err != nil { return err } - // When the user changes the password, all the current user's tokens are invalid. + // Account recovery invalidates both login sessions and delegated credentials. us.authService.RemoveUserAllTokens(ctx, userInfo.ID) + if err := us.personalAccessTokenService.RevokeAll(ctx, userInfo.ID); err != nil { + return err + } return nil } +func (us *UserService) VerifyPassword(ctx context.Context, userID, password string) (bool, error) { + userInfo, has, err := us.userRepo.GetByUserID(ctx, userID) + if err != nil { + return false, err + } + if !has { + return false, errors.BadRequest(reason.UserNotFound) + } + return us.verifyPassword(ctx, password, userInfo.Pass), nil +} + func (us *UserService) UserModifyPassWordVerification(ctx context.Context, req *schema.UserModifyPasswordReq) (bool, error) { userInfo, has, err := us.userRepo.GetByUserID(ctx, req.UserID) if err != nil { @@ -312,6 +330,11 @@ func (us *UserService) UserModifyPassword(ctx context.Context, req *schema.UserM } us.authService.RemoveTokensExceptCurrentUser(ctx, userInfo.ID, req.AccessToken) + if req.RevokePersonalAccessTokens { + if err := us.personalAccessTokenService.RevokeAll(ctx, userInfo.ID); err != nil { + return err + } + } return nil } diff --git a/internal/service/personal_access_token/scope.go b/internal/service/personal_access_token/scope.go new file mode 100644 index 000000000..d326510d8 --- /dev/null +++ b/internal/service/personal_access_token/scope.go @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package personal_access_token + +import ( + "net/http" + "strings" +) + +type scopeRequirement struct { + all []string + any []string + scopeFree bool +} + +var routeScopes = map[string]scopeRequirement{ + route(http.MethodGet, "/question/info"): {all: []string{ScopeQuestionRead}}, + route(http.MethodGet, "/question/page"): {all: []string{ScopeQuestionRead}}, + route(http.MethodGet, "/question/recommend/page"): {all: []string{ScopeQuestionRead}}, + route(http.MethodGet, "/question/similar/tag"): {all: []string{ScopeQuestionRead}}, + route(http.MethodGet, "/question/link"): {all: []string{ScopeQuestionRead}}, + route(http.MethodGet, "/question/similar"): {any: []string{ScopeQuestionRead, ScopeQuestionCreate}}, + + route(http.MethodGet, "/answer/info"): {all: []string{ScopeAnswerRead}}, + route(http.MethodGet, "/answer/page"): {all: []string{ScopeAnswerRead}}, + + route(http.MethodGet, "/search"): {all: []string{ScopeQuestionRead, ScopeAnswerRead}}, + + route(http.MethodGet, "/question/tags"): {any: []string{ScopeQuestionRead, ScopeQuestionCreate}}, + route(http.MethodGet, "/tags/page"): {any: []string{ScopeQuestionRead, ScopeQuestionCreate}}, + route(http.MethodGet, "/tag"): {any: []string{ScopeQuestionRead, ScopeQuestionCreate}}, + route(http.MethodGet, "/tags"): {any: []string{ScopeQuestionRead, ScopeQuestionCreate}}, + route(http.MethodGet, "/tag/synonyms"): {any: []string{ScopeQuestionRead, ScopeQuestionCreate}}, + + route(http.MethodPost, "/question"): {all: []string{ScopeQuestionCreate}}, + route(http.MethodPost, "/answer"): {all: []string{ScopeAnswerCreate}}, + route(http.MethodPost, "/vote/up"): {all: []string{ScopeVoteWrite}}, + route(http.MethodPost, "/vote/down"): {all: []string{ScopeVoteWrite}}, + + route(http.MethodGet, "/personal-access-tokens/current"): {scopeFree: true}, +} + +func route(method, path string) string { + return method + " " + path +} + +// AuthorizeRoute applies the deny-by-default PAT route policy. +func AuthorizeRoute(method, fullPath string, scopes []string) (allowed bool, required []string) { + path := apiPath(fullPath) + requirement, exists := routeScopes[route(method, path)] + if !exists { + return false, []string{"unsupported"} + } + if requirement.scopeFree { + return true, nil + } + have := make(map[string]struct{}, len(scopes)) + for _, scope := range scopes { + have[scope] = struct{}{} + } + for _, scope := range requirement.all { + if _, ok := have[scope]; !ok { + return false, requirement.all + } + } + if len(requirement.any) > 0 { + for _, scope := range requirement.any { + if _, ok := have[scope]; ok { + return true, nil + } + } + return false, requirement.any + } + return true, nil +} + +func apiPath(fullPath string) string { + const prefix = "/answer/api/v1" + if index := strings.Index(fullPath, prefix); index >= 0 { + return fullPath[index+len(prefix):] + } + return fullPath +} diff --git a/internal/service/personal_access_token/scope_test.go b/internal/service/personal_access_token/scope_test.go new file mode 100644 index 000000000..1643a51ec --- /dev/null +++ b/internal/service/personal_access_token/scope_test.go @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package personal_access_token + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRoutePolicyIsDenyByDefault(t *testing.T) { + tests := []struct { + name string + method string + path string + scopes []string + allow bool + }{ + {name: "question read", method: http.MethodGet, path: "/answer/api/v1/question/info", scopes: []string{ScopeQuestionRead}, allow: true}, + {name: "question read missing", method: http.MethodGet, path: "/answer/api/v1/question/info", scopes: []string{ScopeAnswerRead}}, + {name: "search requires both reads", method: http.MethodGet, path: "/answer/api/v1/search", scopes: []string{ScopeQuestionRead}}, + {name: "search with both reads", method: http.MethodGet, path: "/answer/api/v1/search", scopes: []string{ScopeQuestionRead, ScopeAnswerRead}, allow: true}, + {name: "tag lookup supports creation", method: http.MethodGet, path: "/answer/api/v1/question/tags", scopes: []string{ScopeQuestionCreate}, allow: true}, + {name: "create question", method: http.MethodPost, path: "/answer/api/v1/question", scopes: []string{ScopeQuestionCreate}, allow: true}, + {name: "update question denied", method: http.MethodPut, path: "/answer/api/v1/question", scopes: []string{ScopeQuestionCreate}}, + {name: "notification denied", method: http.MethodGet, path: "/answer/api/v1/notification/page", scopes: []string{ScopeQuestionRead, ScopeAnswerRead}}, + {name: "token management denied", method: http.MethodPost, path: "/answer/api/v1/personal-access-tokens", scopes: []string{ScopeQuestionRead, ScopeQuestionCreate}}, + {name: "self inspection", method: http.MethodGet, path: "/answer/api/v1/personal-access-tokens/current", allow: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + allowed, required := AuthorizeRoute(tt.method, tt.path, tt.scopes) + require.Equal(t, tt.allow, allowed) + if !tt.allow { + require.NotEmpty(t, required) + } + }) + } +} diff --git a/internal/service/personal_access_token/service.go b/internal/service/personal_access_token/service.go new file mode 100644 index 000000000..167580047 --- /dev/null +++ b/internal/service/personal_access_token/service.go @@ -0,0 +1,288 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package personal_access_token + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "sort" + "strings" + "time" + + "github.com/apache/answer/internal/entity" +) + +const ( + TokenPrefix = "answer_pat_" + + ScopeQuestionRead = "question.read" + ScopeQuestionCreate = "question.create" + ScopeAnswerRead = "answer.read" + ScopeAnswerCreate = "answer.create" + ScopeVoteWrite = "vote.write" +) + +var ( + ErrInvalidToken = errors.New("invalid personal access token") + ErrInvalidScope = errors.New("invalid personal access token scope") + ErrInvalidExpiry = errors.New("invalid personal access token expiry") +) + +var allowedScopes = map[string]struct{}{ + ScopeQuestionRead: {}, + ScopeQuestionCreate: {}, + ScopeAnswerRead: {}, + ScopeAnswerCreate: {}, + ScopeVoteWrite: {}, +} + +// Repository persists Personal Access Tokens. +type Repository interface { + Create(ctx context.Context, token *entity.PersonalAccessToken) error + FindByHash(ctx context.Context, hash string) (*entity.PersonalAccessToken, bool, error) + ListByUserID(ctx context.Context, userID string) ([]*entity.PersonalAccessToken, error) + Revoke(ctx context.Context, userID string, id int64, revokedAt time.Time) (bool, error) + RevokeAllByUserID(ctx context.Context, userID string, revokedAt time.Time) error +} + +type Option func(*Service) + +// Service manages Personal Access Token lifecycle and authentication. +type Service struct { + repo Repository + now func() time.Time + generateSecret func() (string, error) +} + +func NewService(repo Repository) *Service { + return NewServiceWithOptions(repo) +} + +func NewServiceWithOptions(repo Repository, options ...Option) *Service { + s := &Service{ + repo: repo, + now: time.Now, + generateSecret: randomSecret, + } + for _, option := range options { + option(s) + } + return s +} + +func WithClock(now func() time.Time) Option { + return func(service *Service) { service.now = now } +} + +func WithSecretGenerator(generate func() (string, error)) Option { + return func(service *Service) { service.generateSecret = generate } +} + +type CreateInput struct { + UserID string + Name string + Scopes []string + ExpiresAt time.Time +} + +type Status string + +const ( + StatusActive Status = "active" + StatusExpired Status = "expired" + StatusRevoked Status = "revoked" +) + +type TokenInfo struct { + ID int64 + UserID string + Name string + TokenSuffix string + Scopes []string + CreatedAt time.Time + ExpiresAt time.Time + RevokedAt time.Time + Status Status +} + +type CreatedToken struct { + Token string + Info TokenInfo +} + +type AuthenticatedToken struct { + ID int64 + UserID string + Name string + TokenSuffix string + Scopes []string + CreatedAt time.Time + ExpiresAt time.Time +} + +func (s *Service) Create(ctx context.Context, input CreateInput) (*CreatedToken, error) { + now := s.now().UTC() + if input.ExpiresAt.After(now.Add(365*24*time.Hour)) || !input.ExpiresAt.After(now) { + return nil, ErrInvalidExpiry + } + scopes, err := CanonicalScopes(input.Scopes) + if err != nil { + return nil, err + } + secret, err := s.generateSecret() + if err != nil { + return nil, err + } + rawToken := TokenPrefix + secret + scopeJSON, err := json.Marshal(scopes) + if err != nil { + return nil, err + } + token := &entity.PersonalAccessToken{ + UserID: input.UserID, + Name: strings.TrimSpace(input.Name), + TokenHash: Hash(rawToken), + TokenSuffix: suffix(rawToken), + Scopes: string(scopeJSON), + CreatedAt: now, + ExpiresAt: input.ExpiresAt.UTC(), + } + if err := s.repo.Create(ctx, token); err != nil { + return nil, err + } + info := toInfo(token, scopes) + info.Status = StatusActive + return &CreatedToken{Token: rawToken, Info: info}, nil +} + +func (s *Service) List(ctx context.Context, userID string) ([]TokenInfo, error) { + tokens, err := s.repo.ListByUserID(ctx, userID) + if err != nil { + return nil, err + } + result := make([]TokenInfo, 0, len(tokens)) + for _, token := range tokens { + var scopes []string + if err := json.Unmarshal([]byte(token.Scopes), &scopes); err != nil { + return nil, err + } + info := toInfo(token, scopes) + info.Status = statusAt(token, s.now().UTC()) + result = append(result, info) + } + return result, nil +} + +func (s *Service) Revoke(ctx context.Context, userID string, id int64) error { + _, err := s.repo.Revoke(ctx, userID, id, s.now().UTC()) + return err +} + +func (s *Service) RevokeAll(ctx context.Context, userID string) error { + return s.repo.RevokeAllByUserID(ctx, userID, s.now().UTC()) +} + +func (s *Service) Authenticate(ctx context.Context, rawToken string) (*AuthenticatedToken, error) { + if !strings.HasPrefix(rawToken, TokenPrefix) || len(rawToken) <= len(TokenPrefix)+4 { + return nil, ErrInvalidToken + } + token, found, err := s.repo.FindByHash(ctx, Hash(rawToken)) + if err != nil { + return nil, err + } + if !found || !token.RevokedAt.IsZero() || !token.ExpiresAt.After(s.now().UTC()) { + return nil, ErrInvalidToken + } + var scopes []string + if err := json.Unmarshal([]byte(token.Scopes), &scopes); err != nil { + return nil, ErrInvalidToken + } + scopes, err = CanonicalScopes(scopes) + if err != nil { + return nil, ErrInvalidToken + } + return &AuthenticatedToken{ + ID: token.ID, UserID: token.UserID, Name: token.Name, + TokenSuffix: token.TokenSuffix, Scopes: scopes, CreatedAt: token.CreatedAt, + ExpiresAt: token.ExpiresAt, + }, nil +} + +func CanonicalScopes(scopes []string) ([]string, error) { + if len(scopes) == 0 { + return nil, ErrInvalidScope + } + unique := make(map[string]struct{}, len(scopes)) + for _, scope := range scopes { + if _, ok := allowedScopes[scope]; !ok { + return nil, ErrInvalidScope + } + unique[scope] = struct{}{} + } + result := make([]string, 0, len(unique)) + for scope := range unique { + result = append(result, scope) + } + sort.Strings(result) + return result, nil +} + +func Hash(rawToken string) string { + digest := sha256.Sum256([]byte(rawToken)) + return hex.EncodeToString(digest[:]) +} + +func randomSecret() (string, error) { + secret := make([]byte, 32) + if _, err := rand.Read(secret); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(secret), nil +} + +func suffix(token string) string { + if len(token) <= 4 { + return token + } + return token[len(token)-4:] +} + +func toInfo(token *entity.PersonalAccessToken, scopes []string) TokenInfo { + return TokenInfo{ + ID: token.ID, UserID: token.UserID, Name: token.Name, + TokenSuffix: token.TokenSuffix, Scopes: scopes, CreatedAt: token.CreatedAt, + ExpiresAt: token.ExpiresAt, RevokedAt: token.RevokedAt, + } +} + +func statusAt(token *entity.PersonalAccessToken, now time.Time) Status { + if !token.RevokedAt.IsZero() { + return StatusRevoked + } + if !token.ExpiresAt.After(now) { + return StatusExpired + } + return StatusActive +} diff --git a/internal/service/personal_access_token/service_test.go b/internal/service/personal_access_token/service_test.go new file mode 100644 index 000000000..b6e677211 --- /dev/null +++ b/internal/service/personal_access_token/service_test.go @@ -0,0 +1,163 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package personal_access_token_test + +import ( + "context" + "testing" + "time" + + "github.com/apache/answer/internal/entity" + pat "github.com/apache/answer/internal/service/personal_access_token" + "github.com/stretchr/testify/require" +) + +func TestUserCanCreateAndAuthenticatePersonalAccessToken(t *testing.T) { + now := time.Date(2026, time.September, 13, 12, 0, 0, 0, time.UTC) + repo := newMemoryRepository() + service := pat.NewServiceWithOptions(repo, + pat.WithClock(func() time.Time { return now }), + pat.WithSecretGenerator(func() (string, error) { return "0123456789abcdefghijklmnopqrstuvwxyzAB", nil }), + ) + + created, err := service.Create(context.Background(), pat.CreateInput{ + UserID: "42", + Name: "coding agent", + Scopes: []string{pat.ScopeVoteWrite, pat.ScopeQuestionRead, pat.ScopeQuestionRead}, + ExpiresAt: now.Add(30 * 24 * time.Hour), + }) + require.NoError(t, err) + require.Equal(t, "answer_pat_0123456789abcdefghijklmnopqrstuvwxyzAB", created.Token) + require.Equal(t, "yzAB", created.Info.TokenSuffix) + require.Equal(t, []string{pat.ScopeQuestionRead, pat.ScopeVoteWrite}, created.Info.Scopes) + + authenticated, err := service.Authenticate(context.Background(), created.Token) + require.NoError(t, err) + require.Equal(t, "42", authenticated.UserID) + require.Equal(t, []string{pat.ScopeQuestionRead, pat.ScopeVoteWrite}, authenticated.Scopes) + + stored := repo.byID[created.Info.ID] + require.NotContains(t, stored.TokenHash, created.Token) + require.NotContains(t, stored.Scopes, created.Token) +} + +func TestRevokedAndExpiredPersonalAccessTokensCannotAuthenticate(t *testing.T) { + now := time.Date(2026, time.September, 13, 12, 0, 0, 0, time.UTC) + repo := newMemoryRepository() + service := pat.NewServiceWithOptions(repo, + pat.WithClock(func() time.Time { return now }), + pat.WithSecretGenerator(func() (string, error) { return "0123456789abcdefghijklmnopqrstuvwxyzAB", nil }), + ) + + created, err := service.Create(context.Background(), pat.CreateInput{ + UserID: "42", Name: "coding agent", Scopes: []string{pat.ScopeQuestionRead}, + ExpiresAt: now.Add(time.Hour), + }) + require.NoError(t, err) + require.NoError(t, service.Revoke(context.Background(), "42", created.Info.ID)) + + _, err = service.Authenticate(context.Background(), created.Token) + require.ErrorIs(t, err, pat.ErrInvalidToken) + + listed, err := service.List(context.Background(), "42") + require.NoError(t, err) + require.Len(t, listed, 1) + require.Equal(t, pat.StatusRevoked, listed[0].Status) + + now = now.Add(2 * time.Hour) + repo.byID[created.Info.ID].RevokedAt = time.Time{} + listed, err = service.List(context.Background(), "42") + require.NoError(t, err) + require.Equal(t, pat.StatusExpired, listed[0].Status) +} + +func TestPersonalAccessTokenScopeMustBeKnownAndExpiryIsBounded(t *testing.T) { + now := time.Date(2026, time.September, 13, 12, 0, 0, 0, time.UTC) + service := pat.NewServiceWithOptions(newMemoryRepository(), pat.WithClock(func() time.Time { return now })) + + _, err := service.Create(context.Background(), pat.CreateInput{ + UserID: "42", Name: "invalid", Scopes: []string{"admin.access"}, ExpiresAt: now.Add(time.Hour), + }) + require.ErrorIs(t, err, pat.ErrInvalidScope) + + _, err = service.Create(context.Background(), pat.CreateInput{ + UserID: "42", Name: "too long", Scopes: []string{pat.ScopeQuestionRead}, ExpiresAt: now.Add(366 * 24 * time.Hour), + }) + require.ErrorIs(t, err, pat.ErrInvalidExpiry) +} + +type memoryRepository struct { + nextID int64 + byID map[int64]*entity.PersonalAccessToken +} + +func newMemoryRepository() *memoryRepository { + return &memoryRepository{nextID: 1, byID: make(map[int64]*entity.PersonalAccessToken)} +} + +func (r *memoryRepository) Create(_ context.Context, token *entity.PersonalAccessToken) error { + copy := *token + copy.ID = r.nextID + r.nextID++ + r.byID[copy.ID] = © + token.ID = copy.ID + return nil +} + +func (r *memoryRepository) FindByHash(_ context.Context, hash string) (*entity.PersonalAccessToken, bool, error) { + for _, token := range r.byID { + if token.TokenHash == hash { + copy := *token + return ©, true, nil + } + } + return nil, false, nil +} + +func (r *memoryRepository) ListByUserID(_ context.Context, userID string) ([]*entity.PersonalAccessToken, error) { + var result []*entity.PersonalAccessToken + for _, token := range r.byID { + if token.UserID == userID { + copy := *token + result = append(result, ©) + } + } + return result, nil +} + +func (r *memoryRepository) Revoke(_ context.Context, userID string, id int64, revokedAt time.Time) (bool, error) { + token, ok := r.byID[id] + if !ok || token.UserID != userID { + return false, nil + } + if token.RevokedAt.IsZero() { + token.RevokedAt = revokedAt + } + return true, nil +} + +func (r *memoryRepository) RevokeAllByUserID(_ context.Context, userID string, revokedAt time.Time) error { + for _, token := range r.byID { + if token.UserID == userID && token.RevokedAt.IsZero() { + token.RevokedAt = revokedAt + } + } + return nil +} diff --git a/internal/service/provider.go b/internal/service/provider.go index d848272f7..3396e6803 100644 --- a/internal/service/provider.go +++ b/internal/service/provider.go @@ -49,6 +49,7 @@ import ( "github.com/apache/answer/internal/service/notification" notficationcommon "github.com/apache/answer/internal/service/notification_common" "github.com/apache/answer/internal/service/object_info" + "github.com/apache/answer/internal/service/personal_access_token" "github.com/apache/answer/internal/service/plugin_common" questioncommon "github.com/apache/answer/internal/service/question_common" "github.com/apache/answer/internal/service/rank" @@ -134,6 +135,7 @@ var ProviderSetService = wire.NewSet( importer.NewImporterService, file_record.NewFileRecordService, apikey.NewAPIKeyService, + personal_access_token.NewService, ai_conversation.NewAIConversationService, feature_toggle.NewFeatureToggleService, embedding.NewEmbeddingService, diff --git a/internal/service/siteinfo_common/siteinfo_service.go b/internal/service/siteinfo_common/siteinfo_service.go index 752ae0510..e1bfdd1fb 100644 --- a/internal/service/siteinfo_common/siteinfo_service.go +++ b/internal/service/siteinfo_common/siteinfo_service.go @@ -226,7 +226,10 @@ func (s *siteInfoCommonService) GetSitePolicies(ctx context.Context) (resp *sche // GetSiteSecurity get site security config func (s *siteInfoCommonService) GetSiteSecurity(ctx context.Context) (resp *schema.SiteSecurityResp, err error) { - resp = &schema.SiteSecurityResp{CheckUpdate: true} + resp = &schema.SiteSecurityResp{ + CheckUpdate: true, + PATReauthenticationWindowMinutes: schema.DefaultPATReauthenticationWindowMinutes, + } if err = s.GetSiteInfoByType(ctx, constant.SiteTypeSecurity, resp); err != nil { return nil, err } diff --git a/internal/service/user_admin/user_backyard.go b/internal/service/user_admin/user_backyard.go index acbaf9965..7aa35e7cf 100644 --- a/internal/service/user_admin/user_backyard.go +++ b/internal/service/user_admin/user_backyard.go @@ -36,6 +36,7 @@ import ( "github.com/apache/answer/internal/service/comment_common" "github.com/apache/answer/internal/service/export" notificationcommon "github.com/apache/answer/internal/service/notification_common" + personalaccesstoken "github.com/apache/answer/internal/service/personal_access_token" "github.com/apache/answer/internal/service/plugin_common" questioncommon "github.com/apache/answer/internal/service/question_common" "github.com/apache/answer/pkg/token" @@ -74,21 +75,22 @@ type UserAdminRepo interface { // UserAdminService user service type UserAdminService struct { - userRepo UserAdminRepo - userRoleRelService *role.UserRoleRelService - authService *auth.AuthService - userCommonService *usercommon.UserCommon - userActivity activity.UserActiveActivityRepo - siteInfoCommonService siteinfo_common.SiteInfoCommonService - emailService *export.EmailService - questionCommonRepo questioncommon.QuestionRepo - answerCommonRepo answercommon.AnswerRepo - commentCommonRepo comment_common.CommentCommonRepo - userExternalLoginRepo user_external_login.UserExternalLoginRepo - notificationRepo notificationcommon.NotificationRepo - pluginUserConfigRepo plugin_common.PluginUserConfigRepo - badgeAwardRepo badge.BadgeAwardRepo - apiKeyRepo apikey.APIKeyRepo + userRepo UserAdminRepo + userRoleRelService *role.UserRoleRelService + authService *auth.AuthService + userCommonService *usercommon.UserCommon + userActivity activity.UserActiveActivityRepo + siteInfoCommonService siteinfo_common.SiteInfoCommonService + emailService *export.EmailService + questionCommonRepo questioncommon.QuestionRepo + answerCommonRepo answercommon.AnswerRepo + commentCommonRepo comment_common.CommentCommonRepo + userExternalLoginRepo user_external_login.UserExternalLoginRepo + notificationRepo notificationcommon.NotificationRepo + pluginUserConfigRepo plugin_common.PluginUserConfigRepo + badgeAwardRepo badge.BadgeAwardRepo + apiKeyRepo apikey.APIKeyRepo + personalAccessTokenService *personalaccesstoken.Service } // NewUserAdminService new user admin service @@ -108,23 +110,25 @@ func NewUserAdminService( pluginUserConfigRepo plugin_common.PluginUserConfigRepo, badgeAwardRepo badge.BadgeAwardRepo, apiKeyRepo apikey.APIKeyRepo, + personalAccessTokenService *personalaccesstoken.Service, ) *UserAdminService { return &UserAdminService{ - userRepo: userRepo, - userRoleRelService: userRoleRelService, - authService: authService, - userCommonService: userCommonService, - userActivity: userActivity, - siteInfoCommonService: siteInfoCommonService, - emailService: emailService, - questionCommonRepo: questionCommonRepo, - answerCommonRepo: answerCommonRepo, - commentCommonRepo: commentCommonRepo, - userExternalLoginRepo: userExternalLoginRepo, - notificationRepo: notificationRepo, - pluginUserConfigRepo: pluginUserConfigRepo, - badgeAwardRepo: badgeAwardRepo, - apiKeyRepo: apiKeyRepo, + userRepo: userRepo, + userRoleRelService: userRoleRelService, + authService: authService, + userCommonService: userCommonService, + userActivity: userActivity, + siteInfoCommonService: siteInfoCommonService, + emailService: emailService, + questionCommonRepo: questionCommonRepo, + answerCommonRepo: answerCommonRepo, + commentCommonRepo: commentCommonRepo, + userExternalLoginRepo: userExternalLoginRepo, + notificationRepo: notificationRepo, + pluginUserConfigRepo: pluginUserConfigRepo, + badgeAwardRepo: badgeAwardRepo, + apiKeyRepo: apiKeyRepo, + personalAccessTokenService: personalAccessTokenService, } } @@ -179,6 +183,9 @@ func (us *UserAdminService) UpdateUserStatus(ctx context.Context, req *schema.Up } if req.IsDeleted() { + if err := us.personalAccessTokenService.RevokeAll(ctx, userInfo.ID); err != nil { + return err + } us.removeAllUserConfiguration(ctx, userInfo.ID) } diff --git a/ui/package.json b/ui/package.json index 73fc2a8dd..0668fc364 100644 --- a/ui/package.json +++ b/ui/package.json @@ -7,7 +7,7 @@ "start": "vite", "build": "node ./scripts/env.js && tsc --noEmit && vite build", "preview": "vite preview", - "test": "vitest run", + "test": "vitest run --exclude '**/*.test.cjs' && node --test src/components/Editor/utils/codemirror/commands.test.cjs", "pre-install": "node ./scripts/importPlugins.js && pnpm install && node ./scripts/preinstall.js ", "prepare": "pnpm build:packages", "build:packages": "pnpm -r --filter=./src/plugins/* run build", @@ -58,6 +58,7 @@ "@commitlint/cli": "^17.0.3", "@commitlint/config-conventional": "^17.2.0", "@modyfi/vite-plugin-yaml": "^1.1.1", + "@testing-library/react": "^13.3.0", "@types/color": "^3.0.3", "@types/dompurify": "^2.4.0", "@types/lodash": "^4.14.184", @@ -83,6 +84,7 @@ "eslint-plugin-react-hooks": "^4.6.0", "husky": "^9.1.7", "js-yaml": "^4.1.0", + "jsdom": "^26.1.0", "lint-staged": "^15.5.0", "prettier": "^3.1.0", "sass": "1.79.6", diff --git a/ui/pnpm-lock.yaml b/ui/pnpm-lock.yaml index af7f3d82d..075eb7c70 100644 --- a/ui/pnpm-lock.yaml +++ b/ui/pnpm-lock.yaml @@ -114,6 +114,9 @@ importers: '@modyfi/vite-plugin-yaml': specifier: ^1.1.1 version: 1.1.1(rollup@4.63.4)(vite@8.2.0(@types/node@20.19.43)(esbuild@0.28.2)(jiti@1.21.6)(sass@1.79.6)(terser@5.37.0)(yaml@2.7.0)) + '@testing-library/react': + specifier: ^13.3.0 + version: 13.4.0(@types/react@18.3.16)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) '@types/color': specifier: ^3.0.3 version: 3.0.6 @@ -189,6 +192,9 @@ importers: js-yaml: specifier: ^4.1.0 version: 4.1.0 + jsdom: + specifier: ^26.1.0 + version: 26.1.0 lint-staged: specifier: ^15.5.0 version: 15.5.0 @@ -209,10 +215,13 @@ importers: version: 8.2.0(@types/node@20.19.43)(esbuild@0.28.2)(jiti@1.21.6)(sass@1.79.6)(terser@5.37.0)(yaml@2.7.0) vitest: specifier: ^4.0.18 - version: 4.0.18(@types/node@20.19.43)(jiti@1.21.6)(lightningcss@1.33.0)(sass@1.79.6)(terser@5.37.0)(yaml@2.7.0) + version: 4.0.18(@types/node@20.19.43)(jiti@1.21.6)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.79.6)(terser@5.37.0)(yaml@2.7.0) packages: + '@asamuzakjp/css-color@3.2.0': + resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==} + '@babel/code-frame@7.26.2': resolution: {integrity: sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==} engines: {node: '>=6.9.0'} @@ -390,6 +399,34 @@ packages: resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} + '@csstools/color-helpers@5.1.0': + resolution: {integrity: sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==} + engines: {node: '>=18'} + + '@csstools/css-calc@2.1.4': + resolution: {integrity: sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-parser-algorithms': ^3.0.5 + '@csstools/css-tokenizer': ^3.0.4 + + '@csstools/css-color-parser@3.1.0': + resolution: {integrity: sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-parser-algorithms': ^3.0.5 + '@csstools/css-tokenizer': ^3.0.4 + + '@csstools/css-parser-algorithms@3.0.5': + resolution: {integrity: sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-tokenizer': ^3.0.4 + + '@csstools/css-tokenizer@3.0.4': + resolution: {integrity: sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==} + engines: {node: '>=18'} + '@emnapi/core@2.0.0-alpha.3': resolution: {integrity: sha512-AZypUeJ/yByuxyS7BlSNRDOMLMlROYtjYdIAuBmJssVz1UJDSeYxLrdizhXCFYhedC5bqd/ASy8EuNXbVVXp9g==} @@ -1114,6 +1151,17 @@ packages: '@swc/types@0.1.25': resolution: {integrity: sha512-iAoY/qRhNH8a/hBvm3zKj9qQ4oc2+3w1unPJa2XvTK3XjeLXtzcCingVPw/9e5mn1+0yPqxcBGp9Jf0pkfMb1g==} + '@testing-library/dom@8.20.1': + resolution: {integrity: sha512-/DiOQ5xBxgdYRC8LNk7U+RWat0S3qRLeIw3ZIkMQ9kkVlRmwD/Eg8k8CqIpD6GW7u20JIUOfMKbxtiLutpjQ4g==} + engines: {node: '>=12'} + + '@testing-library/react@13.4.0': + resolution: {integrity: sha512-sXOGON+WNTh3MLE9rve97ftaZukN3oNf2KjDy7YTx6hcTO2uuLHuCGynMDhFwGw/jYf4OJ2Qk0i4i79qMNNkyw==} + engines: {node: '>=12'} + peerDependencies: + react: ^18.0.0 + react-dom: ^18.0.0 + '@tsconfig/node10@1.0.11': resolution: {integrity: sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==} @@ -1129,6 +1177,9 @@ packages: '@tybys/wasm-util@0.10.3': resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==} + '@types/aria-query@5.0.4': + resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==} + '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} @@ -1331,6 +1382,10 @@ packages: engines: {node: '>=0.4.0'} hasBin: true + agent-base@7.1.4: + resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} + engines: {node: '>= 14'} + ajv@6.12.6: resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} @@ -1353,6 +1408,10 @@ packages: resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} engines: {node: '>=8'} + ansi-styles@5.2.0: + resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} + engines: {node: '>=10'} + ansi-styles@6.2.1: resolution: {integrity: sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==} engines: {node: '>=12'} @@ -1366,6 +1425,9 @@ packages: argparse@2.0.1: resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + aria-query@5.1.3: + resolution: {integrity: sha512-R5iJ5lkuHybztUfuOAznmboyjWq8O6sqNqtK7CLOqdydi54VNbORp49mb14KbWgG1QD3JFO9hJdZ+y4KutfdOQ==} + aria-query@5.3.2: resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==} engines: {node: '>= 0.4'} @@ -1481,10 +1543,18 @@ packages: resolution: {integrity: sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==} engines: {node: '>= 0.4'} + call-bind-apply-helpers@1.0.2: + resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} + engines: {node: '>= 0.4'} + call-bind@1.0.8: resolution: {integrity: sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==} engines: {node: '>= 0.4'} + call-bound@1.0.4: + resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} + engines: {node: '>= 0.4'} + callsites@3.1.0: resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} engines: {node: '>=6'} @@ -1628,6 +1698,10 @@ packages: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} + cssstyle@4.6.0: + resolution: {integrity: sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==} + engines: {node: '>=18'} + csstype@3.1.3: resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==} @@ -1638,6 +1712,10 @@ packages: resolution: {integrity: sha512-2iy1EkLdlBzQGvbweYRFxmFath8+K7+AKB0TlhHWkNuH+TmovaMH/Wp7V7R4u7f4SnX3OgLsU9t1NI9ioDnUpg==} engines: {node: '>=8'} + data-urls@5.0.0: + resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==} + engines: {node: '>=18'} + data-view-buffer@1.0.1: resolution: {integrity: sha512-0lht7OugA5x3iJLOWFhWK/5ehONdprk0ISXqVFn/NFrDu+cuc8iADFrGQz5BnRK7LLU3JmkbXSxaqX+/mXYtUA==} engines: {node: '>= 0.4'} @@ -1686,6 +1764,13 @@ packages: resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==} engines: {node: '>=0.10.0'} + decimal.js@10.6.0: + resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + + deep-equal@2.2.3: + resolution: {integrity: sha512-ZIwpnevOurS8bpT4192sqAowWM76JDKSHYzMLty3BZGSswgq6pBaH3DhCSW5xVAZICZyKdOBPjwww5wfgT/6PA==} + engines: {node: '>= 0.4'} + deep-is@0.1.4: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} @@ -1732,6 +1817,9 @@ packages: resolution: {integrity: sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==} engines: {node: '>=6.0.0'} + dom-accessibility-api@0.5.16: + resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} + dom-helpers@5.2.1: resolution: {integrity: sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==} @@ -1743,6 +1831,10 @@ packages: resolution: {integrity: sha512-9+Sj30DIu+4KvHqMfLUGLFYL2PkURSYMVXJyXe92nFRvlYq5hBjLEhblKB+vkd/WVlUYMWigiY07T91Fkk0+4A==} engines: {node: '>= 0.4'} + dunder-proto@1.0.1: + resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} + engines: {node: '>= 0.4'} + duplexer@0.1.2: resolution: {integrity: sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==} @@ -1760,6 +1852,10 @@ packages: emoji-regex@9.2.2: resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + entities@6.0.1: + resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} + engines: {node: '>=0.12'} + environment@1.1.0: resolution: {integrity: sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==} engines: {node: '>=18'} @@ -1779,6 +1875,9 @@ packages: resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} engines: {node: '>= 0.4'} + es-get-iterator@1.1.3: + resolution: {integrity: sha512-sPZmqHBe6JIiTfN5q2pEi//TwxmAFHwj/XEuYjTuse78i8KxaqMTTzxPoFKuzRpDpTJ+0NAbpfenkmH2rePtuw==} + es-iterator-helpers@1.2.0: resolution: {integrity: sha512-tpxqxncxnpw3c93u8n3VOzACmRFoVmWJqbWXvX/JfKbkhBw1oslgPrUfeSt2psuqyEJFD6N/9lg5i7bsKpoq+Q==} engines: {node: '>= 0.4'} @@ -1790,6 +1889,10 @@ packages: resolution: {integrity: sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==} engines: {node: '>= 0.4'} + es-object-atoms@1.1.2: + resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} + engines: {node: '>= 0.4'} + es-set-tostringtag@2.0.3: resolution: {integrity: sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==} engines: {node: '>= 0.4'} @@ -2131,6 +2234,14 @@ packages: resolution: {integrity: sha512-Y4+pKa7XeRUPWFNvOOYHkRYrfzW07oraURSvjDmRVOJ748OrVmeXtpE4+GCEHncjCjkTxPNRt8kEbxDhsn6VTg==} engines: {node: '>= 0.4'} + get-intrinsic@1.3.0: + resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} + engines: {node: '>= 0.4'} + + get-proto@1.0.1: + resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} + engines: {node: '>= 0.4'} + get-stream@6.0.1: resolution: {integrity: sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==} engines: {node: '>=10'} @@ -2231,9 +2342,21 @@ packages: resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==} engines: {node: '>=10'} + html-encoding-sniffer@4.0.0: + resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==} + engines: {node: '>=18'} + html-parse-stringify@3.0.1: resolution: {integrity: sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==} + http-proxy-agent@7.0.2: + resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} + engines: {node: '>= 14'} + + https-proxy-agent@7.0.6: + resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} + engines: {node: '>= 14'} + human-signals@2.1.0: resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==} engines: {node: '>=10.17.0'} @@ -2250,6 +2373,10 @@ packages: i18next@21.10.0: resolution: {integrity: sha512-YeuIBmFsGjUfO3qBmMOc0rQaun4mIpGKET5WDwvu8lU7gvwpcariZLNtL0Fzj+zazcHUrlXHiptcFhBMFaxzfg==} + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + ignore@5.3.2: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} @@ -2286,9 +2413,17 @@ packages: resolution: {integrity: sha512-NGnrKwXzSms2qUUih/ILZ5JBqNTSa1+ZmP6flaIp6KmSElgE9qdndzS3cqjrDovwFdmwsGsLdeFgB6suw+1e9g==} engines: {node: '>= 0.4'} + internal-slot@1.1.0: + resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==} + engines: {node: '>= 0.4'} + invariant@2.2.4: resolution: {integrity: sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==} + is-arguments@1.2.0: + resolution: {integrity: sha512-7bVbi0huj/wrIAOzb8U1aszg9kdi3KN/CyU19CTI7tAoZYEZoL9yCDXpbXN+uPsuWnP02cyug1gleqq+TU+YCA==} + engines: {node: '>= 0.4'} + is-array-buffer@3.0.4: resolution: {integrity: sha512-wcjaerHw0ydZwfhiKbXJWLDY8A7yV7KhjQOpb83hGgGfId/aQa4TOvwyzn2PuswW2gPCYEL/nEAiSVpdOj1lXw==} engines: {node: '>= 0.4'} @@ -2392,6 +2527,9 @@ packages: resolution: {integrity: sha512-yvkRyxmFKEOQ4pNXCmJG5AEQNlXJS5LaONXo5/cLdTZdWvsZ1ioJEonLGAosKlMWE8lwUy/bJzMjcw8az73+Fg==} engines: {node: '>=0.10.0'} + is-potential-custom-element-name@1.0.1: + resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + is-regex@1.2.0: resolution: {integrity: sha512-B6ohK4ZmoftlUe+uvenXSbPJFo6U37BH7oO1B3nQH8f/7h27N56s85MhUtbFJAziz5dcmuR3i8ovUl35zp8pFA==} engines: {node: '>= 0.4'} @@ -2476,6 +2614,15 @@ packages: resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} hasBin: true + jsdom@26.1.0: + resolution: {integrity: sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==} + engines: {node: '>=18'} + peerDependencies: + canvas: ^3.0.0 + peerDependenciesMeta: + canvas: + optional: true + json-buffer@3.0.1: resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} @@ -2662,10 +2809,17 @@ packages: resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} hasBin: true + lru-cache@10.4.3: + resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==} + lru-cache@6.0.0: resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} engines: {node: '>=10'} + lz-string@1.5.0: + resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} + hasBin: true + magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} @@ -2685,6 +2839,10 @@ packages: engines: {node: '>= 12'} hasBin: true + math-intrinsics@1.1.0: + resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} + engines: {node: '>= 0.4'} + meow@8.1.2: resolution: {integrity: sha512-r85E3NdZ+mpYk1C6RjPFEMSE+s1iZMuHtsHAqY0DT3jZczl0diWUZ8g6oU7h0M9cD2EL+PzaYghhCLzR0ZNn5Q==} engines: {node: '>=10'} @@ -2787,6 +2945,9 @@ packages: resolution: {integrity: sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + nwsapi@2.2.28: + resolution: {integrity: sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==} + object-assign@4.1.1: resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} engines: {node: '>=0.10.0'} @@ -2795,6 +2956,14 @@ packages: resolution: {integrity: sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==} engines: {node: '>= 0.4'} + object-inspect@1.14.0: + resolution: {integrity: sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==} + engines: {node: '>= 0.4'} + + object-is@1.1.6: + resolution: {integrity: sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q==} + engines: {node: '>= 0.4'} + object-keys@1.1.1: resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} engines: {node: '>= 0.4'} @@ -2874,6 +3043,9 @@ packages: resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==} engines: {node: '>=8'} + parse5@7.3.0: + resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==} + path-exists@4.0.0: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} @@ -2945,6 +3117,10 @@ packages: engines: {node: '>=14'} hasBin: true + pretty-format@27.5.1: + resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} + engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} + prop-types-extra@1.1.1: resolution: {integrity: sha512-59+AHNnHYCdiC+vMwY52WmvP5dM3QLeoumYuEyceQDi9aEhtwN9zIQ2ZNo25sMyXnbh32h+P1ezDsUpUH3JAew==} peerDependencies: @@ -3016,6 +3192,9 @@ packages: react-is@16.13.1: resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==} + react-is@17.0.2: + resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==} + react-lifecycles-compat@3.0.4: resolution: {integrity: sha512-fBASbA6LnOU9dOU2eW7aQ8xmYBSXUIWr+UmF9b1efZBazGNO+rcXT/icdKnYm2pTwcRylVUYwW7H1PHfLekVzA==} @@ -3142,6 +3321,9 @@ packages: engines: {node: '>=18.0.0', npm: '>=8.0.0'} hasBin: true + rrweb-cssom@0.8.0: + resolution: {integrity: sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==} + run-parallel@1.2.0: resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} @@ -3156,11 +3338,18 @@ packages: resolution: {integrity: sha512-CdASjNJPvRa7roO6Ra/gLYBTzYzzPyyBXxIMdGW3USQLyjWEls2RgW5UBTXaQVp+OrpeCK3bLem8smtmheoRuw==} engines: {node: '>= 0.4'} + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + sass@1.79.6: resolution: {integrity: sha512-PVVjeeiUGx6Nj4PtEE/ecwu8ltwfPKzHxbbVmmLj4l1FYHhOyfA0scuVF8sVaa+b+VY4z7BVKjKq0cPUQdUU3g==} engines: {node: '>=14.0.0'} hasBin: true + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + scheduler@0.23.2: resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==} @@ -3207,10 +3396,26 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} + side-channel-list@1.0.1: + resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} + engines: {node: '>= 0.4'} + + side-channel-map@1.0.1: + resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==} + engines: {node: '>= 0.4'} + + side-channel-weakmap@1.0.2: + resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} + engines: {node: '>= 0.4'} + side-channel@1.0.6: resolution: {integrity: sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==} engines: {node: '>= 0.4'} + side-channel@1.1.1: + resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} + engines: {node: '>= 0.4'} + siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} @@ -3280,6 +3485,10 @@ packages: std-env@3.10.0: resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} + stop-iteration-iterator@1.1.0: + resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==} + engines: {node: '>= 0.4'} + string-argv@0.3.2: resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==} engines: {node: '>=0.6.19'} @@ -3361,6 +3570,9 @@ packages: peerDependencies: react: ^16.11.0 || ^17.0.0 || ^18.0.0 + symbol-tree@3.2.4: + resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} + synckit@0.9.2: resolution: {integrity: sha512-vrozgXDQwYO72vHjUb/HnFbQx1exDjoKzqx23aXEg2a9VIg2TSFZ8FmeZpTjUCFMYw7mpX4BE2SFu8wI7asYsw==} engines: {node: ^14.18.0 || >=16.0.0} @@ -3402,6 +3614,13 @@ packages: resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} engines: {node: '>=14.0.0'} + tldts-core@6.1.86: + resolution: {integrity: sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==} + + tldts@6.1.86: + resolution: {integrity: sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==} + hasBin: true + to-regex-range@5.0.1: resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} engines: {node: '>=8.0'} @@ -3413,6 +3632,14 @@ packages: resolution: {integrity: sha512-KAB2lrSS48y91MzFPFuDg4hLbvDiyTjOVgaK7Erw+5AmZXNq4sFRVn8r6yxSLuNs15PaokrDRpS61ERY9uZOug==} engines: {node: '>=10'} + tough-cookie@5.1.2: + resolution: {integrity: sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==} + engines: {node: '>=16'} + + tr46@5.1.1: + resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==} + engines: {node: '>=18'} + trigram-utils@2.0.1: resolution: {integrity: sha512-nfWIXHEaB+HdyslAfMxSqWKDdmqY9I32jS7GnqpdWQnLH89r6A5sdk3fDVYqGAZ0CrT8ovAFSAo6HRiWcWNIGQ==} @@ -3655,9 +3882,30 @@ packages: w3c-keyname@2.2.8: resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==} + w3c-xmlserializer@5.0.0: + resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} + engines: {node: '>=18'} + warning@4.0.3: resolution: {integrity: sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==} + webidl-conversions@7.0.0: + resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==} + engines: {node: '>=12'} + + whatwg-encoding@3.1.1: + resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==} + engines: {node: '>=18'} + deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation + + whatwg-mimetype@4.0.0: + resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==} + engines: {node: '>=18'} + + whatwg-url@14.2.0: + resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==} + engines: {node: '>=18'} + which-boxed-primitive@1.1.0: resolution: {integrity: sha512-Ei7Miu/AXe2JJ4iNF5j/UphAgRoma4trE6PtisM09bPygb3egMH3YLW/befsWb1A1AxvNSFidOFTB18XtnIIng==} engines: {node: '>= 0.4'} @@ -3706,6 +3954,25 @@ packages: wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + ws@8.23.0: + resolution: {integrity: sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + xml-name-validator@5.0.0: + resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} + engines: {node: '>=18'} + + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + y18n@4.0.3: resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==} @@ -3773,6 +4040,14 @@ packages: snapshots: + '@asamuzakjp/css-color@3.2.0': + dependencies: + '@csstools/css-calc': 2.1.4(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4) + '@csstools/css-color-parser': 3.1.0(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4) + '@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4) + '@csstools/css-tokenizer': 3.0.4 + lru-cache: 10.4.3 + '@babel/code-frame@7.26.2': dependencies: '@babel/helper-validator-identifier': 7.25.9 @@ -4159,6 +4434,26 @@ snapshots: dependencies: '@jridgewell/trace-mapping': 0.3.9 + '@csstools/color-helpers@5.1.0': {} + + '@csstools/css-calc@2.1.4(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4)': + dependencies: + '@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4) + '@csstools/css-tokenizer': 3.0.4 + + '@csstools/css-color-parser@3.1.0(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4)': + dependencies: + '@csstools/color-helpers': 5.1.0 + '@csstools/css-calc': 2.1.4(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4) + '@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4) + '@csstools/css-tokenizer': 3.0.4 + + '@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4)': + dependencies: + '@csstools/css-tokenizer': 3.0.4 + + '@csstools/css-tokenizer@3.0.4': {} + '@emnapi/core@2.0.0-alpha.3': dependencies: '@emnapi/wasi-threads': 2.0.1 @@ -4735,6 +5030,27 @@ snapshots: '@swc/counter': 0.1.3 optional: true + '@testing-library/dom@8.20.1': + dependencies: + '@babel/code-frame': 7.26.2 + '@babel/runtime': 7.26.0 + '@types/aria-query': 5.0.4 + aria-query: 5.1.3 + chalk: 4.1.2 + dom-accessibility-api: 0.5.16 + lz-string: 1.5.0 + pretty-format: 27.5.1 + + '@testing-library/react@13.4.0(@types/react@18.3.16)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@babel/runtime': 7.26.0 + '@testing-library/dom': 8.20.1 + '@types/react-dom': 18.3.5(@types/react@18.3.16) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + transitivePeerDependencies: + - '@types/react' + '@tsconfig/node10@1.0.11': {} '@tsconfig/node12@1.0.11': {} @@ -4748,6 +5064,8 @@ snapshots: tslib: 2.8.1 optional: true + '@types/aria-query@5.0.4': {} + '@types/chai@5.2.3': dependencies: '@types/deep-eql': 4.0.2 @@ -4773,7 +5091,7 @@ snapshots: '@types/eslint@9.6.1': dependencies: - '@types/estree': 1.0.6 + '@types/estree': 1.0.9 '@types/json-schema': 7.0.15 optional: true @@ -4969,6 +5287,8 @@ snapshots: acorn@8.14.0: {} + agent-base@7.1.4: {} + ajv@6.12.6: dependencies: fast-deep-equal: 3.1.3 @@ -4995,6 +5315,8 @@ snapshots: dependencies: color-convert: 2.0.1 + ansi-styles@5.2.0: {} + ansi-styles@6.2.1: {} arg@4.1.3: {} @@ -5005,6 +5327,10 @@ snapshots: argparse@2.0.1: {} + aria-query@5.1.3: + dependencies: + deep-equal: 2.2.3 + aria-query@5.3.2: {} array-buffer-byte-length@1.0.1: @@ -5139,6 +5465,11 @@ snapshots: es-errors: 1.3.0 function-bind: 1.1.2 + call-bind-apply-helpers@1.0.2: + dependencies: + es-errors: 1.3.0 + function-bind: 1.1.2 + call-bind@1.0.8: dependencies: call-bind-apply-helpers: 1.0.1 @@ -5146,6 +5477,11 @@ snapshots: get-intrinsic: 1.2.5 set-function-length: 1.2.2 + call-bound@1.0.4: + dependencies: + call-bind-apply-helpers: 1.0.2 + get-intrinsic: 1.3.0 + callsites@3.1.0: {} camelcase-keys@6.2.2: @@ -5297,12 +5633,22 @@ snapshots: shebang-command: 2.0.0 which: 2.0.2 + cssstyle@4.6.0: + dependencies: + '@asamuzakjp/css-color': 3.2.0 + rrweb-cssom: 0.8.0 + csstype@3.1.3: {} damerau-levenshtein@1.0.8: {} dargs@7.0.0: {} + data-urls@5.0.0: + dependencies: + whatwg-mimetype: 4.0.0 + whatwg-url: 14.2.0 + data-view-buffer@1.0.1: dependencies: call-bind: 1.0.8 @@ -5342,6 +5688,29 @@ snapshots: decamelize@1.2.0: {} + decimal.js@10.6.0: {} + + deep-equal@2.2.3: + dependencies: + array-buffer-byte-length: 1.0.1 + call-bind: 1.0.8 + es-get-iterator: 1.1.3 + get-intrinsic: 1.2.5 + is-arguments: 1.2.0 + is-array-buffer: 3.0.4 + is-date-object: 1.0.5 + is-regex: 1.2.0 + is-shared-array-buffer: 1.0.3 + isarray: 2.0.5 + object-is: 1.1.6 + object-keys: 1.1.1 + object.assign: 4.1.5 + regexp.prototype.flags: 1.5.3 + side-channel: 1.0.6 + which-boxed-primitive: 1.1.0 + which-collection: 1.0.2 + which-typed-array: 1.1.16 + deep-is@0.1.4: {} define-data-property@1.1.4: @@ -5380,6 +5749,8 @@ snapshots: dependencies: esutils: 2.0.3 + dom-accessibility-api@0.5.16: {} + dom-helpers@5.2.1: dependencies: '@babel/runtime': 7.26.0 @@ -5395,6 +5766,12 @@ snapshots: es-errors: 1.3.0 gopd: 1.2.0 + dunder-proto@1.0.1: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-errors: 1.3.0 + gopd: 1.2.0 + duplexer@0.1.2: {} ejs@3.1.10: @@ -5407,6 +5784,8 @@ snapshots: emoji-regex@9.2.2: {} + entities@6.0.1: {} + environment@1.1.0: {} error-ex@1.3.2: @@ -5466,6 +5845,18 @@ snapshots: es-errors@1.3.0: {} + es-get-iterator@1.1.3: + dependencies: + call-bind: 1.0.8 + get-intrinsic: 1.2.5 + has-symbols: 1.1.0 + is-arguments: 1.2.0 + is-map: 2.0.3 + is-set: 2.0.3 + is-string: 1.1.0 + isarray: 2.0.5 + stop-iteration-iterator: 1.1.0 + es-iterator-helpers@1.2.0: dependencies: call-bind: 1.0.8 @@ -5490,6 +5881,10 @@ snapshots: dependencies: es-errors: 1.3.0 + es-object-atoms@1.1.2: + dependencies: + es-errors: 1.3.0 + es-set-tostringtag@2.0.3: dependencies: get-intrinsic: 1.2.5 @@ -5947,6 +6342,24 @@ snapshots: has-symbols: 1.1.0 hasown: 2.0.2 + get-intrinsic@1.3.0: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + function-bind: 1.1.2 + get-proto: 1.0.1 + gopd: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.2 + math-intrinsics: 1.1.0 + + get-proto@1.0.1: + dependencies: + dunder-proto: 1.0.1 + es-object-atoms: 1.1.2 + get-stream@6.0.1: {} get-stream@8.0.1: {} @@ -6048,10 +6461,28 @@ snapshots: dependencies: lru-cache: 6.0.0 + html-encoding-sniffer@4.0.0: + dependencies: + whatwg-encoding: 3.1.1 + html-parse-stringify@3.0.1: dependencies: void-elements: 3.1.0 + http-proxy-agent@7.0.2: + dependencies: + agent-base: 7.1.4 + debug: 4.4.0 + transitivePeerDependencies: + - supports-color + + https-proxy-agent@7.0.6: + dependencies: + agent-base: 7.1.4 + debug: 4.4.0 + transitivePeerDependencies: + - supports-color + human-signals@2.1.0: {} human-signals@5.0.0: {} @@ -6062,6 +6493,10 @@ snapshots: dependencies: '@babel/runtime': 7.26.0 + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + ignore@5.3.2: {} immer@9.0.21: @@ -6093,10 +6528,21 @@ snapshots: hasown: 2.0.2 side-channel: 1.0.6 + internal-slot@1.1.0: + dependencies: + es-errors: 1.3.0 + hasown: 2.0.2 + side-channel: 1.1.1 + invariant@2.2.4: dependencies: loose-envify: 1.4.0 + is-arguments@1.2.0: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + is-array-buffer@3.0.4: dependencies: call-bind: 1.0.8 @@ -6178,6 +6624,8 @@ snapshots: is-plain-obj@1.1.0: {} + is-potential-custom-element-name@1.0.1: {} + is-regex@1.2.0: dependencies: call-bind: 1.0.8 @@ -6264,6 +6712,33 @@ snapshots: dependencies: argparse: 2.0.1 + jsdom@26.1.0: + dependencies: + cssstyle: 4.6.0 + data-urls: 5.0.0 + decimal.js: 10.6.0 + html-encoding-sniffer: 4.0.0 + http-proxy-agent: 7.0.2 + https-proxy-agent: 7.0.6 + is-potential-custom-element-name: 1.0.1 + nwsapi: 2.2.28 + parse5: 7.3.0 + rrweb-cssom: 0.8.0 + saxes: 6.0.0 + symbol-tree: 3.2.4 + tough-cookie: 5.1.2 + w3c-xmlserializer: 5.0.0 + webidl-conversions: 7.0.0 + whatwg-encoding: 3.1.1 + whatwg-mimetype: 4.0.0 + whatwg-url: 14.2.0 + ws: 8.23.0 + xml-name-validator: 5.0.0 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + json-buffer@3.0.1: {} json-parse-even-better-errors@2.3.1: {} @@ -6435,10 +6910,14 @@ snapshots: dependencies: js-tokens: 4.0.0 + lru-cache@10.4.3: {} + lru-cache@6.0.0: dependencies: yallist: 4.0.0 + lz-string@1.5.0: {} + magic-string@0.30.21: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 @@ -6451,6 +6930,8 @@ snapshots: marked@4.3.0: {} + math-intrinsics@1.1.0: {} + meow@8.1.2: dependencies: '@types/minimist': 1.2.5 @@ -6553,10 +7034,19 @@ snapshots: dependencies: path-key: 4.0.0 + nwsapi@2.2.28: {} + object-assign@4.1.1: {} object-inspect@1.13.3: {} + object-inspect@1.14.0: {} + + object-is@1.1.6: + dependencies: + call-bind: 1.0.8 + define-properties: 1.2.1 + object-keys@1.1.1: {} object.assign@4.1.5: @@ -6652,6 +7142,10 @@ snapshots: json-parse-even-better-errors: 2.3.1 lines-and-columns: 1.2.4 + parse5@7.3.0: + dependencies: + entities: 6.0.1 + path-exists@4.0.0: {} path-is-absolute@1.0.1: {} @@ -6694,6 +7188,12 @@ snapshots: prettier@3.4.2: {} + pretty-format@27.5.1: + dependencies: + ansi-regex: 5.0.1 + ansi-styles: 5.2.0 + react-is: 17.0.2 + prop-types-extra@1.1.1(react@18.3.1): dependencies: react: 18.3.1 @@ -6772,6 +7272,8 @@ snapshots: react-is@16.13.1: {} + react-is@17.0.2: {} + react-lifecycles-compat@3.0.4: {} react-router-dom@7.0.2(react-dom@18.3.1(react@18.3.1))(react@18.3.1): @@ -6947,6 +7449,8 @@ snapshots: '@rollup/rollup-win32-x64-msvc': 4.63.4 fsevents: 2.3.3 + rrweb-cssom@0.8.0: {} + run-parallel@1.2.0: dependencies: queue-microtask: 1.2.3 @@ -6966,6 +7470,8 @@ snapshots: es-errors: 1.3.0 is-regex: 1.2.0 + safer-buffer@2.1.2: {} + sass@1.79.6: dependencies: '@parcel/watcher': 2.6.0 @@ -6973,6 +7479,10 @@ snapshots: immutable: 4.3.7 source-map-js: 1.2.1 + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + scheduler@0.23.2: dependencies: loose-envify: 1.4.0 @@ -7015,6 +7525,26 @@ snapshots: shebang-regex@3.0.0: {} + side-channel-list@1.0.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.14.0 + + side-channel-map@1.0.1: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.2.5 + object-inspect: 1.14.0 + + side-channel-weakmap@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.2.5 + object-inspect: 1.14.0 + side-channel-map: 1.0.1 + side-channel@1.0.6: dependencies: call-bind: 1.0.8 @@ -7022,6 +7552,14 @@ snapshots: get-intrinsic: 1.2.5 object-inspect: 1.13.3 + side-channel@1.1.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.14.0 + side-channel-list: 1.0.1 + side-channel-map: 1.0.1 + side-channel-weakmap: 1.0.2 + siginfo@2.0.0: {} signal-exit@3.0.7: {} @@ -7096,6 +7634,11 @@ snapshots: std-env@3.10.0: {} + stop-iteration-iterator@1.1.0: + dependencies: + es-errors: 1.3.0 + internal-slot: 1.1.0 + string-argv@0.3.2: {} string-width@4.2.3: @@ -7191,6 +7734,8 @@ snapshots: dependencies: react: 18.3.1 + symbol-tree@3.2.4: {} + synckit@0.9.2: dependencies: '@pkgr/core': 0.1.1 @@ -7230,6 +7775,12 @@ snapshots: tinyrainbow@3.1.1: {} + tldts-core@6.1.86: {} + + tldts@6.1.86: + dependencies: + tldts-core: 6.1.86 + to-regex-range@5.0.1: dependencies: is-number: 7.0.0 @@ -7238,6 +7789,14 @@ snapshots: tosource@2.0.0-alpha.3: {} + tough-cookie@5.1.2: + dependencies: + tldts: 6.1.86 + + tr46@5.1.1: + dependencies: + punycode: 2.3.1 + trigram-utils@2.0.1: dependencies: collapse-white-space: 2.1.0 @@ -7403,7 +7962,7 @@ snapshots: terser: 5.37.0 yaml: 2.7.0 - vitest@4.0.18(@types/node@20.19.43)(jiti@1.21.6)(lightningcss@1.33.0)(sass@1.79.6)(terser@5.37.0)(yaml@2.7.0): + vitest@4.0.18(@types/node@20.19.43)(jiti@1.21.6)(jsdom@26.1.0)(lightningcss@1.33.0)(sass@1.79.6)(terser@5.37.0)(yaml@2.7.0): dependencies: '@vitest/expect': 4.0.18 '@vitest/mocker': 4.0.18(vite@7.3.6(@types/node@20.19.43)(jiti@1.21.6)(lightningcss@1.33.0)(sass@1.79.6)(terser@5.37.0)(yaml@2.7.0)) @@ -7427,6 +7986,7 @@ snapshots: why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 20.19.43 + jsdom: 26.1.0 transitivePeerDependencies: - jiti - less @@ -7444,10 +8004,27 @@ snapshots: w3c-keyname@2.2.8: {} + w3c-xmlserializer@5.0.0: + dependencies: + xml-name-validator: 5.0.0 + warning@4.0.3: dependencies: loose-envify: 1.4.0 + webidl-conversions@7.0.0: {} + + whatwg-encoding@3.1.1: + dependencies: + iconv-lite: 0.6.3 + + whatwg-mimetype@4.0.0: {} + + whatwg-url@14.2.0: + dependencies: + tr46: 5.1.1 + webidl-conversions: 7.0.0 + which-boxed-primitive@1.1.0: dependencies: is-bigint: 1.1.0 @@ -7520,6 +8097,12 @@ snapshots: wrappy@1.0.2: {} + ws@8.23.0: {} + + xml-name-validator@5.0.0: {} + + xmlchars@2.2.0: {} + y18n@4.0.3: {} y18n@5.0.8: {} diff --git a/ui/src/common/interface.ts b/ui/src/common/interface.ts index 479980278..2d9d1903e 100644 --- a/ui/src/common/interface.ts +++ b/ui/src/common/interface.ts @@ -117,6 +117,7 @@ export interface RegisterReqParams extends LoginReqParams { export interface ModifyPasswordReq { old_pass: string; pass: string; + revoke_personal_access_tokens?: boolean; } /** User */ @@ -410,6 +411,8 @@ export interface AdminSettingsSecurity { external_content_display: string; check_update: boolean; login_required: boolean; + personal_access_tokens_enabled: boolean; + pat_reauthentication_window_minutes: number; } export interface SiteSettings { @@ -812,6 +815,34 @@ export interface BadgeDetailListRes { list: BadgeDetailListItem[]; } +export type PersonalAccessTokenScope = + | 'question.read' + | 'question.create' + | 'answer.read' + | 'answer.create' + | 'vote.write'; + +export interface PersonalAccessTokenInfo { + id: number; + name: string; + token_suffix: string; + scopes: PersonalAccessTokenScope[]; + created_at: number; + expires_at: number; + revoked_at?: number; + status: 'active' | 'expired' | 'revoked' | 'temporarily_unavailable'; +} + +export interface CreatePersonalAccessTokenParams { + name: string; + scopes: PersonalAccessTokenScope[]; + expires_at: number; +} + +export interface CreatePersonalAccessTokenResp extends PersonalAccessTokenInfo { + token: string; +} + export interface AdminApiKeysItem { access_key: string; created_at: number; diff --git a/ui/src/pages/Admin/Security/index.tsx b/ui/src/pages/Admin/Security/index.tsx index 35d7f2f65..b501c9f2f 100644 --- a/ui/src/pages/Admin/Security/index.tsx +++ b/ui/src/pages/Admin/Security/index.tsx @@ -76,6 +76,20 @@ const Security = () => { title: t('check_update.label', { keyPrefix: 'admin.general' }), default: true, }, + personal_access_tokens_enabled: { + type: 'boolean', + title: t('personal_access_tokens.label'), + description: t('personal_access_tokens.text'), + default: false, + }, + pat_reauthentication_window_minutes: { + type: 'number', + title: t('pat_reauthentication_window.label'), + description: t('pat_reauthentication_window.text'), + min: 5, + max: 120, + default: 60, + }, }, }; const uiSchema: UISchema = { @@ -99,6 +113,18 @@ const Security = () => { label: t('check_update.label', { keyPrefix: 'admin.general' }), }, }, + personal_access_tokens_enabled: { + 'ui:widget': 'switch', + 'ui:options': { + label: t('personal_access_tokens.label'), + }, + }, + pat_reauthentication_window_minutes: { + 'ui:widget': 'input', + 'ui:options': { + inputType: 'number', + }, + }, }; const [formData, setFormData] = useState(initFormData(schema)); @@ -113,6 +139,10 @@ const Security = () => { login_required: formData.login_required.value, external_content_display: formData.external_content_display.value, check_update: formData.check_update.value, + personal_access_tokens_enabled: + formData.personal_access_tokens_enabled.value, + pat_reauthentication_window_minutes: + formData.pat_reauthentication_window_minutes.value, }; putSecuritySetting(reqParams) .then(() => { @@ -140,6 +170,10 @@ const Security = () => { formMeta.external_content_display.value = setting.external_content_display; formMeta.check_update.value = setting.check_update; + formMeta.personal_access_tokens_enabled.value = + setting.personal_access_tokens_enabled; + formMeta.pat_reauthentication_window_minutes.value = + setting.pat_reauthentication_window_minutes || 60; setFormData(formMeta); } }); diff --git a/ui/src/pages/Users/Settings/Account/components/ModifyPass/index.tsx b/ui/src/pages/Users/Settings/Account/components/ModifyPass/index.tsx index 4f4ec0cbf..27e2d5cda 100644 --- a/ui/src/pages/Users/Settings/Account/components/ModifyPass/index.tsx +++ b/ui/src/pages/Users/Settings/Account/components/ModifyPass/index.tsx @@ -53,6 +53,11 @@ const Index: FC = () => { isInvalid: false, errorMsg: '', }, + revoke_personal_access_tokens: { + value: false, + isInvalid: false, + errorMsg: '', + }, }); const infoCaptcha = useCaptchaPlugin('edit_userinfo'); @@ -141,6 +146,8 @@ const Index: FC = () => { const params: any = { old_pass: formData.old_pass.value, pass: formData.pass.value, + revoke_personal_access_tokens: + formData.revoke_personal_access_tokens.value, }; const imgCode = infoCaptcha?.getCaptcha(); @@ -256,6 +263,24 @@ const Index: FC = () => { {formData.pass2.errorMsg} + + + handleChange({ + revoke_personal_access_tokens: { + value: e.target.checked, + isInvalid: false, + errorMsg: '', + }, + }) + } + /> +
+ )} + setShowInactive(event.target.checked)} + /> + + + + + + + + + + + + {visibleTokens.map((item) => ( + + + + + + + + + ))} + +
{t('name')}{t('token')}{t('scopes')}{t('expires')}{t('status')} +
{item.name}answer_pat_••••{item.token_suffix} + {item.scopes.map((scope) => t(`scope.${scope}`)).join(', ')} + {dayjs.unix(item.expires_at).format('YYYY-MM-DD')} + + {t(`token_status.${item.status}`)} + + + {item.status === 'active' && ( + + )} +
+ + + + {t('create')} + + + + {t('name')} + setName(event.target.value)} + /> + + + {t('scopes')} + {scopeGroups.map((group) => ( +
+ + {t(`scope_group.${group.topic}`)} + + {group.scopes.map((scope) => ( + toggleScope(scope)} + /> + ))} +
+ ))} +
+ + {t('expiration')} + setExpirationDays(event.target.value)}> + {[7, 30, 90, 365].map((days) => ( + + ))} + + + {expirationDays === 'custom' && ( + setCustomExpiration(event.target.value)} + /> + )} + +
+ + + + +
+ + setShowSecret(false)}> + + {t('created_title')} + + +

{t('created_warning')}

+ +
+ + + +
+ + setShowReauthenticate(false)}> + + {t('reauthenticate')} + + + {user.have_password ? ( + setPassword(event.target.value)} + /> + ) : ( +

{t('reauthenticate_external')}

+ )} +
+ {user.have_password && ( + + + + )} +
+
+ ); +}; + +export default PersonalAccessTokens; diff --git a/ui/src/pages/Users/Settings/components/Nav/index.tsx b/ui/src/pages/Users/Settings/components/Nav/index.tsx index 6e2b0c076..a7ea5ba82 100644 --- a/ui/src/pages/Users/Settings/components/Nav/index.tsx +++ b/ui/src/pages/Users/Settings/components/Nav/index.tsx @@ -47,6 +47,9 @@ const Index: FC = () => { {t('interface')} + + {t('personal_access_tokens')} + {data?.map((item) => { return ( { + const { data, error, mutate } = useSWR( + endpoint, + request.instance.get, + ); + return { data, error, mutate, isLoading: !data && !error }; +}; + +export const createPersonalAccessToken = ( + params: Type.CreatePersonalAccessTokenParams, +) => request.post(endpoint, params); + +export const revokePersonalAccessToken = (id: number) => + request.delete(endpoint, { id }); + +export const reauthenticate = ( + params: { password: string } & Type.ImgCodeReq, +) => request.post('/answer/api/v1/user/reauthenticate', params); diff --git a/ui/src/stores/siteSecurity.ts b/ui/src/stores/siteSecurity.ts index e4e5bb52b..669f7eb62 100644 --- a/ui/src/stores/siteSecurity.ts +++ b/ui/src/stores/siteSecurity.ts @@ -23,10 +23,14 @@ interface SecurityStore { login_required: boolean; check_update: boolean; external_content_display: string; + personal_access_tokens_enabled: boolean; + pat_reauthentication_window_minutes: number; update: (params: { external_content_display: string; check_update: boolean; login_required: boolean; + personal_access_tokens_enabled: boolean; + pat_reauthentication_window_minutes: number; }) => void; } @@ -34,6 +38,8 @@ const siteSecurityStore = create((set) => ({ login_required: false, check_update: true, external_content_display: 'always_display', + personal_access_tokens_enabled: false, + pat_reauthentication_window_minutes: 60, update: (params) => set((state) => { return { diff --git a/ui/src/utils/request.ts b/ui/src/utils/request.ts index d74b7b434..326f6366e 100644 --- a/ui/src/utils/request.ts +++ b/ui/src/utils/request.ts @@ -83,10 +83,11 @@ class Request { data: errBody, config: errConfig, } = error.response || {}; - const { data = {}, msg = '' } = errBody || {}; + const { data = {}, msg = '', reason = '' } = errBody || {}; const errorObject: { code: any; + reason: string; msg: string; data: any; // Currently only used for form errors @@ -95,6 +96,7 @@ class Request { list?: any[]; } = { code: status, + reason, msg, data, }; @@ -155,6 +157,13 @@ class Request { return Promise.reject(false); } + if ( + status === 403 && + reason.startsWith('error.personal_access_token.') + ) { + return Promise.reject(errorObject); + } + if (status === 403) { // Permission interception if (data?.type === 'url_expired') { From f6c7496e8c41f063c7bb24cf151ca3c2f339e6f5 Mon Sep 17 00:00:00 2001 From: hgaol Date: Mon, 23 Nov 2026 14:20:09 +0000 Subject: [PATCH 2/3] docs(auth): remove standalone personal access token guide --- README.md | 2 - docs/personal-access-tokens.md | 141 --------------------------------- 2 files changed, 143 deletions(-) delete mode 100644 docs/personal-access-tokens.md diff --git a/README.md b/README.md index 2cb423707..64a0c2aa6 100644 --- a/README.md +++ b/README.md @@ -40,8 +40,6 @@ You can also check out the [plugins here](https://answer.apache.org/plugins). Administrators can enable **Personal access tokens** under **Admin → Security**. Users can create scoped, expiring tokens from **Settings → Personal access tokens** to use existing REST endpoints as their own account. -See [Personal access tokens](docs/personal-access-tokens.md) for setup, scopes, security behavior, and HTTP examples. - ## Building from Source ### Prerequisites diff --git a/docs/personal-access-tokens.md b/docs/personal-access-tokens.md deleted file mode 100644 index 1504af821..000000000 --- a/docs/personal-access-tokens.md +++ /dev/null @@ -1,141 +0,0 @@ - - -# Personal access tokens - -A personal access token (PAT) lets an HTTP client act as an existing Answer -user. The token's scopes limit the operations it can request. The user's -current permissions, reputation, account status, visibility rules, rate -limits, CAPTCHA requirements, and moderation policies still apply. - -Effective authority is the intersection of token scopes, current account -permissions, and instance policy. Administrator-managed instance API keys -remain a separate credential type. - -## Enable and create - -1. As an administrator, open **Admin → Security** and enable **Personal access - tokens**. The feature is disabled by default. -2. Set the reauthentication window if needed: the default is 60 minutes and - the supported range is 5–120 minutes. -3. As the token owner, open **Settings → Personal access tokens**. -4. Choose **Create token**, enter a name, explicitly select scopes, and choose - an expiration. Scopes are not preselected and do not imply one another. -5. Confirm the current password if recent authentication is required. Users - authenticating through an external identity provider can sign out and sign - in again through that provider. -6. Copy the secret from its one-time display. The complete secret cannot be - retrieved later; the server stores its SHA-256 digest and a display suffix. - -Expiration is mandatory and must be no more than 365 days in the future. - -| Scope | Permits | -| --- | --- | -| `question.read` | Question reads and related tag discovery | -| `question.create` | Question creation and supporting tag discovery | -| `answer.read` | Answer reads | -| `answer.create` | Answer creation | -| `vote.write` | Upvotes, downvotes, and vote retraction | - -Search requires both `question.read` and `answer.read`. A create scope does -not include the corresponding read scope. Routes outside the PAT allowlist -are denied even when the owner is an administrator. - -## Use an existing REST endpoint - -The supported transport is `Authorization: Bearer answer_pat_…`. Use your -instance's HTTPS URL and read the secret into a variable: - -```bash -export ANSWER_URL=https://answer.example.com -read -rsp 'Personal access token: ' ANSWER_PAT -echo - -curl --fail-with-body --silent --show-error \ - -H "Authorization: Bearer $ANSWER_PAT" \ - "$ANSWER_URL/answer/api/v1/personal-access-tokens/current" -``` - -Self-inspection returns the owner and token metadata, including scopes and -expiry. It does not return the complete secret. A bare token header or a -token supplied through the `Authorization` query parameter is rejected. - -For the following examples, select the matching create/read/vote scopes. -Choose an existing tag on the instance in place of `support`. - -```bash -curl --fail-with-body --silent --show-error \ - -H "Authorization: Bearer $ANSWER_PAT" \ - -H 'Content-Type: application/json' \ - -d '{"title":"How should we organize shared project knowledge?","content":"Which practices work well for maintaining useful questions and answers?","tags":[{"slug_name":"support","display_name":"support"}]}' \ - "$ANSWER_URL/answer/api/v1/question" -``` - -Use the returned question ID to post an answer: - -```bash -export QUESTION_ID='' -curl --fail-with-body --silent --show-error \ - -H "Authorization: Bearer $ANSWER_PAT" \ - -H 'Content-Type: application/json' \ - -d "{\"question_id\":\"$QUESTION_ID\",\"content\":\"Search before posting, write focused questions, and keep accepted answers current.\"}" \ - "$ANSWER_URL/answer/api/v1/answer" -``` - -For voting, choose an object owned by a different user. The owner must have -the required account permission and reputation: - -```bash -export OBJECT_ID='' -curl --fail-with-body --silent --show-error \ - -H "Authorization: Bearer $ANSWER_PAT" \ - -H 'Content-Type: application/json' \ - -d "{\"object_id\":\"$OBJECT_ID\",\"is_cancel\":false}" \ - "$ANSWER_URL/answer/api/v1/vote/up" -``` - -Use `is_cancel: true` to retract that vote. Use `/vote/down` for a downvote. -Content can enter the normal review flow, and requests can require CAPTCHA. - -## Revoke or disable - -Owners can list and revoke their own tokens in account settings. Revocation -is immediate and permanent. Expiry is also terminal. Disabling PAT support -blocks existing PAT authentication and new token creation; owners can still -revoke tokens. Re-enabling support resumes access only for tokens that remain -unexpired and unrevoked. - -Deleting an account or recovering its password revokes its PATs. The normal -password-change flow also offers a choice to revoke PATs. Current suspension, -verification, role, and external-user status continue to constrain access. - -Token management requires a browser login session; a PAT cannot create, list, -or revoke tokens. The management endpoints are: - -| Method | Path | Credential | -| --- | --- | --- | -| POST | `/answer/api/v1/user/reauthenticate` | Browser session | -| GET / POST / DELETE | `/answer/api/v1/personal-access-tokens` | Browser session | -| GET | `/answer/api/v1/personal-access-tokens/current` | PAT | - -OpenAPI describes request and response fields. Missing scope returns HTTP -403 with reason `error.personal_access_token.insufficient_scope`; disabled -access returns HTTP 403 with reason `error.feature.disabled`. Invalid, -expired, or revoked credentials return HTTP 401. Account and content policy -errors retain their existing server reasons and status codes. From 138b297233a73f6b6d9b78542f4998cf15e22bd8 Mon Sep 17 00:00:00 2001 From: hgaol Date: Thu, 26 Nov 2026 11:14:32 +0000 Subject: [PATCH 3/3] fix(auth): resolve PAT identity for the active user center Filter external login lookup by both user ID and the active UserCenter provider. Leave ExternalID empty when no UserCenter or matching binding exists, so unrelated OAuth identities are never sent to the plugin. Add regression coverage for disabled UserCenter, missing bindings, unrelated and inactive providers, matching bindings, and multiple providers, including another user's binding. Addresses the review comment on apache/answer#1686. --- internal/repo/auth/auth.go | 17 ++++-- .../service/auth/user_center_status_test.go | 59 +++++++++++++++++++ 2 files changed, 70 insertions(+), 6 deletions(-) diff --git a/internal/repo/auth/auth.go b/internal/repo/auth/auth.go index a9e5ed270..ed945dc99 100644 --- a/internal/repo/auth/auth.go +++ b/internal/repo/auth/auth.go @@ -29,6 +29,7 @@ import ( "github.com/apache/answer/internal/base/data" "github.com/apache/answer/internal/base/reason" "github.com/apache/answer/internal/entity" + "github.com/apache/answer/plugin" "github.com/segmentfault/pacman/errors" "github.com/segmentfault/pacman/log" ) @@ -207,7 +208,7 @@ func (ar *authRepo) AddUserTokenMapping(ctx context.Context, userID, accessToken return ar.data.Cache.SetString(ctx, key, string(content), constant.UserTokenCacheTime) } -// RemoveUserTokens Log out all users under this user id +// GetUserCacheInfoByUserID reloads account state and the active UserCenter binding. func (ar *authRepo) GetUserCacheInfoByUserID(ctx context.Context, userID string) (*entity.UserCacheInfo, bool, error) { user := &entity.User{} exists, err := ar.data.DB.Context(ctx).ID(userID).Get(user) @@ -227,11 +228,15 @@ func (ar *authRepo) GetUserCacheInfoByUserID(ctx context.Context, userID string) } externalID := "" - externalLogin := &entity.UserExternalLogin{} - if hasExternal, externalErr := ar.data.DB.Context(ctx).Where("user_id = ?", userID).Get(externalLogin); externalErr != nil { - return nil, false, errors.InternalServer(reason.DatabaseError).WithError(externalErr).WithStack() - } else if hasExternal { - externalID = externalLogin.ExternalID + if userCenter, enabled := plugin.GetUserCenter(); enabled { + externalLogin := &entity.UserExternalLogin{} + if hasExternal, externalErr := ar.data.DB.Context(ctx). + Where("user_id = ? AND provider = ?", userID, userCenter.Info().SlugName). + Get(externalLogin); externalErr != nil { + return nil, false, errors.InternalServer(reason.DatabaseError).WithError(externalErr).WithStack() + } else if hasExternal { + externalID = externalLogin.ExternalID + } } return &entity.UserCacheInfo{ diff --git a/internal/service/auth/user_center_status_test.go b/internal/service/auth/user_center_status_test.go index df8b379e3..56c3f47b4 100644 --- a/internal/service/auth/user_center_status_test.go +++ b/internal/service/auth/user_center_status_test.go @@ -22,6 +22,7 @@ package auth_test import ( "context" "fmt" + "path/filepath" "testing" "github.com/apache/answer/internal/base/data" @@ -29,8 +30,66 @@ import ( authrepo "github.com/apache/answer/internal/repo/auth" authservice "github.com/apache/answer/internal/service/auth" "github.com/apache/answer/plugin" + "github.com/stretchr/testify/require" ) +func TestGetUserCacheInfoByUserIDUsesActiveUserCenterBinding(t *testing.T) { + tests := []struct { + name string + enabled bool + bindings []entity.UserExternalLogin + externalID string + }{ + {name: "no user center", bindings: []entity.UserExternalLogin{{Provider: "github", ExternalID: "github-user"}}}, + {name: "no binding", enabled: true}, + {name: "github only", enabled: true, bindings: []entity.UserExternalLogin{{Provider: "github", ExternalID: "github-user"}}}, + {name: "inactive user center", enabled: true, bindings: []entity.UserExternalLogin{{Provider: "inactive-user-center", ExternalID: "inactive-user"}}}, + {name: "active user center", enabled: true, bindings: []entity.UserExternalLogin{{Provider: "auth-test-user-center", ExternalID: "central-user"}}, externalID: "central-user"}, + {name: "multiple providers", enabled: true, bindings: []entity.UserExternalLogin{ + {Provider: "github", ExternalID: "github-user"}, + {Provider: "auth-test-user-center", ExternalID: "central-user"}, + }, externalID: "central-user"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + db, err := data.NewDB(false, &data.Database{Driver: "sqlite3", Connection: filepath.Join(t.TempDir(), "auth.db")}) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, db.Close()) }) + require.NoError(t, db.Sync2(new(entity.User), new(entity.UserRoleRel), new(entity.UserExternalLogin))) + _, err = db.Insert(&entity.User{ID: "1", Status: entity.UserStatusAvailable, MailStatus: entity.EmailStatusAvailable}) + require.NoError(t, err) + // A matching provider binding belonging to another user must also be ignored. + _, err = db.Insert(&entity.UserExternalLogin{UserID: "2", Provider: "auth-test-user-center", ExternalID: "another-user"}) + require.NoError(t, err) + for _, binding := range tt.bindings { + binding.UserID = "1" + _, err = db.Insert(&binding) + require.NoError(t, err) + } + previous := plugin.CallUserCenter + center := &authTestUserCenter{status: plugin.UserStatusSuspended} + plugin.CallUserCenter = func(call plugin.Caller[plugin.UserCenter]) error { + if tt.enabled { + return call(center) + } + return nil + } + t.Cleanup(func() { plugin.CallUserCenter = previous }) + service := authservice.NewAuthService(authrepo.NewAuthRepo(&data.Data{DB: db}), nil) + user, err := service.GetUserCacheInfoByUserID(t.Context(), "1") + require.NoError(t, err) + require.NotNil(t, user) + require.Equal(t, tt.externalID, user.ExternalID) + require.Equal(t, tt.externalID, center.externalID) + expectedStatus := entity.UserStatusAvailable + if tt.externalID != "" { + expectedStatus = entity.UserStatusSuspended + } + require.Equal(t, expectedStatus, user.UserStatus) + }) + } +} + func TestGetUserCacheInfoChecksUserCenterStatus(t *testing.T) { cache, cleanup, err := data.NewCache(&data.CacheConf{}) if err != nil {