This is an automated email from the ASF dual-hosted git repository. lahirujayathilake pushed a commit to branch custos-apps in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit 541480d83fc8bac602a7a686ff84bd17186ad547 Author: lahiruj <[email protected]> AuthorDate: Tue Nov 10 01:33:29 2026 -0500 Custos app implementation --- api/core.openapi.yaml | 473 ++++++++++++++++++++++++++++ cmd/server/main.go | 3 +- docs/privileges.md | 9 +- internal/db/migrations/000009_apps.down.sql | 19 ++ internal/db/migrations/000009_apps.up.sql | 44 +++ internal/server/app.go | 253 +++++++++++++++ internal/server/server.go | 10 + internal/store/app_store.go | 109 +++++++ internal/store/store.go | 11 + pkg/identity/app_middleware_test.go | 96 ++++++ pkg/identity/identity.go | 9 + pkg/identity/middleware.go | 58 +++- pkg/models/app.go | 90 ++++++ pkg/models/privilege.go | 2 + pkg/service/app.go | 223 +++++++++++++ pkg/service/app_integration_test.go | 219 +++++++++++++ pkg/service/interface.go | 12 + pkg/service/mock.go | 454 ++++++++++++++++++++++++++ pkg/service/service.go | 3 + pkg/service/user_role.go | 4 +- 20 files changed, 2092 insertions(+), 9 deletions(-) diff --git a/api/core.openapi.yaml b/api/core.openapi.yaml index c46fb47ae..623b47e08 100644 --- a/api/core.openapi.yaml +++ b/api/core.openapi.yaml @@ -40,6 +40,25 @@ definitions: - ACTIVE - INACTIVE - DELETED + AppConnector: + properties: + actions: + items: + type: string + type: array + name: + type: string + needs_user_grant: + type: boolean + type: object + AppStatus: + enum: + - ACTIVE + - DISABLED + type: string + x-enum-varnames: + - AppActive + - AppDisabled AuditEvent: properties: details: @@ -657,6 +676,7 @@ definitions: - core:events:manage - core:agreements:read - core:agreements:manage + - core:apps:manage type: string x-enum-varnames: - ClustersRead @@ -675,6 +695,7 @@ definitions: - EventsManage - AgreementsRead - AgreementsManage + - AppsManage Project: properties: created_time: @@ -1108,6 +1129,73 @@ definitions: name: type: string type: object + appNameView: + properties: + key: + type: string + name: + type: string + type: object + appView: + properties: + actions: + items: + type: string + type: array + connector: + type: string + created_at: + type: string + created_by: + type: string + description: + type: string + id: + type: string + key: + type: string + name: + type: string + needs_user_authorization: + type: boolean + secret_hint: + type: string + status: + $ref: '#/definitions/AppStatus' + updated_at: + type: string + type: object + appWithTokenView: + properties: + actions: + items: + type: string + type: array + connector: + type: string + created_at: + type: string + created_by: + type: string + description: + type: string + id: + type: string + key: + type: string + name: + type: string + needs_user_authorization: + type: boolean + secret_hint: + type: string + status: + $ref: '#/definitions/AppStatus' + token: + type: string + updated_at: + type: string + type: object attachResourceRequest: properties: compute_allocation_resource_id: @@ -1124,6 +1212,19 @@ definitions: $ref: '#/definitions/UserAgreement' type: array type: object + createAppRequest: + properties: + actions: + items: + type: string + type: array + description: + type: string + key: + type: string + name: + type: string + type: object createComputeClusterUserRequest: properties: compute_cluster_id: @@ -1246,6 +1347,13 @@ definitions: resource_time: type: integer type: object + updateAppRequest: + properties: + description: + type: string + name: + type: string + type: object updateProjectRequest: properties: project_pi_id: @@ -1752,6 +1860,368 @@ paths: summary: Remove a published user agreement tags: - Agreements + /apps: + get: + produces: + - application/json + responses: + "200": + description: OK + schema: + items: + $ref: '#/definitions/appView' + type: array + "401": + description: Unauthorized + schema: + properties: + error: + type: string + type: object + "403": + description: Caller lacks apps:manage + schema: + properties: + error: + type: string + type: object + security: + - BearerAuth: [] + summary: List apps + tags: + - Apps + post: + consumes: + - application/json + description: The token is returned only here. + parameters: + - description: App + in: body + name: request + required: true + schema: + $ref: '#/definitions/createAppRequest' + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/appWithTokenView' + "400": + description: Bad Request + schema: + properties: + error: + type: string + type: object + "401": + description: Unauthorized + schema: + properties: + error: + type: string + type: object + "403": + description: Caller lacks apps:manage + schema: + properties: + error: + type: string + type: object + "409": + description: That key or name is taken + schema: + properties: + error: + type: string + type: object + security: + - BearerAuth: [] + summary: Create an app + tags: + - Apps + /apps/{id}: + get: + parameters: + - description: App ID + in: path + name: id + required: true + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appView' + "401": + description: Unauthorized + schema: + properties: + error: + type: string + type: object + "403": + description: Caller lacks apps:manage + schema: + properties: + error: + type: string + type: object + "404": + description: Not Found + schema: + properties: + error: + type: string + type: object + security: + - BearerAuth: [] + summary: Get an app + tags: + - Apps + put: + consumes: + - application/json + parameters: + - description: App ID + in: path + name: id + required: true + type: string + - description: Name and description + in: body + name: request + required: true + schema: + $ref: '#/definitions/updateAppRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appView' + "400": + description: Bad Request + schema: + properties: + error: + type: string + type: object + "401": + description: Unauthorized + schema: + properties: + error: + type: string + type: object + "403": + description: Caller lacks apps:manage + schema: + properties: + error: + type: string + type: object + "404": + description: Not Found + schema: + properties: + error: + type: string + type: object + "409": + description: That name is taken + schema: + properties: + error: + type: string + type: object + security: + - BearerAuth: [] + summary: Edit an app's name and description + tags: + - Apps + /apps/{id}/disable: + post: + parameters: + - description: App ID + in: path + name: id + required: true + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appView' + "401": + description: Unauthorized + schema: + properties: + error: + type: string + type: object + "403": + description: Caller lacks apps:manage + schema: + properties: + error: + type: string + type: object + "404": + description: Not Found + schema: + properties: + error: + type: string + type: object + security: + - BearerAuth: [] + summary: Disable an app + tags: + - Apps + /apps/{id}/enable: + post: + parameters: + - description: App ID + in: path + name: id + required: true + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appView' + "401": + description: Unauthorized + schema: + properties: + error: + type: string + type: object + "403": + description: Caller lacks apps:manage + schema: + properties: + error: + type: string + type: object + "404": + description: Not Found + schema: + properties: + error: + type: string + type: object + security: + - BearerAuth: [] + summary: Enable an app + tags: + - Apps + /apps/{id}/secret: + post: + description: The old token stops working at once. The new token is returned + only here. + parameters: + - description: App ID + in: path + name: id + required: true + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appWithTokenView' + "401": + description: Unauthorized + schema: + properties: + error: + type: string + type: object + "403": + description: Caller lacks apps:manage + schema: + properties: + error: + type: string + type: object + "404": + description: Not Found + schema: + properties: + error: + type: string + type: object + security: + - BearerAuth: [] + summary: Issue a new secret for an app + tags: + - Apps + /apps/connectors: + get: + produces: + - application/json + responses: + "200": + description: OK + schema: + items: + $ref: '#/definitions/AppConnector' + type: array + "401": + description: Unauthorized + schema: + properties: + error: + type: string + type: object + "403": + description: Caller lacks apps:manage + schema: + properties: + error: + type: string + type: object + security: + - BearerAuth: [] + summary: List the connectors apps can use and their actions + tags: + - Apps + /apps/names: + get: + produces: + - application/json + responses: + "200": + description: OK + schema: + items: + $ref: '#/definitions/appNameView' + type: array + "401": + description: Unauthorized + schema: + properties: + error: + type: string + type: object + security: + - BearerAuth: [] + summary: List the key and name of every app, including disabled ones + tags: + - Apps /audit/events: get: parameters: @@ -4466,6 +4936,7 @@ paths: - core:events:manage - core:agreements:read - core:agreements:manage + - core:apps:manage in: path name: key required: true @@ -5124,6 +5595,7 @@ paths: - core:events:manage - core:agreements:read - core:agreements:manage + - core:apps:manage in: path name: key required: true @@ -5786,6 +6258,7 @@ paths: - core:events:manage - core:agreements:read - core:agreements:manage + - core:apps:manage in: path name: key required: true diff --git a/cmd/server/main.go b/cmd/server/main.go index 429130b70..6412c1bfa 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -158,7 +158,8 @@ func run() error { // identity.Middleware sits in front of the router-backed server, so every // gated route sees a verified caller + privilege set on ctx. authed := identity.Middleware(verifier, svc, router.PublicRoutes(), router.WithoutUserConsentRoutes(), srv) - handler := server.LoggingMiddleware(tracing.Middleware(authed)) + routed := identity.AppMiddleware(svc, router.AppRoutes(), srv, authed) + handler := server.LoggingMiddleware(tracing.Middleware(routed)) httpServer := &http.Server{ Addr: addr, diff --git a/docs/privileges.md b/docs/privileges.md index 1f2c24946..28a131f36 100644 --- a/docs/privileges.md +++ b/docs/privileges.md @@ -62,6 +62,7 @@ A key exists only once it is registered with `models.Register(...)`. Grants and | `core:roles:manage` | `GET /roles`<br>`POST /roles`<br>`GET /roles/{id}`<br>`PUT /roles/{id}`<br>`DELETE /roles/{id}`<br>`POST /roles/{id}/privileges`<br>`DELETE /roles/{id}/privileges/{key}`<br>`GET /roles/{id}/holders`<br>`GET /users/{id}/roles`<br>`POST /users/{id}/roles`<br>`DELETE /users/{id}/roles/{roleId}` [...] | `core:agreements:read` | `GET /agreements`<br>`GET /agreements/{id}`<br>`GET /agreements/{id}/acceptances` [...] | `core:agreements:manage` | `POST /agreements`<br>`PUT /agreements/{id}`<br>`DELETE /agreements/{id}`<br>`POST /agreements/{id}/publish`<br>`POST /agreements/{id}/remove` [...] +| `core:apps:manage` | `GET /apps`<br>`POST /apps`<br>`GET /apps/connectors`<br>`GET /apps/{id}`<br>`PUT /apps/{id}`<br>`POST /apps/{id}/disable`<br>`POST /apps/{id}/enable`<br>`POST /apps/{id}/secret` [...] `POST /users` with `portal_admin` or `cluster_admin` set also requires `core:roles:manage`. @@ -114,10 +115,10 @@ no route on a key. Two roles are created by the server and marked `is_system`. -| Role | Privileges | Created | -|---------------|----------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------| -| `super_admin` | All keys registered at startup, core and connector alike | At startup, for the user named by `CUSTOS_BOOTSTRAP_ADMIN_EMAIL` ([CONFIG.md](../CONFIG.md#environment-variables-read-directly)) | -| `admin` | All registered keys except `core:privileges:grant` and `core:roles:manage` | The first time `POST /users` onboards a portal admin. Its keys are set only then | +| Role | Privileges | Created | +|---------------|------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------| +| `super_admin` | All keys registered at startup, core and connector alike | At startup, for the user named by `CUSTOS_BOOTSTRAP_ADMIN_EMAIL` ([CONFIG.md](../CONFIG.md#environment-variables-read-directly)) | +| `admin` | All registered keys except `core:privileges:grant`, `core:roles:manage` and `core:apps:manage` | The first time `POST /users` onboards a portal admin. Its keys are set only then | Two revoke paths guard against locking every administrator out: diff --git a/internal/db/migrations/000009_apps.down.sql b/internal/db/migrations/000009_apps.down.sql new file mode 100644 index 000000000..d933138f0 --- /dev/null +++ b/internal/db/migrations/000009_apps.down.sql @@ -0,0 +1,19 @@ +-- 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. + +DROP TABLE IF EXISTS app_actions; +DROP TABLE IF EXISTS apps; diff --git a/internal/db/migrations/000009_apps.up.sql b/internal/db/migrations/000009_apps.up.sql new file mode 100644 index 000000000..09b21e6e1 --- /dev/null +++ b/internal/db/migrations/000009_apps.up.sql @@ -0,0 +1,44 @@ +-- 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. + +CREATE TABLE IF NOT EXISTS apps +( + id VARCHAR(255) NOT NULL, + key VARCHAR(50) NOT NULL, -- The app's readable ID. It is in the token and on every certificate. + name VARCHAR(100) NOT NULL, + description TEXT NOT NULL DEFAULT '', + connector VARCHAR(50) NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'ACTIVE', + secret_hash VARCHAR(64) NOT NULL, + secret_hint VARCHAR(12) NOT NULL, -- First part of the secret to identify which key is being used + created_by VARCHAR(255) NOT NULL, + created_at TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + updated_at TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + PRIMARY KEY (id), + CONSTRAINT uq_apps_key UNIQUE (key), + CONSTRAINT uq_apps_name UNIQUE (name), + CONSTRAINT chk_apps_status CHECK (status IN ('ACTIVE', 'DISABLED')), + CONSTRAINT fk_apps_created_by FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE RESTRICT +); + +CREATE TABLE IF NOT EXISTS app_actions +( + app_id VARCHAR(255) NOT NULL, + action VARCHAR(100) NOT NULL, + PRIMARY KEY (app_id, action), + CONSTRAINT fk_app_actions_app FOREIGN KEY (app_id) REFERENCES apps (id) ON DELETE RESTRICT +); diff --git a/internal/server/app.go b/internal/server/app.go new file mode 100644 index 000000000..390e37e2b --- /dev/null +++ b/internal/server/app.go @@ -0,0 +1,253 @@ +// 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 server + +import ( + "net/http" + + "github.com/apache/airavata-custos/pkg/common" + "github.com/apache/airavata-custos/pkg/models" +) + +type appView struct { + models.App + NeedsUserAuthorization bool `json:"needs_user_authorization"` +} + +type appWithTokenView struct { + appView + Token string `json:"token"` +} + +type appNameView struct { + Key string `json:"key"` + Name string `json:"name"` +} + +type createAppRequest struct { + Key string `json:"key"` + Name string `json:"name"` + Description string `json:"description"` + Actions []string `json:"actions"` +} + +type updateAppRequest struct { + Name string `json:"name"` + Description string `json:"description"` +} + +func viewApp(a models.App) appView { + return appView{App: a, NeedsUserAuthorization: a.NeedsUserGrant()} +} + +func writeApp(w http.ResponseWriter, a *models.App, err error) { + if err != nil { + common.WriteServiceError(w, err) + return + } + common.WriteJSON(w, http.StatusOK, viewApp(*a)) +} + +// @Summary List apps +// @Tags Apps +// @Security BearerAuth +// @Produce json +// @Success 200 {array} appView +// @Failure 401 {object} object{error=string} +// @Failure 403 {object} object{error=string} "Caller lacks apps:manage" +// @Router /apps [get] +func (s *Server) listApps(w http.ResponseWriter, r *http.Request) { + apps, err := s.svc.ListApps(r.Context()) + if err != nil { + common.WriteServiceError(w, err) + return + } + views := make([]appView, 0, len(apps)) + for _, a := range apps { + views = append(views, viewApp(a)) + } + common.WriteJSON(w, http.StatusOK, views) +} + +// @Summary List the connectors apps can use and their actions +// @Tags Apps +// @Security BearerAuth +// @Produce json +// @Success 200 {array} models.AppConnector +// @Failure 401 {object} object{error=string} +// @Failure 403 {object} object{error=string} "Caller lacks apps:manage" +// @Router /apps/connectors [get] +func (s *Server) listAppConnectors(w http.ResponseWriter, r *http.Request) { + common.WriteJSON(w, http.StatusOK, models.KnownAppConnectors()) +} + +// @Summary List the key and name of every app, including disabled ones +// @Tags Apps +// @Security BearerAuth +// @Produce json +// @Success 200 {array} appNameView +// @Failure 401 {object} object{error=string} +// @Router /apps/names [get] +func (s *Server) listAppNames(w http.ResponseWriter, r *http.Request) { + apps, err := s.svc.ListApps(r.Context()) + if err != nil { + common.WriteServiceError(w, err) + return + } + names := make([]appNameView, 0, len(apps)) + for _, a := range apps { + names = append(names, appNameView{Key: a.Key, Name: a.Name}) + } + common.WriteJSON(w, http.StatusOK, names) +} + +// @Summary Create an app +// @Description The token is returned only here. +// @Tags Apps +// @Security BearerAuth +// @Accept json +// @Produce json +// @Param request body createAppRequest true "App" +// @Success 201 {object} appWithTokenView +// @Failure 400 {object} object{error=string} +// @Failure 401 {object} object{error=string} +// @Failure 403 {object} object{error=string} "Caller lacks apps:manage" +// @Failure 409 {object} object{error=string} "That key or name is taken" +// @Router /apps [post] +func (s *Server) createApp(w http.ResponseWriter, r *http.Request) { + caller := common.RequireCaller(w, r) + if caller == nil { + return + } + var req createAppRequest + if err := common.DecodeJSON(r, &req); err != nil { + common.WriteError(w, http.StatusBadRequest, err) + return + } + a, token, err := s.svc.CreateApp(r.Context(), req.Key, req.Name, req.Description, req.Actions, caller.UserID) + if err != nil { + common.WriteServiceError(w, err) + return + } + common.WriteJSON(w, http.StatusCreated, appWithTokenView{appView: viewApp(*a), Token: token}) +} + +// @Summary Get an app +// @Tags Apps +// @Security BearerAuth +// @Produce json +// @Param id path string true "App ID" +// @Success 200 {object} appView +// @Failure 401 {object} object{error=string} +// @Failure 403 {object} object{error=string} "Caller lacks apps:manage" +// @Failure 404 {object} object{error=string} +// @Router /apps/{id} [get] +func (s *Server) getApp(w http.ResponseWriter, r *http.Request) { + a, err := s.svc.GetApp(r.Context(), r.PathValue("id")) + writeApp(w, a, err) +} + +// @Summary Edit an app's name and description +// @Tags Apps +// @Security BearerAuth +// @Accept json +// @Produce json +// @Param id path string true "App ID" +// @Param request body updateAppRequest true "Name and description" +// @Success 200 {object} appView +// @Failure 400 {object} object{error=string} +// @Failure 401 {object} object{error=string} +// @Failure 403 {object} object{error=string} "Caller lacks apps:manage" +// @Failure 404 {object} object{error=string} +// @Failure 409 {object} object{error=string} "That name is taken" +// @Router /apps/{id} [put] +func (s *Server) updateApp(w http.ResponseWriter, r *http.Request) { + caller := common.RequireCaller(w, r) + if caller == nil { + return + } + var req updateAppRequest + if err := common.DecodeJSON(r, &req); err != nil { + common.WriteError(w, http.StatusBadRequest, err) + return + } + a, err := s.svc.UpdateApp(r.Context(), r.PathValue("id"), req.Name, req.Description, caller.UserID) + writeApp(w, a, err) +} + +// @Summary Disable an app +// @Tags Apps +// @Security BearerAuth +// @Produce json +// @Param id path string true "App ID" +// @Success 200 {object} appView +// @Failure 401 {object} object{error=string} +// @Failure 403 {object} object{error=string} "Caller lacks apps:manage" +// @Failure 404 {object} object{error=string} +// @Router /apps/{id}/disable [post] +func (s *Server) disableApp(w http.ResponseWriter, r *http.Request) { + caller := common.RequireCaller(w, r) + if caller == nil { + return + } + a, err := s.svc.DisableApp(r.Context(), r.PathValue("id"), caller.UserID) + writeApp(w, a, err) +} + +// @Summary Enable an app +// @Tags Apps +// @Security BearerAuth +// @Produce json +// @Param id path string true "App ID" +// @Success 200 {object} appView +// @Failure 401 {object} object{error=string} +// @Failure 403 {object} object{error=string} "Caller lacks apps:manage" +// @Failure 404 {object} object{error=string} +// @Router /apps/{id}/enable [post] +func (s *Server) enableApp(w http.ResponseWriter, r *http.Request) { + caller := common.RequireCaller(w, r) + if caller == nil { + return + } + a, err := s.svc.EnableApp(r.Context(), r.PathValue("id"), caller.UserID) + writeApp(w, a, err) +} + +// @Summary Issue a new secret for an app +// @Description The old token stops working at once. The new token is returned only here. +// @Tags Apps +// @Security BearerAuth +// @Produce json +// @Param id path string true "App ID" +// @Success 200 {object} appWithTokenView +// @Failure 401 {object} object{error=string} +// @Failure 403 {object} object{error=string} "Caller lacks apps:manage" +// @Failure 404 {object} object{error=string} +// @Router /apps/{id}/secret [post] +func (s *Server) issueAppSecret(w http.ResponseWriter, r *http.Request) { + caller := common.RequireCaller(w, r) + if caller == nil { + return + } + a, token, err := s.svc.IssueAppSecret(r.Context(), r.PathValue("id"), caller.UserID) + if err != nil { + common.WriteServiceError(w, err) + return + } + common.WriteJSON(w, http.StatusOK, appWithTokenView{appView: viewApp(*a), Token: token}) +} diff --git a/internal/server/server.go b/internal/server/server.go index 3ace6306f..6ccd22797 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -200,6 +200,16 @@ func (s *Server) routes() { s.router.RequirePrivilege("POST /agreements/{id}/remove", models.AgreementsManage, s.removeUserAgreement) s.router.RequirePrivilege("GET /agreements/{id}/acceptances", models.AgreementsRead, s.listUserAgreementAcceptances) + s.router.RequirePrivilege("GET /apps", models.AppsManage, s.listApps) + s.router.RequirePrivilege("POST /apps", models.AppsManage, s.createApp) + s.router.RequirePrivilege("GET /apps/connectors", models.AppsManage, s.listAppConnectors) + s.router.RequireAuth("GET /apps/names", s.listAppNames) + s.router.RequirePrivilege("GET /apps/{id}", models.AppsManage, s.getApp) + s.router.RequirePrivilege("PUT /apps/{id}", models.AppsManage, s.updateApp) + s.router.RequirePrivilege("POST /apps/{id}/disable", models.AppsManage, s.disableApp) + s.router.RequirePrivilege("POST /apps/{id}/enable", models.AppsManage, s.enableApp) + s.router.RequirePrivilege("POST /apps/{id}/secret", models.AppsManage, s.issueAppSecret) + s.router.RequirePrivilege("GET /audit/traces", models.TracesRead, s.handleListTraces) s.router.RequirePrivilege("GET /audit/traces/{trace_id}", models.TracesRead, s.handleGetTrace) s.router.RequirePrivilege("GET /audit/events", models.TracesRead, s.handleListEvents) diff --git a/internal/store/app_store.go b/internal/store/app_store.go new file mode 100644 index 000000000..c20b72a8d --- /dev/null +++ b/internal/store/app_store.go @@ -0,0 +1,109 @@ +// 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 store + +import ( + "context" + "database/sql" + "errors" + + "github.com/jmoiron/sqlx" + + "github.com/apache/airavata-custos/pkg/models" +) + +const appColumns = `id, key, name, description, connector, status, secret_hash, secret_hint, created_by, created_at, updated_at` + +type pgAppStore struct { + db *sqlx.DB +} + +func NewAppStore(db *sqlx.DB) AppStore { + return &pgAppStore{db: db} +} + +func (s *pgAppStore) actions(ctx context.Context, appID string) ([]string, error) { + actions := []string{} + err := s.db.SelectContext(ctx, &actions, `SELECT action FROM app_actions WHERE app_id = $1 ORDER BY action`, appID) + return actions, err +} + +func (s *pgAppStore) find(ctx context.Context, q sqlx.QueryerContext, where string, arg any) (*models.App, error) { + var a models.App + err := sqlx.GetContext(ctx, q, &a, `SELECT `+appColumns+` FROM apps WHERE `+where, arg) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + if a.Actions, err = s.actions(ctx, a.ID); err != nil { + return nil, err + } + return &a, nil +} + +func (s *pgAppStore) FindByID(ctx context.Context, id string) (*models.App, error) { + return s.find(ctx, s.db, `id = $1`, id) +} + +func (s *pgAppStore) FindByKey(ctx context.Context, key string) (*models.App, error) { + return s.find(ctx, s.db, `key = $1`, key) +} + +func (s *pgAppStore) FindByIDTx(ctx context.Context, tx *sql.Tx, id string) (*models.App, error) { + return s.find(ctx, &sqlx.Tx{Tx: tx, Mapper: s.db.Mapper}, `id = $1 FOR UPDATE`, id) +} + +func (s *pgAppStore) List(ctx context.Context) ([]models.App, error) { + var apps []models.App + if err := s.db.SelectContext(ctx, &apps, `SELECT `+appColumns+` FROM apps ORDER BY name`); err != nil { + return nil, err + } + for i := range apps { + actions, err := s.actions(ctx, apps[i].ID) + if err != nil { + return nil, err + } + apps[i].Actions = actions + } + return apps, nil +} + +func (s *pgAppStore) Create(ctx context.Context, tx *sql.Tx, a *models.App) error { + if _, err := tx.ExecContext(ctx, + `INSERT INTO apps (id, key, name, description, connector, status, secret_hash, secret_hint, created_by) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, + a.ID, a.Key, a.Name, a.Description, a.Connector, a.Status, a.SecretHash, a.SecretHint, a.CreatedBy); err != nil { + return err + } + for _, action := range a.Actions { + if _, err := tx.ExecContext(ctx, `INSERT INTO app_actions (app_id, action) VALUES ($1, $2)`, a.ID, action); err != nil { + return err + } + } + return nil +} + +func (s *pgAppStore) Update(ctx context.Context, tx *sql.Tx, a *models.App) error { + _, err := tx.ExecContext(ctx, + `UPDATE apps SET name = $1, description = $2, status = $3, secret_hash = $4, secret_hint = $5, updated_at = CURRENT_TIMESTAMP(6) + WHERE id = $6`, + a.Name, a.Description, a.Status, a.SecretHash, a.SecretHint, a.ID) + return err +} diff --git a/internal/store/store.go b/internal/store/store.go index 8e0030d71..f31c49512 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -560,6 +560,17 @@ type UserAgreementStore interface { CountPendingUsers(ctx context.Context, agreementID string) (int, error) } +// AppStore defines persistence operations for apps. Find methods return nil if not found. +type AppStore interface { + FindByID(ctx context.Context, id string) (*models.App, error) + FindByKey(ctx context.Context, key string) (*models.App, error) + // FindByIDTx returns the app locked FOR UPDATE in tx. + FindByIDTx(ctx context.Context, tx *sql.Tx, id string) (*models.App, error) + List(ctx context.Context) ([]models.App, error) + Create(ctx context.Context, tx *sql.Tx, a *models.App) error + Update(ctx context.Context, tx *sql.Tx, a *models.App) error +} + // UserAgreementAcceptanceStore defines persistence operations for the record of who accepted which agreement. type UserAgreementAcceptanceStore interface { // FindTx returns the user's acceptance of the agreement inside tx, or nil. diff --git a/pkg/identity/app_middleware_test.go b/pkg/identity/app_middleware_test.go new file mode 100644 index 000000000..20902ee0f --- /dev/null +++ b/pkg/identity/app_middleware_test.go @@ -0,0 +1,96 @@ +// 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 identity + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +type fakeApps struct { + caller *Caller + err error +} + +func (f fakeApps) ResolveApp(context.Context, string) (*Caller, error) { return f.caller, f.err } + +// serveWith sends a request through AppMiddleware to a router with one app route +// and one signed-in route. Non-app tokens arrive as a signed-in user. +func serveWith(apps fakeApps, token, path string) (int, string) { + ok := func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) } + router := NewRouter(http.NewServeMux()) + router.RequireApp("GET /app-route", "signer:app:generate", ok) + router.RequireAuth("GET /me", ok) + users := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + router.ServeHTTP(w, req.WithContext(WithCaller(req.Context(), &Caller{UserID: "u1"}))) + }) + handler := AppMiddleware(apps, router.AppRoutes(), router, users) + + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Header.Set("Authorization", "Bearer "+token) + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + + var body struct { + Code string `json:"code"` + } + _ = json.Unmarshal(rec.Body.Bytes(), &body) + return rec.Code, body.Code +} + +// Make sure an app token cannot reach a route that was not opened to apps, even one that needs no privilege. +func TestAppMiddleware_RefusesRouteNotOpenToApps(t *testing.T) { + apps := fakeApps{caller: &Caller{AppID: "a1", AppActions: []string{"signer:app:generate"}}} + code, errorCode := serveWith(apps, AppTokenPrefix+"key", "/me") + if code != http.StatusForbidden || errorCode != "app_route_not_allowed" { + t.Fatalf("got %d %s", code, errorCode) + } +} + +// Make sure an app reaches an app route only when it holds the action that route needs. +func TestRequireApp_NeedsTheRouteAction(t *testing.T) { + allowed := fakeApps{caller: &Caller{AppID: "a1", AppActions: []string{"signer:app:generate"}}} + if code, errorCode := serveWith(allowed, AppTokenPrefix+"key", "/app-route"); code != http.StatusOK { + t.Errorf("app with the action: got %d %s", code, errorCode) + } + other := fakeApps{caller: &Caller{AppID: "a1", AppActions: []string{"signer:app:revoke"}}} + if code, errorCode := serveWith(other, AppTokenPrefix+"key", "/app-route"); code != http.StatusForbidden || errorCode != "app_action_not_allowed" { + t.Errorf("app without the action: got %d %s", code, errorCode) + } +} + +// Make sure a signed-in user cannot call an app route, whatever they hold. +func TestRequireApp_RefusesUser(t *testing.T) { + code, errorCode := serveWith(fakeApps{}, "user-token", "/app-route") + if code != http.StatusForbidden || errorCode != "app_action_not_allowed" { + t.Fatalf("got %d %s", code, errorCode) + } +} + +// Make sure an unknown token and a disabled app are refused before any route runs. +func TestAppMiddleware_RefusesBadKeyAndDisabledApp(t *testing.T) { + if code, errorCode := serveWith(fakeApps{err: ErrInvalidAppToken}, AppTokenPrefix+"key", "/app-route"); code != http.StatusUnauthorized || errorCode != "invalid_token" { + t.Errorf("unknown token: got %d %s", code, errorCode) + } + if code, errorCode := serveWith(fakeApps{err: ErrAppDisabled}, AppTokenPrefix+"key", "/app-route"); code != http.StatusForbidden || errorCode != "app_disabled" { + t.Errorf("disabled app: got %d %s", code, errorCode) + } +} diff --git a/pkg/identity/identity.go b/pkg/identity/identity.go index cd3dc64e9..625298502 100644 --- a/pkg/identity/identity.go +++ b/pkg/identity/identity.go @@ -34,6 +34,9 @@ type Caller struct { UserID string NeedsOnboarding bool ConsentPending bool + AppID string // set only for an app. UserID is then empty. + AppKey string + AppActions []string } // Wrap the ErrNotLinked to keep the specific cause in the log while the middleware @@ -45,6 +48,8 @@ var ( ErrUserNotPending = fmt.Errorf("%w: user is not pending", ErrNotLinked) ErrUserAlreadyOIDCLinked = fmt.Errorf("%w: user already has an OIDC binding", ErrNotLinked) ErrUserDisabled = errors.New("user is disabled") + ErrInvalidAppToken = errors.New("app token is not valid") + ErrAppDisabled = errors.New("app is disabled") ) type TokenVerifier interface { @@ -57,6 +62,10 @@ type UserResolver interface { ResolveCaller(ctx context.Context, claims *Claims) (*Caller, []models.PrivilegeKey, error) } +type AppResolver interface { + ResolveApp(ctx context.Context, token string) (*Caller, error) +} + type ctxKey string const ( diff --git a/pkg/identity/middleware.go b/pkg/identity/middleware.go index 7c00c6f7e..5167e10aa 100644 --- a/pkg/identity/middleware.go +++ b/pkg/identity/middleware.go @@ -22,6 +22,7 @@ import ( "errors" "log/slog" "net/http" + "slices" "strings" "github.com/apache/airavata-custos/pkg/models" @@ -79,18 +80,71 @@ func Middleware(verifier TokenVerifier, resolver UserResolver, public, withoutUs }) } +// AppTokenPrefix marks a Custos issued app token (cak_ - custos app key). +const AppTokenPrefix = "cak_" + +// AppMiddleware makes sure an app can only call the app routes, since routes with no privilege check are open otherwise. +func AppMiddleware(resolver AppResolver, appRoutes func(*http.Request) bool, apps, users http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + rawToken, ok := bearer(req.Header.Get("Authorization")) + if !ok || !strings.HasPrefix(rawToken, AppTokenPrefix) { + users.ServeHTTP(w, req) + return + } + caller, err := resolver.ResolveApp(req.Context(), rawToken) + if errors.Is(err, ErrInvalidAppToken) { + writeJSONError(w, http.StatusUnauthorized, "invalid_token", "Invalid app token") + return + } + if errors.Is(err, ErrAppDisabled) { + writeJSONError(w, http.StatusForbidden, "app_disabled", "App is disabled") + return + } + if err != nil { + slog.ErrorContext(req.Context(), "app lookup failed", "error", err.Error()) + writeJSONError(w, http.StatusServiceUnavailable, "auth_lookup_failed", "Identity resolution failed") + return + } + if !appRoutes(req) { + writeJSONError(w, http.StatusForbidden, "app_route_not_allowed", "Apps cannot use this route") + return + } + apps.ServeHTTP(w, req.WithContext(WithCaller(req.Context(), caller))) + }) +} + // Router is the only path that lets HTTP routes hit the mux. The mux // field is unexported on purpose: callers must go through RequirePrivilege, -// RequireAuth, RequireAuthWithoutUserConsent, RequireScoped, or Public. +// RequireAuth, RequireAuthWithoutUserConsent, RequireScoped, RequireApp, or Public. type Router struct { mux *http.ServeMux publicMux *http.ServeMux withoutUserConsentMux *http.ServeMux + appMux *http.ServeMux } // NewRouter wraps mux. func NewRouter(mux *http.ServeMux) *Router { - return &Router{mux: mux, publicMux: http.NewServeMux(), withoutUserConsentMux: http.NewServeMux()} + return &Router{mux: mux, publicMux: http.NewServeMux(), withoutUserConsentMux: http.NewServeMux(), appMux: http.NewServeMux()} +} + +// RequireApp registers a route only an app can call, and only with this action. +// Patterns must be under /connectors/<name>/app/ so they cannot overlap a user route. +func (r *Router) RequireApp(pattern, action string, handler http.HandlerFunc) { + r.mux.HandleFunc(pattern, func(w http.ResponseWriter, req *http.Request) { + caller := CallerFromContext(req.Context()) + if caller == nil || caller.AppID == "" || !slices.Contains(caller.AppActions, action) { + writeJSONError(w, http.StatusForbidden, "app_action_not_allowed", "Caller cannot perform this app action") + return + } + handler(w, req) + }) + r.appMux.HandleFunc(pattern, func(http.ResponseWriter, *http.Request) {}) +} + +// AppRoutes reports whether a request targets a RequireApp route. +func (r *Router) AppRoutes() func(*http.Request) bool { + return routesIn(r.appMux) } // RequirePrivilege registers an authenticated handler. The wrapper checks privilege diff --git a/pkg/models/app.go b/pkg/models/app.go new file mode 100644 index 000000000..8459d0baf --- /dev/null +++ b/pkg/models/app.go @@ -0,0 +1,90 @@ +// 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 models + +import ( + "slices" + "strings" + "sync" + "time" +) + +type AppStatus string + +const ( + AppActive AppStatus = "ACTIVE" + AppDisabled AppStatus = "DISABLED" +) + +// App is a trusted tool that calls connector routes with its own token. +type App struct { + ID string `json:"id" db:"id"` + Key string `json:"key" db:"key"` + Name string `json:"name" db:"name"` + Description string `json:"description" db:"description"` + Connector string `json:"connector" db:"connector"` + Status AppStatus `json:"status" db:"status"` + SecretHash string `json:"-" db:"secret_hash"` + SecretHint string `json:"secret_hint" db:"secret_hint"` + CreatedBy string `json:"created_by" db:"created_by"` + CreatedAt time.Time `json:"created_at" db:"created_at"` + UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + Actions []string `json:"actions" db:"-"` +} + +// AppConnector is what apps can do on one connector. Action keys have the shape +// <connector>:app:<action>. A user might have to authorize the whole app. +type AppConnector struct { + Name string `json:"name"` + NeedsUserGrant bool `json:"needs_user_grant"` + Actions []string `json:"actions"` +} + +var ( + appConnectorsMu sync.RWMutex + appConnectors = map[string]AppConnector{} +) + +func RegisterAppConnector(c AppConnector) { + appConnectorsMu.Lock() + defer appConnectorsMu.Unlock() + appConnectors[c.Name] = c +} + +func KnownAppConnectors() []AppConnector { + appConnectorsMu.RLock() + defer appConnectorsMu.RUnlock() + connectors := make([]AppConnector, 0, len(appConnectors)) + for _, c := range appConnectors { + connectors = append(connectors, c) + } + slices.SortFunc(connectors, func(a, b AppConnector) int { return strings.Compare(a.Name, b.Name) }) + return connectors +} + +func FindAppConnector(name string) (AppConnector, bool) { + appConnectorsMu.RLock() + defer appConnectorsMu.RUnlock() + c, ok := appConnectors[name] + return c, ok +} + +func (a App) NeedsUserGrant() bool { + c, ok := FindAppConnector(a.Connector) + return ok && c.NeedsUserGrant +} diff --git a/pkg/models/privilege.go b/pkg/models/privilege.go index 6f6130cef..fd9f79779 100644 --- a/pkg/models/privilege.go +++ b/pkg/models/privilege.go @@ -43,6 +43,7 @@ const ( EventsManage PrivilegeKey = "core:events:manage" AgreementsRead PrivilegeKey = "core:agreements:read" AgreementsManage PrivilegeKey = "core:agreements:manage" + AppsManage PrivilegeKey = "core:apps:manage" ) var ( @@ -68,6 +69,7 @@ func init() { EventsManage, AgreementsRead, AgreementsManage, + AppsManage, ) } diff --git a/pkg/service/app.go b/pkg/service/app.go new file mode 100644 index 000000000..5f772066f --- /dev/null +++ b/pkg/service/app.go @@ -0,0 +1,223 @@ +// 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 service + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "database/sql" + "encoding/hex" + "fmt" + "regexp" + "slices" + "strings" + + "github.com/apache/airavata-custos/pkg/identity" + "github.com/apache/airavata-custos/pkg/models" +) + +const ( + appAuditCreated = "APP_CREATED" + appAuditUpdated = "APP_UPDATED" + appAuditDisabled = "APP_DISABLED" + appAuditEnabled = "APP_ENABLED" + appAuditSecretIssued = "APP_SECRET_ISSUED" + + appNameMaxLength = 100 + appSecretHintLength = 4 +) + +// The token splits on "." and the certificate key ID splits on ":", so an app key can have neither. +var appKeyRegex = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`) + +func hashAppSecret(secret string) string { + sum := sha256.Sum256([]byte(secret)) + return hex.EncodeToString(sum[:]) +} + +// The returned token is never stored. +func setNewAppSecret(a *models.App) string { + secret := rand.Text() + a.SecretHash, a.SecretHint = hashAppSecret(secret), secret[:appSecretHintLength] + return identity.AppTokenPrefix + a.Key + "." + secret +} + +func validateAppKey(key string) error { + if len(key) > 50 || !appKeyRegex.MatchString(key) { + return fmt.Errorf("%w: app key must be lowercase letters, digits and hyphens, at most 50 characters", ErrInvalidInput) + } + return nil +} + +func validateAppName(name string) (string, error) { + name = strings.TrimSpace(name) + if name == "" || len(name) > appNameMaxLength { + return "", fmt.Errorf("%w: name is required, at most %d characters", ErrInvalidInput, appNameMaxLength) + } + return name, nil +} + +func appConnector(actions []string) (string, error) { + if len(actions) == 0 { + return "", fmt.Errorf("%w: at least one action is required", ErrInvalidInput) + } + name, _, _ := strings.Cut(actions[0], ":") + connector, ok := models.FindAppConnector(name) + if !ok { + return "", fmt.Errorf("%w: unknown action %s", ErrInvalidInput, actions[0]) + } + for _, action := range actions { + if !slices.Contains(connector.Actions, action) { + return "", fmt.Errorf("%w: %s is not an action of the %s connector", ErrInvalidInput, action, name) + } + } + return name, nil +} + +func appWriteErr(op string, err error) error { + if strings.Contains(err.Error(), "uq_apps_key") { + return fmt.Errorf("%w: an app with this key already exists", ErrAlreadyExists) + } + if strings.Contains(err.Error(), "uq_apps_name") { + return fmt.Errorf("%w: an app with this name already exists", ErrAlreadyExists) + } + return fmt.Errorf("%s: %w", op, err) +} + +func (s *Service) ListApps(ctx context.Context) ([]models.App, error) { + return s.apps.List(ctx) +} + +func (s *Service) GetApp(ctx context.Context, id string) (*models.App, error) { + a, err := s.apps.FindByID(ctx, id) + if err != nil { + return nil, fmt.Errorf("lookup app: %w", err) + } + if a == nil { + return nil, ErrNotFound + } + return a, nil +} + +// CreateApp The returned token cannot be read again. +func (s *Service) CreateApp(ctx context.Context, key, name, description string, actions []string, actorID string) (*models.App, string, error) { + if err := validateAppKey(key); err != nil { + return nil, "", err + } + name, err := validateAppName(name) + if err != nil { + return nil, "", err + } + slices.Sort(actions) + actions = slices.Compact(actions) + connector, err := appConnector(actions) + if err != nil { + return nil, "", err + } + a := &models.App{ + ID: newID(), + Key: key, + Name: name, + Description: description, + Connector: connector, + Status: models.AppActive, + CreatedBy: actorID, + Actions: actions, + } + token := setNewAppSecret(a) + if err := s.inTx(ctx, func(tx *sql.Tx) error { + if err := s.assertHasPrivilegeTx(ctx, tx, actorID, models.AppsManage); err != nil { + return err + } + if err := s.apps.Create(ctx, tx, a); err != nil { + return appWriteErr("insert app", err) + } + return s.writeAuditTx(ctx, tx, "app", appAuditCreated, a.ID, map[string]any{"actor_id": actorID, "name": a.Name, "actions": a.Actions}) + }); err != nil { + return nil, "", err + } + saved, err := s.GetApp(ctx, a.ID) + return saved, token, err +} + +func (s *Service) changeApp(ctx context.Context, id, actorID, auditType string, change func(*models.App)) (*models.App, error) { + var a *models.App + if err := s.inTx(ctx, func(tx *sql.Tx) (err error) { + if err := s.assertHasPrivilegeTx(ctx, tx, actorID, models.AppsManage); err != nil { + return err + } + if a, err = s.apps.FindByIDTx(ctx, tx, id); err != nil { + return fmt.Errorf("lookup app: %w", err) + } + if a == nil { + return ErrNotFound + } + change(a) + if err := s.apps.Update(ctx, tx, a); err != nil { + return appWriteErr("update app", err) + } + return s.writeAuditTx(ctx, tx, "app", auditType, id, map[string]any{"actor_id": actorID}) + }); err != nil { + return nil, err + } + return a, nil +} + +func (s *Service) UpdateApp(ctx context.Context, id, name, description, actorID string) (*models.App, error) { + name, err := validateAppName(name) + if err != nil { + return nil, err + } + return s.changeApp(ctx, id, actorID, appAuditUpdated, func(a *models.App) { + a.Name, a.Description = name, description + }) +} + +func (s *Service) DisableApp(ctx context.Context, id, actorID string) (*models.App, error) { + return s.changeApp(ctx, id, actorID, appAuditDisabled, func(a *models.App) { a.Status = models.AppDisabled }) +} + +func (s *Service) EnableApp(ctx context.Context, id, actorID string) (*models.App, error) { + return s.changeApp(ctx, id, actorID, appAuditEnabled, func(a *models.App) { a.Status = models.AppActive }) +} + +func (s *Service) IssueAppSecret(ctx context.Context, id, actorID string) (*models.App, string, error) { + var token string + a, err := s.changeApp(ctx, id, actorID, appAuditSecretIssued, func(a *models.App) { token = setNewAppSecret(a) }) + return a, token, err +} + +func (s *Service) ResolveApp(ctx context.Context, token string) (*identity.Caller, error) { + key, secret, ok := strings.Cut(strings.TrimPrefix(token, identity.AppTokenPrefix), ".") + if !ok { + return nil, identity.ErrInvalidAppToken + } + a, err := s.apps.FindByKey(ctx, key) + if err != nil { + return nil, fmt.Errorf("lookup app by key: %w", err) + } + if a == nil || subtle.ConstantTimeCompare([]byte(a.SecretHash), []byte(hashAppSecret(secret))) != 1 { + return nil, identity.ErrInvalidAppToken + } + if a.Status != models.AppActive { + return nil, identity.ErrAppDisabled + } + return &identity.Caller{AppID: a.ID, AppKey: a.Key, AppActions: a.Actions}, nil +} diff --git a/pkg/service/app_integration_test.go b/pkg/service/app_integration_test.go new file mode 100644 index 000000000..5e93c7f76 --- /dev/null +++ b/pkg/service/app_integration_test.go @@ -0,0 +1,219 @@ +//go:build integration + +// 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 service + +import ( + "database/sql" + "errors" + "slices" + "strings" + "testing" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + + "github.com/apache/airavata-custos/pkg/identity" + "github.com/apache/airavata-custos/pkg/models" +) + +func registerTestAppConnectors() { + models.RegisterAppConnector(models.AppConnector{Name: "signer", NeedsUserGrant: true, Actions: []string{"signer:app:generate", "signer:app:revoke"}}) + models.RegisterAppConnector(models.AppConnector{Name: "temp-account", Actions: []string{"temp-account:app:create"}}) +} + +func seedAppAdmin(t *testing.T, database *sqlx.DB) string { + t.Helper() + userID := seedUser(t, database, "[email protected]") + if _, err := database.Exec( + `INSERT INTO user_privileges (id, user_id, privilege, granted_at, reason) VALUES ($1, $2, $3, NOW(), 'seed')`, + uuid.NewString(), userID, string(models.AppsManage), + ); err != nil { + t.Fatalf("seed apps:manage: %v", err) + } + return userID +} + +func newTestApp(t *testing.T, svc *Service, adminID string) (*models.App, string) { + t.Helper() + registerTestAppConnectors() + app, token, err := svc.CreateApp(ctx(), "test-gateway", "Test Gateway", "", []string{"signer:app:revoke", "signer:app:generate"}, adminID) + if err != nil { + t.Fatalf("create app: %v", err) + } + return app, token +} + +// Make sure the token returned at creation authenticates the app with its actions, and the secret itself is not stored. +func TestApp_TokenAuthenticatesAndSecretIsNotStored(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + app, token := newTestApp(t, svc, seedAppAdmin(t, database)) + + caller, err := svc.ResolveApp(ctx(), token) + if err != nil { + t.Fatalf("resolve: %v", err) + } + if caller.AppID != app.ID || caller.AppKey != "test-gateway" || caller.UserID != "" || !slices.Equal(caller.AppActions, []string{"signer:app:generate", "signer:app:revoke"}) { + t.Fatalf("caller = %+v", caller) + } + _, secret, _ := strings.Cut(token, ".") + var stored int + if err := database.Get(&stored, `SELECT COUNT(*) FROM apps WHERE secret_hash = $1 OR secret_hint = $1`, secret); err != nil { + t.Fatal(err) + } + if stored != 0 { + t.Fatal("the secret was stored") + } +} + +// Make sure a token with the right app key but a wrong or missing secret is refused. +func TestApp_WrongSecretIsRefused(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + newTestApp(t, svc, seedAppAdmin(t, database)) + + for _, token := range []string{identity.AppTokenPrefix + "test-gateway.wrong", identity.AppTokenPrefix + "test-gateway"} { + if _, err := svc.ResolveApp(ctx(), token); !errors.Is(err, identity.ErrInvalidAppToken) { + t.Errorf("%s: got %v", token, err) + } + } +} + +// Make sure an app key or name that is already taken is reported as a conflict. +func TestApp_CreateRefusesDuplicateKeyAndName(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + adminID := seedAppAdmin(t, database) + newTestApp(t, svc, adminID) + + for _, app := range []struct{ key, name string }{ + {"test-gateway", "Another Gateway"}, + {"another-gateway", "Test Gateway"}, + } { + if _, _, err := svc.CreateApp(ctx(), app.key, app.name, "", []string{"signer:app:generate"}, adminID); !errors.Is(err, ErrAlreadyExists) { + t.Errorf("%s: got %v", app.key, err) + } + } +} + +// Make sure an app key that would break the token or the certificate key ID is refused. +func TestApp_CreateRefusesBadAppKey(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + adminID := seedAppAdmin(t, database) + registerTestAppConnectors() + + for _, key := range []string{"has.dot", "has:colon", "Upper", ""} { + if _, _, err := svc.CreateApp(ctx(), key, "Test Gateway", "", []string{"signer:app:generate"}, adminID); !errors.Is(err, ErrInvalidInput) { + t.Errorf("%q: %v", key, err) + } + } +} + +// Make sure the old token stops working as soon as a new secret is issued. +func TestApp_NewSecretStopsOldToken(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + adminID := seedAppAdmin(t, database) + app, oldToken := newTestApp(t, svc, adminID) + + _, newToken, err := svc.IssueAppSecret(ctx(), app.ID, adminID) + if err != nil { + t.Fatalf("issue secret: %v", err) + } + if _, err := svc.ResolveApp(ctx(), oldToken); !errors.Is(err, identity.ErrInvalidAppToken) { + t.Errorf("old token: %v", err) + } + if _, err := svc.ResolveApp(ctx(), newToken); err != nil { + t.Errorf("new token: %v", err) + } +} + +// Make sure a disabled app is refused and works again once it is enabled. +func TestApp_DisabledAppIsRefused(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + adminID := seedAppAdmin(t, database) + app, token := newTestApp(t, svc, adminID) + + if _, err := svc.DisableApp(ctx(), app.ID, adminID); err != nil { + t.Fatal(err) + } + if _, err := svc.ResolveApp(ctx(), token); !errors.Is(err, identity.ErrAppDisabled) { + t.Errorf("disabled: %v", err) + } + if _, err := svc.EnableApp(ctx(), app.ID, adminID); err != nil { + t.Fatal(err) + } + if _, err := svc.ResolveApp(ctx(), token); err != nil { + t.Errorf("enabled: %v", err) + } +} + +// Make sure an app cannot be created with actions from two connectors or with an unknown action. +func TestApp_CreateRefusesBadActions(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + adminID := seedAppAdmin(t, database) + registerTestAppConnectors() + + for _, actions := range [][]string{ + {"signer:app:generate", "temp-account:app:create"}, + {"signer:app:unknown"}, + {}, + } { + if _, _, err := svc.CreateApp(ctx(), "test-gateway", "Test Gateway", "", actions, adminID); !errors.Is(err, ErrInvalidInput) { + t.Errorf("%v: %v", actions, err) + } + } +} + +// Make sure only a holder of core:apps:manage can create an app. +func TestApp_CreateNeedsAppsManage(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + registerTestAppConnectors() + userID := seedUser(t, database, "[email protected]") + + if _, _, err := svc.CreateApp(ctx(), "test-gateway", "Test Gateway", "", []string{"signer:app:generate"}, userID); err == nil { + t.Fatal("created an app without core:apps:manage") + } +} + +// Make sure the admin role is not given core:apps:manage, so only super admins run apps. +func TestApp_AdminRoleCannotManageApps(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + + var role *models.Role + if err := svc.inTx(ctx(), func(tx *sql.Tx) (err error) { + role, err = svc.ensureAdminRoleTx(ctx(), tx) + return err + }); err != nil { + t.Fatal(err) + } + keys, err := svc.roles.ListPrivileges(ctx(), role.ID) + if err != nil { + t.Fatal(err) + } + if slices.Contains(keys, models.AppsManage) { + t.Fatal("the admin role holds core:apps:manage") + } +} diff --git a/pkg/service/interface.go b/pkg/service/interface.go index 7330dcba9..019d54f36 100644 --- a/pkg/service/interface.go +++ b/pkg/service/interface.go @@ -321,6 +321,18 @@ type CoreService interface { UserRoleService UserAgreementService UserConsentService + AppService +} + +type AppService interface { + ListApps(ctx context.Context) ([]models.App, error) + GetApp(ctx context.Context, id string) (*models.App, error) + CreateApp(ctx context.Context, key, name, description string, actions []string, actorID string) (*models.App, string, error) + UpdateApp(ctx context.Context, id, name, description, actorID string) (*models.App, error) + DisableApp(ctx context.Context, id, actorID string) (*models.App, error) + EnableApp(ctx context.Context, id, actorID string) (*models.App, error) + IssueAppSecret(ctx context.Context, id, actorID string) (*models.App, string, error) + ResolveApp(ctx context.Context, token string) (*identity.Caller, error) } // Compile-time assertion that *Service satisfies the aggregate CoreService. diff --git a/pkg/service/mock.go b/pkg/service/mock.go index f6fea8d1e..335915d20 100644 --- a/pkg/service/mock.go +++ b/pkg/service/mock.go @@ -43,6 +43,9 @@ var _ CoreService = &CoreServiceMock{} // CompleteOnboardingFunc: func(ctx context.Context, claims *identity.Claims, in OnboardingInput) (*models.User, error) { // panic("mock out the CompleteOnboarding method") // }, +// CreateAppFunc: func(ctx context.Context, key string, name string, description string, actions []string, actorID string) (*models.App, string, error) { +// panic("mock out the CreateApp method") +// }, // CreateAuditEventFunc: func(ctx context.Context, e *models.AuditEvent) (*models.AuditEvent, error) { // panic("mock out the CreateAuditEvent method") // }, @@ -154,12 +157,21 @@ var _ CoreService = &CoreServiceMock{} // DetachResourceFromAllocationFunc: func(ctx context.Context, allocationID string, resourceID string) error { // panic("mock out the DetachResourceFromAllocation method") // }, +// DisableAppFunc: func(ctx context.Context, id string, actorID string) (*models.App, error) { +// panic("mock out the DisableApp method") +// }, // EffectivePrivilegesFunc: func(ctx context.Context, userID string) ([]models.PrivilegeKey, error) { // panic("mock out the EffectivePrivileges method") // }, +// EnableAppFunc: func(ctx context.Context, id string, actorID string) (*models.App, error) { +// panic("mock out the EnableApp method") +// }, // EnsureProjectMembershipFunc: func(ctx context.Context, projectID string, userID string, role string) error { // panic("mock out the EnsureProjectMembership method") // }, +// GetAppFunc: func(ctx context.Context, id string) (*models.App, error) { +// panic("mock out the GetApp method") +// }, // GetAuditEventFunc: func(ctx context.Context, id string) (*models.AuditEvent, error) { // panic("mock out the GetAuditEvent method") // }, @@ -280,6 +292,9 @@ var _ CoreService = &CoreServiceMock{} // IsProjectParticipantFunc: func(ctx context.Context, projectID string, userID string) (bool, error) { // panic("mock out the IsProjectParticipant method") // }, +// IssueAppSecretFunc: func(ctx context.Context, id string, actorID string) (*models.App, string, error) { +// panic("mock out the IssueAppSecret method") +// }, // LatestUsageTimeForClusterFunc: func(ctx context.Context, clusterID string) (*time.Time, error) { // panic("mock out the LatestUsageTimeForCluster method") // }, @@ -292,6 +307,9 @@ var _ CoreService = &CoreServiceMock{} // ListAllocationsForUserFunc: func(ctx context.Context, userID string) ([]models.ComputeAllocationMembership, error) { // panic("mock out the ListAllocationsForUser method") // }, +// ListAppsFunc: func(ctx context.Context) ([]models.App, error) { +// panic("mock out the ListApps method") +// }, // ListAuditEventsByEntityFunc: func(ctx context.Context, entityID string) ([]models.AuditEvent, error) { // panic("mock out the ListAuditEventsByEntity method") // }, @@ -418,6 +436,9 @@ var _ CoreService = &CoreServiceMock{} // RemoveUserAgreementFunc: func(ctx context.Context, id string, actorID string) (*models.UserAgreement, error) { // panic("mock out the RemoveUserAgreement method") // }, +// ResolveAppFunc: func(ctx context.Context, token string) (*identity.Caller, error) { +// panic("mock out the ResolveApp method") +// }, // RevokePrivilegeFunc: func(ctx context.Context, userID string, privilege models.PrivilegeKey, revokerID string, reason string) error { // panic("mock out the RevokePrivilege method") // }, @@ -427,6 +448,9 @@ var _ CoreService = &CoreServiceMock{} // UpdateAllocationResourceMappingFunc: func(ctx context.Context, allocationID string, resourceID string, resourceAmount int64, resourceTime int64) (*models.ComputeAllocationResourceMapping, error) { // panic("mock out the UpdateAllocationResourceMapping method") // }, +// UpdateAppFunc: func(ctx context.Context, id string, name string, description string, actorID string) (*models.App, error) { +// panic("mock out the UpdateApp method") +// }, // UpdateComputeAllocationFunc: func(ctx context.Context, alloc *models.ComputeAllocation) error { // panic("mock out the UpdateComputeAllocation method") // }, @@ -515,6 +539,9 @@ type CoreServiceMock struct { // CompleteOnboardingFunc mocks the CompleteOnboarding method. CompleteOnboardingFunc func(ctx context.Context, claims *identity.Claims, in OnboardingInput) (*models.User, error) + // CreateAppFunc mocks the CreateApp method. + CreateAppFunc func(ctx context.Context, key string, name string, description string, actions []string, actorID string) (*models.App, string, error) + // CreateAuditEventFunc mocks the CreateAuditEvent method. CreateAuditEventFunc func(ctx context.Context, e *models.AuditEvent) (*models.AuditEvent, error) @@ -626,12 +653,21 @@ type CoreServiceMock struct { // DetachResourceFromAllocationFunc mocks the DetachResourceFromAllocation method. DetachResourceFromAllocationFunc func(ctx context.Context, allocationID string, resourceID string) error + // DisableAppFunc mocks the DisableApp method. + DisableAppFunc func(ctx context.Context, id string, actorID string) (*models.App, error) + // EffectivePrivilegesFunc mocks the EffectivePrivileges method. EffectivePrivilegesFunc func(ctx context.Context, userID string) ([]models.PrivilegeKey, error) + // EnableAppFunc mocks the EnableApp method. + EnableAppFunc func(ctx context.Context, id string, actorID string) (*models.App, error) + // EnsureProjectMembershipFunc mocks the EnsureProjectMembership method. EnsureProjectMembershipFunc func(ctx context.Context, projectID string, userID string, role string) error + // GetAppFunc mocks the GetApp method. + GetAppFunc func(ctx context.Context, id string) (*models.App, error) + // GetAuditEventFunc mocks the GetAuditEvent method. GetAuditEventFunc func(ctx context.Context, id string) (*models.AuditEvent, error) @@ -752,6 +788,9 @@ type CoreServiceMock struct { // IsProjectParticipantFunc mocks the IsProjectParticipant method. IsProjectParticipantFunc func(ctx context.Context, projectID string, userID string) (bool, error) + // IssueAppSecretFunc mocks the IssueAppSecret method. + IssueAppSecretFunc func(ctx context.Context, id string, actorID string) (*models.App, string, error) + // LatestUsageTimeForClusterFunc mocks the LatestUsageTimeForCluster method. LatestUsageTimeForClusterFunc func(ctx context.Context, clusterID string) (*time.Time, error) @@ -764,6 +803,9 @@ type CoreServiceMock struct { // ListAllocationsForUserFunc mocks the ListAllocationsForUser method. ListAllocationsForUserFunc func(ctx context.Context, userID string) ([]models.ComputeAllocationMembership, error) + // ListAppsFunc mocks the ListApps method. + ListAppsFunc func(ctx context.Context) ([]models.App, error) + // ListAuditEventsByEntityFunc mocks the ListAuditEventsByEntity method. ListAuditEventsByEntityFunc func(ctx context.Context, entityID string) ([]models.AuditEvent, error) @@ -890,6 +932,9 @@ type CoreServiceMock struct { // RemoveUserAgreementFunc mocks the RemoveUserAgreement method. RemoveUserAgreementFunc func(ctx context.Context, id string, actorID string) (*models.UserAgreement, error) + // ResolveAppFunc mocks the ResolveApp method. + ResolveAppFunc func(ctx context.Context, token string) (*identity.Caller, error) + // RevokePrivilegeFunc mocks the RevokePrivilege method. RevokePrivilegeFunc func(ctx context.Context, userID string, privilege models.PrivilegeKey, revokerID string, reason string) error @@ -899,6 +944,9 @@ type CoreServiceMock struct { // UpdateAllocationResourceMappingFunc mocks the UpdateAllocationResourceMapping method. UpdateAllocationResourceMappingFunc func(ctx context.Context, allocationID string, resourceID string, resourceAmount int64, resourceTime int64) (*models.ComputeAllocationResourceMapping, error) + // UpdateAppFunc mocks the UpdateApp method. + UpdateAppFunc func(ctx context.Context, id string, name string, description string, actorID string) (*models.App, error) + // UpdateComputeAllocationFunc mocks the UpdateComputeAllocation method. UpdateComputeAllocationFunc func(ctx context.Context, alloc *models.ComputeAllocation) error @@ -1030,6 +1078,21 @@ type CoreServiceMock struct { // In is the in argument value. In OnboardingInput } + // CreateApp holds details about calls to the CreateApp method. + CreateApp []struct { + // Ctx is the ctx argument value. + Ctx context.Context + // Key is the key argument value. + Key string + // Name is the name argument value. + Name string + // Description is the description argument value. + Description string + // Actions is the actions argument value. + Actions []string + // ActorID is the actorID argument value. + ActorID string + } // CreateAuditEvent holds details about calls to the CreateAuditEvent method. CreateAuditEvent []struct { // Ctx is the ctx argument value. @@ -1301,6 +1364,15 @@ type CoreServiceMock struct { // ResourceID is the resourceID argument value. ResourceID string } + // DisableApp holds details about calls to the DisableApp method. + DisableApp []struct { + // Ctx is the ctx argument value. + Ctx context.Context + // ID is the id argument value. + ID string + // ActorID is the actorID argument value. + ActorID string + } // EffectivePrivileges holds details about calls to the EffectivePrivileges method. EffectivePrivileges []struct { // Ctx is the ctx argument value. @@ -1308,6 +1380,15 @@ type CoreServiceMock struct { // UserID is the userID argument value. UserID string } + // EnableApp holds details about calls to the EnableApp method. + EnableApp []struct { + // Ctx is the ctx argument value. + Ctx context.Context + // ID is the id argument value. + ID string + // ActorID is the actorID argument value. + ActorID string + } // EnsureProjectMembership holds details about calls to the EnsureProjectMembership method. EnsureProjectMembership []struct { // Ctx is the ctx argument value. @@ -1319,6 +1400,13 @@ type CoreServiceMock struct { // Role is the role argument value. Role string } + // GetApp holds details about calls to the GetApp method. + GetApp []struct { + // Ctx is the ctx argument value. + Ctx context.Context + // ID is the id argument value. + ID string + } // GetAuditEvent holds details about calls to the GetAuditEvent method. GetAuditEvent []struct { // Ctx is the ctx argument value. @@ -1633,6 +1721,15 @@ type CoreServiceMock struct { // UserID is the userID argument value. UserID string } + // IssueAppSecret holds details about calls to the IssueAppSecret method. + IssueAppSecret []struct { + // Ctx is the ctx argument value. + Ctx context.Context + // ID is the id argument value. + ID string + // ActorID is the actorID argument value. + ActorID string + } // LatestUsageTimeForCluster holds details about calls to the LatestUsageTimeForCluster method. LatestUsageTimeForCluster []struct { // Ctx is the ctx argument value. @@ -1659,6 +1756,11 @@ type CoreServiceMock struct { // UserID is the userID argument value. UserID string } + // ListApps holds details about calls to the ListApps method. + ListApps []struct { + // Ctx is the ctx argument value. + Ctx context.Context + } // ListAuditEventsByEntity holds details about calls to the ListAuditEventsByEntity method. ListAuditEventsByEntity []struct { // Ctx is the ctx argument value. @@ -1959,6 +2061,13 @@ type CoreServiceMock struct { // ActorID is the actorID argument value. ActorID string } + // ResolveApp holds details about calls to the ResolveApp method. + ResolveApp []struct { + // Ctx is the ctx argument value. + Ctx context.Context + // Token is the token argument value. + Token string + } // RevokePrivilege holds details about calls to the RevokePrivilege method. RevokePrivilege []struct { // Ctx is the ctx argument value. @@ -1998,6 +2107,19 @@ type CoreServiceMock struct { // ResourceTime is the resourceTime argument value. ResourceTime int64 } + // UpdateApp holds details about calls to the UpdateApp method. + UpdateApp []struct { + // Ctx is the ctx argument value. + Ctx context.Context + // ID is the id argument value. + ID string + // Name is the name argument value. + Name string + // Description is the description argument value. + Description string + // ActorID is the actorID argument value. + ActorID string + } // UpdateComputeAllocation holds details about calls to the UpdateComputeAllocation method. UpdateComputeAllocation []struct { // Ctx is the ctx argument value. @@ -2164,6 +2286,7 @@ type CoreServiceMock struct { lockBootstrapSuperAdmin sync.RWMutex lockCheckOnboardingUsername sync.RWMutex lockCompleteOnboarding sync.RWMutex + lockCreateApp sync.RWMutex lockCreateAuditEvent sync.RWMutex lockCreateComputeAllocation sync.RWMutex lockCreateComputeAllocationChangeRequest sync.RWMutex @@ -2201,8 +2324,11 @@ type CoreServiceMock struct { lockDeleteUserAgreementDraft sync.RWMutex lockDeleteUserIdentity sync.RWMutex lockDetachResourceFromAllocation sync.RWMutex + lockDisableApp sync.RWMutex lockEffectivePrivileges sync.RWMutex + lockEnableApp sync.RWMutex lockEnsureProjectMembership sync.RWMutex + lockGetApp sync.RWMutex lockGetAuditEvent sync.RWMutex lockGetComputeAllocation sync.RWMutex lockGetComputeAllocationChangeRequest sync.RWMutex @@ -2243,10 +2369,12 @@ type CoreServiceMock struct { lockGrantRoleToUser sync.RWMutex lockHasPrivilege sync.RWMutex lockIsProjectParticipant sync.RWMutex + lockIssueAppSecret sync.RWMutex lockLatestUsageTimeForCluster sync.RWMutex lockListAllAuditEvents sync.RWMutex lockListAllocationsForResource sync.RWMutex lockListAllocationsForUser sync.RWMutex + lockListApps sync.RWMutex lockListAuditEventsByEntity sync.RWMutex lockListAuditEventsByEventType sync.RWMutex lockListChangeRequestsByRequester sync.RWMutex @@ -2289,9 +2417,11 @@ type CoreServiceMock struct { lockPublishUserAgreement sync.RWMutex lockRemovePrivilegeFromRole sync.RWMutex lockRemoveUserAgreement sync.RWMutex + lockResolveApp sync.RWMutex lockRevokePrivilege sync.RWMutex lockRevokeRoleFromUser sync.RWMutex lockUpdateAllocationResourceMapping sync.RWMutex + lockUpdateApp sync.RWMutex lockUpdateComputeAllocation sync.RWMutex lockUpdateComputeAllocationChangeRequest sync.RWMutex lockUpdateComputeAllocationMembership sync.RWMutex @@ -2606,6 +2736,58 @@ func (mock *CoreServiceMock) CompleteOnboardingCalls() []struct { return calls } +// CreateApp calls CreateAppFunc. +func (mock *CoreServiceMock) CreateApp(ctx context.Context, key string, name string, description string, actions []string, actorID string) (*models.App, string, error) { + if mock.CreateAppFunc == nil { + panic("CoreServiceMock.CreateAppFunc: method is nil but CoreService.CreateApp was just called") + } + callInfo := struct { + Ctx context.Context + Key string + Name string + Description string + Actions []string + ActorID string + }{ + Ctx: ctx, + Key: key, + Name: name, + Description: description, + Actions: actions, + ActorID: actorID, + } + mock.lockCreateApp.Lock() + mock.calls.CreateApp = append(mock.calls.CreateApp, callInfo) + mock.lockCreateApp.Unlock() + return mock.CreateAppFunc(ctx, key, name, description, actions, actorID) +} + +// CreateAppCalls gets all the calls that were made to CreateApp. +// Check the length with: +// +// len(mockedCoreService.CreateAppCalls()) +func (mock *CoreServiceMock) CreateAppCalls() []struct { + Ctx context.Context + Key string + Name string + Description string + Actions []string + ActorID string +} { + var calls []struct { + Ctx context.Context + Key string + Name string + Description string + Actions []string + ActorID string + } + mock.lockCreateApp.RLock() + calls = mock.calls.CreateApp + mock.lockCreateApp.RUnlock() + return calls +} + // CreateAuditEvent calls CreateAuditEventFunc. func (mock *CoreServiceMock) CreateAuditEvent(ctx context.Context, e *models.AuditEvent) (*models.AuditEvent, error) { if mock.CreateAuditEventFunc == nil { @@ -3962,6 +4144,46 @@ func (mock *CoreServiceMock) DetachResourceFromAllocationCalls() []struct { return calls } +// DisableApp calls DisableAppFunc. +func (mock *CoreServiceMock) DisableApp(ctx context.Context, id string, actorID string) (*models.App, error) { + if mock.DisableAppFunc == nil { + panic("CoreServiceMock.DisableAppFunc: method is nil but CoreService.DisableApp was just called") + } + callInfo := struct { + Ctx context.Context + ID string + ActorID string + }{ + Ctx: ctx, + ID: id, + ActorID: actorID, + } + mock.lockDisableApp.Lock() + mock.calls.DisableApp = append(mock.calls.DisableApp, callInfo) + mock.lockDisableApp.Unlock() + return mock.DisableAppFunc(ctx, id, actorID) +} + +// DisableAppCalls gets all the calls that were made to DisableApp. +// Check the length with: +// +// len(mockedCoreService.DisableAppCalls()) +func (mock *CoreServiceMock) DisableAppCalls() []struct { + Ctx context.Context + ID string + ActorID string +} { + var calls []struct { + Ctx context.Context + ID string + ActorID string + } + mock.lockDisableApp.RLock() + calls = mock.calls.DisableApp + mock.lockDisableApp.RUnlock() + return calls +} + // EffectivePrivileges calls EffectivePrivilegesFunc. func (mock *CoreServiceMock) EffectivePrivileges(ctx context.Context, userID string) ([]models.PrivilegeKey, error) { if mock.EffectivePrivilegesFunc == nil { @@ -3998,6 +4220,46 @@ func (mock *CoreServiceMock) EffectivePrivilegesCalls() []struct { return calls } +// EnableApp calls EnableAppFunc. +func (mock *CoreServiceMock) EnableApp(ctx context.Context, id string, actorID string) (*models.App, error) { + if mock.EnableAppFunc == nil { + panic("CoreServiceMock.EnableAppFunc: method is nil but CoreService.EnableApp was just called") + } + callInfo := struct { + Ctx context.Context + ID string + ActorID string + }{ + Ctx: ctx, + ID: id, + ActorID: actorID, + } + mock.lockEnableApp.Lock() + mock.calls.EnableApp = append(mock.calls.EnableApp, callInfo) + mock.lockEnableApp.Unlock() + return mock.EnableAppFunc(ctx, id, actorID) +} + +// EnableAppCalls gets all the calls that were made to EnableApp. +// Check the length with: +// +// len(mockedCoreService.EnableAppCalls()) +func (mock *CoreServiceMock) EnableAppCalls() []struct { + Ctx context.Context + ID string + ActorID string +} { + var calls []struct { + Ctx context.Context + ID string + ActorID string + } + mock.lockEnableApp.RLock() + calls = mock.calls.EnableApp + mock.lockEnableApp.RUnlock() + return calls +} + // EnsureProjectMembership calls EnsureProjectMembershipFunc. func (mock *CoreServiceMock) EnsureProjectMembership(ctx context.Context, projectID string, userID string, role string) error { if mock.EnsureProjectMembershipFunc == nil { @@ -4042,6 +4304,42 @@ func (mock *CoreServiceMock) EnsureProjectMembershipCalls() []struct { return calls } +// GetApp calls GetAppFunc. +func (mock *CoreServiceMock) GetApp(ctx context.Context, id string) (*models.App, error) { + if mock.GetAppFunc == nil { + panic("CoreServiceMock.GetAppFunc: method is nil but CoreService.GetApp was just called") + } + callInfo := struct { + Ctx context.Context + ID string + }{ + Ctx: ctx, + ID: id, + } + mock.lockGetApp.Lock() + mock.calls.GetApp = append(mock.calls.GetApp, callInfo) + mock.lockGetApp.Unlock() + return mock.GetAppFunc(ctx, id) +} + +// GetAppCalls gets all the calls that were made to GetApp. +// Check the length with: +// +// len(mockedCoreService.GetAppCalls()) +func (mock *CoreServiceMock) GetAppCalls() []struct { + Ctx context.Context + ID string +} { + var calls []struct { + Ctx context.Context + ID string + } + mock.lockGetApp.RLock() + calls = mock.calls.GetApp + mock.lockGetApp.RUnlock() + return calls +} + // GetAuditEvent calls GetAuditEventFunc. func (mock *CoreServiceMock) GetAuditEvent(ctx context.Context, id string) (*models.AuditEvent, error) { if mock.GetAuditEventFunc == nil { @@ -5550,6 +5848,46 @@ func (mock *CoreServiceMock) IsProjectParticipantCalls() []struct { return calls } +// IssueAppSecret calls IssueAppSecretFunc. +func (mock *CoreServiceMock) IssueAppSecret(ctx context.Context, id string, actorID string) (*models.App, string, error) { + if mock.IssueAppSecretFunc == nil { + panic("CoreServiceMock.IssueAppSecretFunc: method is nil but CoreService.IssueAppSecret was just called") + } + callInfo := struct { + Ctx context.Context + ID string + ActorID string + }{ + Ctx: ctx, + ID: id, + ActorID: actorID, + } + mock.lockIssueAppSecret.Lock() + mock.calls.IssueAppSecret = append(mock.calls.IssueAppSecret, callInfo) + mock.lockIssueAppSecret.Unlock() + return mock.IssueAppSecretFunc(ctx, id, actorID) +} + +// IssueAppSecretCalls gets all the calls that were made to IssueAppSecret. +// Check the length with: +// +// len(mockedCoreService.IssueAppSecretCalls()) +func (mock *CoreServiceMock) IssueAppSecretCalls() []struct { + Ctx context.Context + ID string + ActorID string +} { + var calls []struct { + Ctx context.Context + ID string + ActorID string + } + mock.lockIssueAppSecret.RLock() + calls = mock.calls.IssueAppSecret + mock.lockIssueAppSecret.RUnlock() + return calls +} + // LatestUsageTimeForCluster calls LatestUsageTimeForClusterFunc. func (mock *CoreServiceMock) LatestUsageTimeForCluster(ctx context.Context, clusterID string) (*time.Time, error) { if mock.LatestUsageTimeForClusterFunc == nil { @@ -5690,6 +6028,38 @@ func (mock *CoreServiceMock) ListAllocationsForUserCalls() []struct { return calls } +// ListApps calls ListAppsFunc. +func (mock *CoreServiceMock) ListApps(ctx context.Context) ([]models.App, error) { + if mock.ListAppsFunc == nil { + panic("CoreServiceMock.ListAppsFunc: method is nil but CoreService.ListApps was just called") + } + callInfo := struct { + Ctx context.Context + }{ + Ctx: ctx, + } + mock.lockListApps.Lock() + mock.calls.ListApps = append(mock.calls.ListApps, callInfo) + mock.lockListApps.Unlock() + return mock.ListAppsFunc(ctx) +} + +// ListAppsCalls gets all the calls that were made to ListApps. +// Check the length with: +// +// len(mockedCoreService.ListAppsCalls()) +func (mock *CoreServiceMock) ListAppsCalls() []struct { + Ctx context.Context +} { + var calls []struct { + Ctx context.Context + } + mock.lockListApps.RLock() + calls = mock.calls.ListApps + mock.lockListApps.RUnlock() + return calls +} + // ListAuditEventsByEntity calls ListAuditEventsByEntityFunc. func (mock *CoreServiceMock) ListAuditEventsByEntity(ctx context.Context, entityID string) ([]models.AuditEvent, error) { if mock.ListAuditEventsByEntityFunc == nil { @@ -7213,6 +7583,42 @@ func (mock *CoreServiceMock) RemoveUserAgreementCalls() []struct { return calls } +// ResolveApp calls ResolveAppFunc. +func (mock *CoreServiceMock) ResolveApp(ctx context.Context, token string) (*identity.Caller, error) { + if mock.ResolveAppFunc == nil { + panic("CoreServiceMock.ResolveAppFunc: method is nil but CoreService.ResolveApp was just called") + } + callInfo := struct { + Ctx context.Context + Token string + }{ + Ctx: ctx, + Token: token, + } + mock.lockResolveApp.Lock() + mock.calls.ResolveApp = append(mock.calls.ResolveApp, callInfo) + mock.lockResolveApp.Unlock() + return mock.ResolveAppFunc(ctx, token) +} + +// ResolveAppCalls gets all the calls that were made to ResolveApp. +// Check the length with: +// +// len(mockedCoreService.ResolveAppCalls()) +func (mock *CoreServiceMock) ResolveAppCalls() []struct { + Ctx context.Context + Token string +} { + var calls []struct { + Ctx context.Context + Token string + } + mock.lockResolveApp.RLock() + calls = mock.calls.ResolveApp + mock.lockResolveApp.RUnlock() + return calls +} + // RevokePrivilege calls RevokePrivilegeFunc. func (mock *CoreServiceMock) RevokePrivilege(ctx context.Context, userID string, privilege models.PrivilegeKey, revokerID string, reason string) error { if mock.RevokePrivilegeFunc == nil { @@ -7357,6 +7763,54 @@ func (mock *CoreServiceMock) UpdateAllocationResourceMappingCalls() []struct { return calls } +// UpdateApp calls UpdateAppFunc. +func (mock *CoreServiceMock) UpdateApp(ctx context.Context, id string, name string, description string, actorID string) (*models.App, error) { + if mock.UpdateAppFunc == nil { + panic("CoreServiceMock.UpdateAppFunc: method is nil but CoreService.UpdateApp was just called") + } + callInfo := struct { + Ctx context.Context + ID string + Name string + Description string + ActorID string + }{ + Ctx: ctx, + ID: id, + Name: name, + Description: description, + ActorID: actorID, + } + mock.lockUpdateApp.Lock() + mock.calls.UpdateApp = append(mock.calls.UpdateApp, callInfo) + mock.lockUpdateApp.Unlock() + return mock.UpdateAppFunc(ctx, id, name, description, actorID) +} + +// UpdateAppCalls gets all the calls that were made to UpdateApp. +// Check the length with: +// +// len(mockedCoreService.UpdateAppCalls()) +func (mock *CoreServiceMock) UpdateAppCalls() []struct { + Ctx context.Context + ID string + Name string + Description string + ActorID string +} { + var calls []struct { + Ctx context.Context + ID string + Name string + Description string + ActorID string + } + mock.lockUpdateApp.RLock() + calls = mock.calls.UpdateApp + mock.lockUpdateApp.RUnlock() + return calls +} + // UpdateComputeAllocation calls UpdateComputeAllocationFunc. func (mock *CoreServiceMock) UpdateComputeAllocation(ctx context.Context, alloc *models.ComputeAllocation) error { if mock.UpdateComputeAllocationFunc == nil { diff --git a/pkg/service/service.go b/pkg/service/service.go index 6f6d364a5..528d80ed0 100644 --- a/pkg/service/service.go +++ b/pkg/service/service.go @@ -64,6 +64,7 @@ type Service struct { agreements store.UserAgreementStore acceptances store.UserAgreementAcceptanceStore auditTraces store.AuditTraceStore + apps store.AppStore identityCache *identityCache } @@ -98,6 +99,7 @@ func New(database *sqlx.DB, eventBus *events.Bus) *Service { agreements: store.NewUserAgreementStore(database), acceptances: store.NewUserAgreementAcceptanceStore(database), auditTraces: store.NewAuditTraceStore(database), + apps: store.NewAppStore(database), identityCache: newIdentityCache(), } } @@ -159,6 +161,7 @@ func NewWithStores( agreements: agreements, acceptances: acceptances, auditTraces: store.NewAuditTraceStore(database), + apps: store.NewAppStore(database), identityCache: newIdentityCache(), } } diff --git a/pkg/service/user_role.go b/pkg/service/user_role.go index 475b68762..d95cf194b 100644 --- a/pkg/service/user_role.go +++ b/pkg/service/user_role.go @@ -307,14 +307,14 @@ func (s *Service) ensureAdminRoleTx(ctx context.Context, tx *sql.Tx) (*models.Ro role = &models.Role{ ID: newID(), Name: models.SystemRoleAdmin, - Description: stringPtrOrNil("day-to-day administration, everything except grants and role management"), + Description: stringPtrOrNil("day-to-day administration, everything except grants, role management and apps"), IsSystem: true, } if err := s.roles.Create(ctx, tx, role); err != nil { return nil, fmt.Errorf("create admin role: %w", err) } for _, key := range models.KnownPrivileges() { - if key == models.PrivilegesGrant || key == models.RolesManage { + if key == models.PrivilegesGrant || key == models.RolesManage || key == models.AppsManage { continue } if err := s.roles.AddPrivilege(ctx, tx, role.ID, key); err != nil {
