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 1cb82b06012992e339b62e800cbda752bcc6df28 Author: lahiruj <[email protected]> AuthorDate: Thu Nov 12 14:04:09 2026 -0500 Remove delegated apps --- .env.example | 2 - CONFIG.md | 2 - api/core.openapi.yaml | 171 +------------- cmd/server/main.go | 8 +- config/custos.yaml | 1 - connectors/Signer/internal/handlers_test.go | 20 -- docs/architecture.md | 42 +--- docs/privileges.md | 2 - internal/config/config.go | 7 - internal/config/config_test.go | 21 -- internal/db/migrations/000009_apps.down.sql | 1 - internal/db/migrations/000009_apps.up.sql | 15 +- internal/server/app.go | 112 +-------- internal/server/privilege.go | 7 +- internal/server/privilege_integration_test.go | 24 -- internal/server/server.go | 4 - internal/store/app_store.go | 54 +---- internal/store/store.go | 7 - pkg/identity/app_middleware_test.go | 222 +++--------------- pkg/identity/identity.go | 6 +- pkg/identity/middleware.go | 112 +-------- pkg/models/app.go | 10 +- pkg/service/app.go | 112 ++------- pkg/service/app_integration_test.go | 162 ++----------- pkg/service/interface.go | 8 +- pkg/service/mock.go | 326 +------------------------- pkg/service/user_merge.go | 3 - 27 files changed, 118 insertions(+), 1343 deletions(-) diff --git a/.env.example b/.env.example index 1dc2363de..10d630f9a 100644 --- a/.env.example +++ b/.env.example @@ -35,8 +35,6 @@ DATABASE_DSN=postgres://admin:admin@localhost:5432/custos?sslmode=disable # your provider's issuer URL and the access-token `aud` claim (typically the client_id). OIDC_ISSUER_URL=http://localhost:8081/realms/custos OIDC_AUDIENCE=custos-api -# Public client that apps use to get the user's token. Empty turns off delegated apps. -OIDC_APPS_AUDIENCE= # --- Server: dev convenience --------------------------------------------- diff --git a/CONFIG.md b/CONFIG.md index a55bdee49..806ab74cc 100644 --- a/CONFIG.md +++ b/CONFIG.md @@ -93,7 +93,6 @@ core: oidc: issuer: "${OIDC_ISSUER_URL}" audience: "${OIDC_AUDIENCE}" - apps_audience: "${OIDC_APPS_AUDIENCE}" cache_ttl: "30s" users: reserved_usernames: [ root, daemon, slurm, ... ] @@ -106,7 +105,6 @@ core: | `core.log_level` | `info` | `debug`, `info`, `warn` or `error`. Any other value means `info`. | | `core.auth.oidc.issuer` | required | OIDC issuer URL. The verifier discovers the JWKS from `<issuer>/.well-known/openid-configuration`. Empty → boot fails with `core.auth.oidc.issuer is required`. | | `core.auth.oidc.audience` | required | Expected `aud` claim, usually the client ID registered with the provider. Empty → boot fails with `core.auth.oidc.audience is required`. | -| `core.auth.oidc.apps_audience` | empty | Client ID of our public client that delegated apps use to get the user's token ([apps](docs/architecture.md#apps)). Empty turns off delegated apps. The same value as `audience` → boot fails. | | `core.auth.cache_ttl` | `30s` | How long a resolved caller and its privileges stay cached. A Go duration such as `30s` or `1m`. Zero or negative → `30s`. Above `60s` → capped at `60s` with a warning. | | `core.users.reserved_usernames` | empty | Names a user cannot choose as their cluster login. The sample lists system, service and distribution accounts. | diff --git a/api/core.openapi.yaml b/api/core.openapi.yaml index bed3f1dc6..627e3b4bf 100644 --- a/api/core.openapi.yaml +++ b/api/core.openapi.yaml @@ -52,8 +52,6 @@ definitions: type: string key: type: string - mode: - $ref: '#/definitions/AppMode' name: type: string privileges: @@ -67,14 +65,6 @@ definitions: updated_at: type: string type: object - AppMode: - enum: - - SERVICE - - DELEGATED - type: string - x-enum-varnames: - - AppService - - AppDelegated AppStatus: enum: - ACTIVE @@ -1155,53 +1145,6 @@ definitions: name: type: string type: object - appAuthorizationView: - properties: - authorized: - type: boolean - description: - type: string - id: - type: string - name: - type: string - type: object - appDetailView: - properties: - authorized_users: - type: integer - created_at: - type: string - created_by: - type: string - description: - type: string - id: - type: string - key: - type: string - mode: - $ref: '#/definitions/AppMode' - name: - type: string - privileges: - items: - $ref: '#/definitions/PrivilegeKey' - type: array - secret_hint: - type: string - status: - $ref: '#/definitions/AppStatus' - updated_at: - type: string - type: object - appNameView: - properties: - key: - type: string - name: - type: string - type: object appWithTokenView: properties: created_at: @@ -1214,8 +1157,6 @@ definitions: type: string key: type: string - mode: - $ref: '#/definitions/AppMode' name: type: string privileges: @@ -1253,8 +1194,6 @@ definitions: type: string key: type: string - mode: - $ref: '#/definitions/AppMode' name: type: string privileges: @@ -1980,7 +1919,7 @@ paths: - Apps /apps/{id}: delete: - description: Every user's allow is removed. The key can never be used again. + description: The key can never be used again. parameters: - description: App ID in: path @@ -2036,7 +1975,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/appDetailView' + $ref: '#/definitions/App' "401": description: Unauthorized schema: @@ -2250,29 +2189,6 @@ paths: summary: Issue a new secret for an app 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 and deleted ones - tags: - - Apps /apps/privileges: get: produces: @@ -4816,89 +4732,6 @@ paths: summary: List the current agreement if the caller has not accepted it tags: - Consent - /me/app-authorizations: - get: - produces: - - application/json - responses: - "200": - description: OK - schema: - items: - $ref: '#/definitions/appAuthorizationView' - type: array - "401": - description: Unauthorized - schema: - properties: - error: - type: string - type: object - security: - - BearerAuth: [] - summary: List the apps that can act for the caller - tags: - - Apps - /me/app-authorizations/{appId}: - delete: - description: Certificates the app already generated stay valid. - parameters: - - description: App ID - in: path - name: appId - required: true - type: string - responses: - "204": - description: No Content - "401": - description: Unauthorized - schema: - properties: - error: - type: string - type: object - security: - - BearerAuth: [] - summary: Remove an app's authorization - tags: - - Apps - post: - parameters: - - description: App ID - in: path - name: appId - required: true - type: string - responses: - "204": - description: No Content - "400": - description: The app cannot be authorized - schema: - properties: - error: - type: string - type: object - "401": - description: Unauthorized - schema: - properties: - error: - type: string - type: object - "404": - description: Not Found - schema: - properties: - error: - type: string - type: object - security: - - BearerAuth: [] - summary: Allow an app to act for the caller - tags: - - Apps /me/onboarding: post: consumes: diff --git a/cmd/server/main.go b/cmd/server/main.go index b1d9f0f37..7a03d6802 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -152,19 +152,13 @@ func run() error { if err != nil { return err } - var appUserTokenVerifier identity.TokenVerifier - if cfg.Core.Auth.OIDC.AppsAudience != "" { - if appUserTokenVerifier, err = identity.NewJWTVerifier(ctx, cfg.Core.Auth.OIDC.Issuer, cfg.Core.Auth.OIDC.AppsAudience); err != nil { - return err - } - } svc.SetIdentityCacheTTL(cfg.Core.Auth.CacheTTL) svc.SetReservedUsernames(cfg.Core.Users.ReservedUsernames) // 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) - routed := identity.AppMiddleware(svc, appUserTokenVerifier, svc, srv, authed) + routed := identity.AppMiddleware(svc, srv, authed) handler := server.LoggingMiddleware(tracing.Middleware(routed)) httpServer := &http.Server{ diff --git a/config/custos.yaml b/config/custos.yaml index 77fd5cc26..5aaff2055 100644 --- a/config/custos.yaml +++ b/config/custos.yaml @@ -25,7 +25,6 @@ core: oidc: issuer: "${OIDC_ISSUER_URL}" audience: "${OIDC_AUDIENCE}" - apps_audience: "${OIDC_APPS_AUDIENCE}" cache_ttl: "30s" users: # Names a user cannot choose as their cluster login. diff --git a/connectors/Signer/internal/handlers_test.go b/connectors/Signer/internal/handlers_test.go index 605bcc8f2..a1c1edcdf 100644 --- a/connectors/Signer/internal/handlers_test.go +++ b/connectors/Signer/internal/handlers_test.go @@ -114,11 +114,6 @@ func serveWith(core CoreAccounts, baseURL string, r *http.Request, privs ...mode return serveAs(&identity.Caller{UserID: "user-1", Email: "[email protected]"}, &identity.Claims{Sub: testSub, Email: "[email protected]"}, core, baseURL, r, privs...) } -// serveForApp calls as a delegated app. Its user token has no email. -func serveForApp(baseURL string, r *http.Request) *httptest.ResponseRecorder { - return serveAs(&identity.Caller{UserID: "user-1", Email: "[email protected]", AppID: "a1", AppKey: "gateway"}, &identity.Claims{Sub: testSub}, readyCore(), baseURL, r) -} - func serve(baseURL string, r *http.Request, privs ...models.PrivilegeKey) *httptest.ResponseRecorder { return serveWith(readyCore(), baseURL, r, privs...) } @@ -242,21 +237,6 @@ func TestRevokeOwn_RecordedAsTheUser(t *testing.T) { } } -// Make sure a certificate a delegated app generates or revokes records the app and gets the user's email even though the token has none. -func TestOwnRoutes_ByAppRecordTheApp(t *testing.T) { - srv, seen := mockSignerServer(t, http.StatusOK, `{"user_sub":"`+testSub+`"}`) - - serveForApp(srv.URL, httptest.NewRequest(http.MethodPost, "/connectors/signer/me/certificates", strings.NewReader(`{"public_key":"k"}`))) - if !strings.Contains(seen.body, `"requested_by":"app/gateway"`) || !strings.Contains(seen.body, `"user_email":"[email protected]"`) { - t.Fatalf("generate: signer got %s", seen.body) - } - - serveForApp(srv.URL, httptest.NewRequest(http.MethodPost, "/connectors/signer/me/certificates/42/revoke", strings.NewReader(`{}`))) - if !strings.Contains(seen.body, `"revoked_by":"app/gateway"`) { - t.Fatalf("revoke: signer got %s", seen.body) - } -} - // Make sure an admin revoke is recorded under the admin's user ID. func TestRevokeAny_RecordedAsTheAdmin(t *testing.T) { srv, seen := mockSignerServer(t, http.StatusOK, `{}`) diff --git a/docs/architecture.md b/docs/architecture.md index d87aeca50..aca693a33 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -128,14 +128,13 @@ Inbound authentication is an OIDC bearer JWT. `pkg/identity/verifier.go` checks `iss` and `aud` must match `core.auth.oidc.{issuer,audience}`. The resolved caller is cached for `core.auth.cache_ttl` ([CONFIG.md](../CONFIG.md#core-keys)). Apps authenticate differently, see [Apps](#apps). -Routes register through one of six router methods: +Routes register through one of five router methods: | Method | Who gets through | Example | |---------------------------------------------|------------------------------------------------------------------------|---------------------------------------------| | `Public(pattern, h)` | Anyone; the token is not checked | `GET /healthz` | | `RequireAuthWithoutUserConsent(pattern, h)` | A verified caller, before onboarding or accepting the user agreement | `GET /me`, `POST /me/onboarding` | | `RequireAuth(pattern, h)` | A verified caller who has onboarded and accepted the current agreement | `GET /projects`, `GET /compute-allocations` | -| `RequireAuthUsersOnly(pattern, h)` | Like `RequireAuth`, but never an app | `POST /me/app-authorizations/{appId}` | | `RequireScoped(pattern, authorize, h)` | A verified caller whom `authorize` admits for that resource | `GET /compute-allocations/{id}` | | `RequirePrivilege(pattern, key, h)` | A verified caller who holds `key` | `POST /compute-clusters` | @@ -160,38 +159,23 @@ The middleware answers authentication failures with `{"code": ..., "message": .. An app is a tool a super admin registers at `/apps` (`core:apps:manage`). It calls with `Authorization: Bearer cak_<key>.<secret>`, and `identity.AppMiddleware` handles those calls before the user path. -Each app has a fixed mode: +An app always acts as itself, with the privileges the admin gave it. It never acts as a user. -- **Service.** The app acts as itself, with the privileges the admin gave it. -- **Delegated.** The app acts for a user who allowed it. Every call also sends the user's id token in - `X-User-Token`. The token must be issued to `core.auth.oidc.apps_audience`, our public client for apps, which must - differ from the portal's `audience`. The user must have signed in to the portal once, be active and have accepted - the agreement. The call then runs as that user with only the privileges both the app and the user hold. +Only keys registered with `models.AllowForApps(...)` can be given to an app. -Only keys registered with `models.AllowForApps(...)` can be given to an app. Leaving `apps_audience` empty turns off -delegated apps. - -| Method | Service app | Delegated app | -|---------------------------------|--------------------------|---------------------------------| -| `Public` | Yes | Yes | -| `RequireAuthWithoutUserConsent` | No | `GET` routes only, as the user | -| `RequireAuth`, `RequireScoped` | No | Yes, as the user | -| `RequireAuthUsersOnly` | No | No | -| `RequirePrivilege` | If the app holds the key | If the app and the user hold it | +| Method | App | +|-----------------------------------------------------------------|--------------------------| +| `Public` | Yes | +| `RequirePrivilege` | If the app holds the key | +| `RequireAuth`, `RequireScoped`, `RequireAuthWithoutUserConsent` | No | Extra codes on app calls: -| Status | `code` | Cause | -|--------|--------------------------|--------------------------------------------------| -| `401` | `invalid_token` | Unknown app or wrong secret | -| `403` | `app_disabled` | The app is disabled | -| `403` | `user_token_not_allowed` | A service app sent `X-User-Token` | -| `401` | `user_token_required` | A delegated app sent no `X-User-Token` | -| `401` | `invalid_user_token` | The user token is expired or from another client | -| `403` | `user_not_signed_in` | The user has never signed in to the portal | -| `403` | `app_not_authorized` | The user has not allowed the app | -| `403` | `app_needs_user` | A service app called a route without a privilege | -| `403` | `app_not_allowed` | The route is for the user only | +| Status | `code` | Cause | +|--------|-------------------|-------------------------------------------| +| `401` | `invalid_token` | Unknown app or wrong secret | +| `403` | `app_disabled` | The app is disabled | +| `403` | `app_not_allowed` | The route has no privilege an app can use | Who made a call is `Caller.Requester()`: `app/<key>` when an app called, otherwise `user/<id>`. Audit rows written during an app's call also carry `app_key`. diff --git a/docs/privileges.md b/docs/privileges.md index 802a76e35..9c01d5835 100644 --- a/docs/privileges.md +++ b/docs/privileges.md @@ -80,8 +80,6 @@ These routes need a verified caller but no key. | `RequireScoped` | `GET /compute-allocations/{id}`<br>`GET /compute-allocations/{id}/resources`<br>`GET /compute-allocations/{id}/memberships`<br>`GET /compute-allocations/{id}/usages`<br>`GET /compute-allocations/{id}/usages/total` | `core:allocations:read`, or a participant in the allocation; `404` otherwise | | `RequireAuth` | `GET /connectors/analytics/contexts`<br>`GET /connectors/analytics/allocations/{id}/usage-summary`<br>`GET /connectors/analytics/allocations/{id}/jobs` | Decided by allocation role alone: PI, CO_PI and ALLOCATION_MANAGER see all members, plain members see their own records | | `RequireAuth` | `GET /connectors/signer/me/certificates`<br>`POST /connectors/signer/me/certificates`<br>`GET /connectors/signer/me/certificates/{serial}`<br>`POST /connectors/signer/me/certificates/{serial}/revoke` | The caller's own certificates. Generating also needs a ready cluster account and an active allocation | -| `RequireAuth` | `GET /apps/names` | The key and name of every app, to show which app generated a certificate | -| `RequireAuthUsersOnly` | `GET /me/app-authorizations`<br>`POST /me/app-authorizations/{appId}`<br>`DELETE /me/app-authorizations/{appId}` | The caller's own allowed apps. The user only, never an app | How these routes treat apps is in [architecture.md](architecture.md#apps). diff --git a/internal/config/config.go b/internal/config/config.go index 9411a0108..97a50d80b 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -68,8 +68,6 @@ type AuthConfig struct { type OIDCConfig struct { Issuer string `yaml:"issuer"` Audience string `yaml:"audience"` - // Public client for apps. Empty turns off delegated apps. - AppsAudience string `yaml:"apps_audience"` } type ConnectorConfig struct { @@ -100,7 +98,6 @@ func LoadConfig(path string) (*Config, error) { // applyAuthDefaults enforces the auth invariants: // - Issuer and Audience are required. -// - AppsAudience, when set, must differ from Audience. // - CacheTTL <= 0 collapses to IdentityCacheDefaultTTL. // - CacheTTL > IdentityCacheMaxTTL caps at the ceiling and logs a warning. func applyAuthDefaults(a *AuthConfig) error { @@ -110,10 +107,6 @@ func applyAuthDefaults(a *AuthConfig) error { if a.OIDC.Audience == "" { return fmt.Errorf("core.auth.oidc.audience is required") } - // The same client for both would let portal tokens act as user tokens for apps, and the other way round. - if a.OIDC.AppsAudience == a.OIDC.Audience { - return fmt.Errorf("core.auth.oidc.apps_audience must be a different client from core.auth.oidc.audience") - } if a.CacheTTL <= 0 { a.CacheTTL = IdentityCacheDefaultTTL } else if a.CacheTTL > IdentityCacheMaxTTL { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index c522a2dac..7798f36c7 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -168,27 +168,6 @@ func TestLoadConfig_AuthRejectsEmptyAudience(t *testing.T) { assert.Contains(t, err.Error(), "core.auth.oidc.audience") } -// Make sure Custos refuses to start when the app client is the portal client. -func TestLoadConfig_AuthRejectsAppsAudienceSameAsPortal(t *testing.T) { - yaml := `core: - database: - url: "dsn" - api: - port: 8080 - log_level: "info" - auth: - oidc: - issuer: "https://idp.example" - audience: "portal-client" - apps_audience: "portal-client" -` - _, err := LoadConfig(writeTempYAML(t, yaml)) - if err == nil { - t.Fatal("expected error for apps_audience equal to audience, got nil") - } - assert.Contains(t, err.Error(), "core.auth.oidc.apps_audience") -} - func TestLoadConfig_AuthClampsTTLAboveMax(t *testing.T) { yaml := `core: database: diff --git a/internal/db/migrations/000009_apps.down.sql b/internal/db/migrations/000009_apps.down.sql index ca206480e..a8e929bdc 100644 --- a/internal/db/migrations/000009_apps.down.sql +++ b/internal/db/migrations/000009_apps.down.sql @@ -15,6 +15,5 @@ -- specific language governing permissions and limitations -- under the License. -DROP TABLE IF EXISTS app_grants; DROP TABLE IF EXISTS app_privileges; DROP TABLE IF EXISTS apps; diff --git a/internal/db/migrations/000009_apps.up.sql b/internal/db/migrations/000009_apps.up.sql index 5db9926c6..cbbacc147 100644 --- a/internal/db/migrations/000009_apps.up.sql +++ b/internal/db/migrations/000009_apps.up.sql @@ -18,11 +18,10 @@ 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. + key VARCHAR(50) NOT NULL, -- The app's readable ID. It is in the token and in audit records. name VARCHAR(100) NOT NULL, description TEXT NOT NULL DEFAULT '', status VARCHAR(16) NOT NULL DEFAULT 'ACTIVE', - mode VARCHAR(16) NOT NULL, 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, @@ -31,7 +30,6 @@ CREATE TABLE IF NOT EXISTS apps PRIMARY KEY (id), CONSTRAINT uq_apps_key UNIQUE (key), -- Deleted apps keep their key, so it is never reused. CONSTRAINT chk_apps_status CHECK (status IN ('ACTIVE', 'DISABLED', 'DELETED')), - CONSTRAINT chk_apps_mode CHECK (mode IN ('SERVICE', 'DELEGATED')), CONSTRAINT fk_apps_created_by FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE RESTRICT ); @@ -45,14 +43,3 @@ CREATE TABLE IF NOT EXISTS app_privileges PRIMARY KEY (app_id, privilege), CONSTRAINT fk_app_privileges_app FOREIGN KEY (app_id) REFERENCES apps (id) ON DELETE RESTRICT ); - --- A row means the user has allowed the app. Removing it is recorded in audit_events. -CREATE TABLE IF NOT EXISTS app_grants -( - app_id VARCHAR(255) NOT NULL, - user_id VARCHAR(255) NOT NULL, - granted_at TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), - PRIMARY KEY (app_id, user_id), - CONSTRAINT fk_app_grants_app FOREIGN KEY (app_id) REFERENCES apps (id) ON DELETE RESTRICT, - CONSTRAINT fk_app_grants_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE RESTRICT -); diff --git a/internal/server/app.go b/internal/server/app.go index 6065a4980..a96102c99 100644 --- a/internal/server/app.go +++ b/internal/server/app.go @@ -29,21 +29,10 @@ type appWithTokenView struct { Token string `json:"token"` } -type appDetailView struct { - models.App - AuthorizedUsers int `json:"authorized_users"` -} - -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"` - Mode models.AppMode `json:"mode"` Privileges []models.PrivilegeKey `json:"privileges"` } @@ -89,26 +78,6 @@ func (s *Server) listAppPrivileges(w http.ResponseWriter, r *http.Request) { common.WriteJSON(w, http.StatusOK, models.AppPrivileges()) } -// @Summary List the key and name of every app, including disabled and deleted 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.ListAppNames(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 @@ -132,7 +101,7 @@ func (s *Server) createApp(w http.ResponseWriter, r *http.Request) { common.WriteError(w, http.StatusBadRequest, err) return } - a, token, err := s.svc.CreateApp(r.Context(), req.Key, req.Name, req.Description, req.Mode, req.Privileges, caller.UserID) + a, token, err := s.svc.CreateApp(r.Context(), req.Key, req.Name, req.Description, req.Privileges, caller.UserID) if err != nil { common.WriteServiceError(w, err) return @@ -145,27 +114,18 @@ func (s *Server) createApp(w http.ResponseWriter, r *http.Request) { // @Security BearerAuth // @Produce json // @Param id path string true "App ID" -// @Success 200 {object} appDetailView +// @Success 200 {object} models.App // @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")) - if err != nil { - common.WriteServiceError(w, err) - return - } - count, err := s.svc.CountAppAuthorizations(r.Context(), a.ID) - if err != nil { - common.WriteServiceError(w, err) - return - } - common.WriteJSON(w, http.StatusOK, appDetailView{App: *a, AuthorizedUsers: count}) + writeApp(w, a, err) } // @Summary Delete a disabled app -// @Description Every user's allow is removed. The key can never be used again. +// @Description The key can never be used again. // @Tags Apps // @Security BearerAuth // @Param id path string true "App ID" @@ -273,70 +233,6 @@ func (s *Server) issueAppSecret(w http.ResponseWriter, r *http.Request) { common.WriteJSON(w, http.StatusOK, appWithTokenView{App: *a, Token: token}) } -type appAuthorizationView struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Authorized bool `json:"authorized"` -} - -// @Summary List the apps that can act for the caller -// @Tags Apps -// @Security BearerAuth -// @Produce json -// @Success 200 {array} appAuthorizationView -// @Failure 401 {object} object{error=string} -// @Router /me/app-authorizations [get] -func (s *Server) listAppAuthorizations(w http.ResponseWriter, r *http.Request) { - caller := common.RequireCaller(w, r) - if caller == nil { - return - } - authorizations, err := s.svc.ListAppAuthorizations(r.Context(), caller.UserID) - if err != nil { - common.WriteServiceError(w, err) - return - } - views := make([]appAuthorizationView, 0, len(authorizations)) - for _, item := range authorizations { - views = append(views, appAuthorizationView{ID: item.App.ID, Name: item.App.Name, Description: item.App.Description, Authorized: item.Authorized}) - } - common.WriteJSON(w, http.StatusOK, views) -} - -// @Summary Allow an app to act for the caller -// @Tags Apps -// @Security BearerAuth -// @Param appId path string true "App ID" -// @Success 204 -// @Failure 400 {object} object{error=string} "The app cannot be authorized" -// @Failure 401 {object} object{error=string} -// @Failure 404 {object} object{error=string} -// @Router /me/app-authorizations/{appId} [post] -func (s *Server) authorizeApp(w http.ResponseWriter, r *http.Request) { - caller := common.RequireCaller(w, r) - if caller == nil { - return - } - writeNoContent(w, s.svc.AuthorizeApp(r.Context(), r.PathValue("appId"), caller.UserID)) -} - -// @Summary Remove an app's authorization -// @Description Certificates the app already generated stay valid. -// @Tags Apps -// @Security BearerAuth -// @Param appId path string true "App ID" -// @Success 204 -// @Failure 401 {object} object{error=string} -// @Router /me/app-authorizations/{appId} [delete] -func (s *Server) removeAppAuthorization(w http.ResponseWriter, r *http.Request) { - caller := common.RequireCaller(w, r) - if caller == nil { - return - } - writeNoContent(w, s.svc.RemoveAppAuthorization(r.Context(), r.PathValue("appId"), caller.UserID)) -} - func writeNoContent(w http.ResponseWriter, err error) { if err != nil { common.WriteServiceError(w, err) diff --git a/internal/server/privilege.go b/internal/server/privilege.go index 164c5e1a5..e6f60cc87 100644 --- a/internal/server/privilege.go +++ b/internal/server/privilege.go @@ -101,12 +101,7 @@ func (s *Server) getCallerProfile(w http.ResponseWriter, r *http.Request) { } keys := []models.PrivilegeKey{} roles := []CallerRoleGrant{} - if caller.IsApp() { - // Show what the app can use for this user, privileges both hold. - if shared := identity.PrivilegesFromContext(r.Context()); shared != nil { - keys = shared - } - } else if !caller.NeedsOnboarding { + if !caller.NeedsOnboarding { // Read fresh instead of using the cached context set, so roles and the // effective privileges in one response always agree with each other. if keys, err = s.svc.EffectivePrivileges(r.Context(), caller.UserID); err != nil { diff --git a/internal/server/privilege_integration_test.go b/internal/server/privilege_integration_test.go index 472892edd..3d751e830 100644 --- a/internal/server/privilege_integration_test.go +++ b/internal/server/privilege_integration_test.go @@ -29,7 +29,6 @@ import ( "github.com/apache/airavata-custos/internal/tracing" "github.com/apache/airavata-custos/internal/tracing/tracingtest" - "github.com/apache/airavata-custos/pkg/identity" "github.com/apache/airavata-custos/pkg/models" ) @@ -173,29 +172,6 @@ func TestGetCallerProfile_IncludesOwnRoles(t *testing.T) { } } -// Make sure a delegated app reading the profile sees only the privileges it shares with the user, not the user's own privileges or roles. -func TestGetCallerProfile_DelegatedAppSeesOnlySharedPrivileges(t *testing.T) { - database, _, srv := setupTestStack(t) - user := seedUser(t, database, "[email protected]") - seedPrivilegesGrant(t, database, user) - - rr := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/me", nil) - ctx, _ := tracing.Start(req.Context(), "test.request") - ctx = identity.WithCaller(ctx, &identity.Caller{UserID: user, AppID: "app-1", AppKey: "gateway"}) - srv.ServeHTTP(rr, req.WithContext(identity.WithPrivilegesForTest(ctx, nil))) - if rr.Code != http.StatusOK { - t.Fatalf("status: got %d, want 200; body=%s", rr.Code, rr.Body.String()) - } - var body CallerProfileResponse - if err := json.NewDecoder(rr.Body).Decode(&body); err != nil { - t.Fatalf("decode: %v", err) - } - if len(body.Privileges) != 0 || len(body.Roles) != 0 { - t.Errorf("privileges %v, roles %v: want both empty", body.Privileges, body.Roles) - } -} - func TestRequirePrivilege_NoGrants_403(t *testing.T) { database, _, srv := setupTestStack(t) user := seedUser(t, database, "[email protected]") diff --git a/internal/server/server.go b/internal/server/server.go index e6e698bea..829c0fc59 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -203,10 +203,6 @@ func (s *Server) routes() { s.router.RequirePrivilege("GET /apps", models.AppsManage, s.listApps) s.router.RequirePrivilege("POST /apps", models.AppsManage, s.createApp) s.router.RequirePrivilege("GET /apps/privileges", models.AppsManage, s.listAppPrivileges) - s.router.RequireAuth("GET /apps/names", s.listAppNames) - s.router.RequireAuthUsersOnly("GET /me/app-authorizations", s.listAppAuthorizations) - s.router.RequireAuthUsersOnly("POST /me/app-authorizations/{appId}", s.authorizeApp) - s.router.RequireAuthUsersOnly("DELETE /me/app-authorizations/{appId}", s.removeAppAuthorization) s.router.RequirePrivilege("GET /apps/{id}", models.AppsManage, s.getApp) s.router.RequirePrivilege("PUT /apps/{id}", models.AppsManage, s.updateApp) s.router.RequirePrivilege("DELETE /apps/{id}", models.AppsManage, s.deleteApp) diff --git a/internal/store/app_store.go b/internal/store/app_store.go index dd87dd5c1..ab6266482 100644 --- a/internal/store/app_store.go +++ b/internal/store/app_store.go @@ -27,7 +27,7 @@ import ( "github.com/apache/airavata-custos/pkg/models" ) -const appColumns = `id, key, name, description, status, mode, secret_hash, secret_hint, created_by, created_at, updated_at` +const appColumns = `id, key, name, description, status, secret_hash, secret_hint, created_by, created_at, updated_at` type pgAppStore struct { db *sqlx.DB @@ -87,9 +87,9 @@ func (s *pgAppStore) List(ctx context.Context) ([]models.App, error) { 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, status, mode, 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.Status, a.Mode, a.SecretHash, a.SecretHint, a.CreatedBy); err != nil { + `INSERT INTO apps (id, key, name, description, status, secret_hash, secret_hint, created_by) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, + a.ID, a.Key, a.Name, a.Description, a.Status, a.SecretHash, a.SecretHint, a.CreatedBy); err != nil { return err } for _, privilege := range a.Privileges { @@ -107,49 +107,3 @@ func (s *pgAppStore) Update(ctx context.Context, tx *sql.Tx, a *models.App) erro a.Name, a.Description, a.Status, a.SecretHash, a.SecretHint, a.ID) return err } - -func (s *pgAppStore) HasGrant(ctx context.Context, appID, userID string) (bool, error) { - var granted bool - err := s.db.GetContext(ctx, &granted, `SELECT EXISTS (SELECT 1 FROM app_grants WHERE app_id = $1 AND user_id = $2)`, appID, userID) - return granted, err -} - -func (s *pgAppStore) ListGrantedAppIDs(ctx context.Context, userID string) ([]string, error) { - var appIDs []string - err := s.db.SelectContext(ctx, &appIDs, `SELECT app_id FROM app_grants WHERE user_id = $1`, userID) - return appIDs, err -} - -func (s *pgAppStore) CreateGrant(ctx context.Context, tx *sql.Tx, appID, userID string) error { - _, err := tx.ExecContext(ctx, `INSERT INTO app_grants (app_id, user_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, appID, userID) - return err -} - -func (s *pgAppStore) DeleteGrant(ctx context.Context, tx *sql.Tx, appID, userID string) (bool, error) { - return execOnce(ctx, tx, `DELETE FROM app_grants WHERE app_id = $1 AND user_id = $2`, appID, userID) -} - -func (s *pgAppStore) CountGrants(ctx context.Context, appID string) (int, error) { - var count int - err := s.db.GetContext(ctx, &count, `SELECT COUNT(*) FROM app_grants WHERE app_id = $1`, appID) - return count, err -} - -func (s *pgAppStore) DeleteAllGrants(ctx context.Context, tx *sql.Tx, appID string) (int64, error) { - res, err := tx.ExecContext(ctx, `DELETE FROM app_grants WHERE app_id = $1`, appID) - if err != nil { - return 0, err - } - return res.RowsAffected() -} - -func (s *pgAppStore) ReassignGrants(ctx context.Context, tx *sql.Tx, fromUserID, toUserID string) error { - if _, err := tx.ExecContext(ctx, - `INSERT INTO app_grants (app_id, user_id, granted_at) - SELECT app_id, $2, granted_at FROM app_grants WHERE user_id = $1 - ON CONFLICT DO NOTHING`, fromUserID, toUserID); err != nil { - return err - } - _, err := tx.ExecContext(ctx, `DELETE FROM app_grants WHERE user_id = $1`, fromUserID) - return err -} diff --git a/internal/store/store.go b/internal/store/store.go index c67410876..f31c49512 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -569,13 +569,6 @@ type AppStore interface { 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 - HasGrant(ctx context.Context, appID, userID string) (bool, error) - ListGrantedAppIDs(ctx context.Context, userID string) ([]string, error) - CreateGrant(ctx context.Context, tx *sql.Tx, appID, userID string) error - DeleteGrant(ctx context.Context, tx *sql.Tx, appID, userID string) (bool, error) - CountGrants(ctx context.Context, appID string) (int, error) - DeleteAllGrants(ctx context.Context, tx *sql.Tx, appID string) (int64, error) - ReassignGrants(ctx context.Context, tx *sql.Tx, fromUserID, toUserID string) error } // UserAgreementAcceptanceStore defines persistence operations for the record of who accepted which agreement. diff --git a/pkg/identity/app_middleware_test.go b/pkg/identity/app_middleware_test.go index 61c0a58fd..790e26a12 100644 --- a/pkg/identity/app_middleware_test.go +++ b/pkg/identity/app_middleware_test.go @@ -20,7 +20,6 @@ package identity import ( "context" "encoding/json" - "errors" "net/http" "net/http/httptest" "testing" @@ -29,85 +28,30 @@ import ( ) type fakeApps struct { - app *models.App - err error - allowed bool + app *models.App + err error } func (f fakeApps) ResolveApp(context.Context, string) (*models.App, error) { return f.app, f.err } -func (f fakeApps) IsAppAuthorized(context.Context, string, string) (bool, error) { - return f.allowed, nil +func appWith(privileges ...models.PrivilegeKey) fakeApps { + return fakeApps{app: &models.App{ID: "a1", Key: "tool", Privileges: privileges}} } -// fakeAppsClient accepts any user token except one from another client. -type fakeAppsClient struct{} - -func (fakeAppsClient) Verify(_ context.Context, token string) (*Claims, error) { - if token == "other-client-token" { - return nil, errors.New("wrong audience") - } - return &Claims{Sub: "sub-1"}, nil -} - -// fakeUser is an active user who accepted the agreement, unless a field says otherwise. -type fakeUser struct { - privileges []models.PrivilegeKey - consentPending bool - err error -} - -func (f fakeUser) ResolveCaller(context.Context, *Claims) (*Caller, []models.PrivilegeKey, error) { - if f.err != nil { - return nil, nil, f.err - } - return &Caller{UserID: "u1", ConsentPending: f.consentPending}, f.privileges, nil -} - -type appCall struct { - apps fakeApps - user fakeUser - userToken string - appsClientOff bool // no app client configured - method string // GET when empty - path string -} - -func serviceApp(privileges ...models.PrivilegeKey) *models.App { - return &models.App{ID: "a1", Key: "tool", Mode: models.AppService, Privileges: privileges} -} - -func delegatedApp(privileges ...models.PrivilegeKey) *models.App { - return &models.App{ID: "a1", Key: "gateway", Mode: models.AppDelegated, Privileges: privileges} -} - -// serve runs an app call through AppMiddleware. The router has a privileged route, the user's -// own routes registered as in the server, and the app authorization route. -func serve(call appCall) (int, string) { +// serve runs an app call through AppMiddleware. The router has one route of each kind, +// registered the way the server registers them. +func serve(apps fakeApps, method, path string) (int, string) { ok := func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) } router := NewRouter(http.NewServeMux()) router.RequirePrivilege("GET /clusters", models.ClustersWrite, ok) router.RequireAuth("GET /me/certificates", ok) router.RequireScoped("GET /projects/{id}", func(http.ResponseWriter, *http.Request) bool { return true }, ok) router.RequireAuthWithoutUserConsent("GET /me", ok) - router.RequireAuthWithoutUserConsent("POST /me/agreements/{id}/accept", ok) - router.RequireAuthUsersOnly("GET /me/app-authorizations", ok) nonAppCalls := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusTeapot) }) - var userTokens TokenVerifier = fakeAppsClient{} - if call.appsClientOff { - userTokens = nil - } - handler := AppMiddleware(call.apps, userTokens, call.user, router, nonAppCalls) + handler := AppMiddleware(apps, router, nonAppCalls) - method := call.method - if method == "" { - method = http.MethodGet - } - req := httptest.NewRequest(method, call.path, nil) + req := httptest.NewRequest(method, path, nil) req.Header.Set("Authorization", "Bearer "+AppTokenPrefix+"tool.secret") - if call.userToken != "" { - req.Header.Set(UserTokenHeader, call.userToken) - } rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) @@ -118,139 +62,49 @@ func serve(call appCall) (int, string) { return rec.Code, body.Code } -// Make sure a service app can call a privileged route only when it has that privilege. -func TestServiceApp_NeedsTheRoutePrivilege(t *testing.T) { - if code, errorCode := serve(appCall{apps: fakeApps{app: serviceApp(models.ClustersWrite)}, path: "/clusters"}); code != http.StatusOK { +// Make sure an app can call a privileged route only when it has that privilege. +func TestApp_NeedsTheRoutePrivilege(t *testing.T) { + if code, errorCode := serve(appWith(models.ClustersWrite), http.MethodGet, "/clusters"); code != http.StatusOK { t.Errorf("app with the privilege: got %d %s", code, errorCode) } - if code, errorCode := serve(appCall{apps: fakeApps{app: serviceApp(models.ClustersRead)}, path: "/clusters"}); code != http.StatusForbidden || errorCode != "insufficient_privilege" { + if code, errorCode := serve(appWith(models.ClustersRead), http.MethodGet, "/clusters"); code != http.StatusForbidden || errorCode != "insufficient_privilege" { t.Errorf("app without the privilege: got %d %s", code, errorCode) } } -// Make sure a service app can't use routes without a privilege, since those work on the caller's own data. -func TestServiceApp_RefusedOnMeRoutes(t *testing.T) { - code, errorCode := serve(appCall{apps: fakeApps{app: serviceApp(models.ClustersWrite)}, path: "/me"}) - if code != http.StatusForbidden || errorCode != "app_needs_user" { - t.Fatalf("got %d %s", code, errorCode) - } -} - -// Make sure a service app can't act for a user by sending a user token. -func TestServiceApp_RefusesUserToken(t *testing.T) { - code, errorCode := serve(appCall{apps: fakeApps{app: serviceApp(models.ClustersWrite)}, userToken: "user-token", path: "/clusters"}) - if code != http.StatusForbidden || errorCode != "user_token_not_allowed" { - t.Fatalf("got %d %s", code, errorCode) - } -} - -// Make sure a delegated app can't call anything without a user token. -func TestDelegatedApp_NeedsUserToken(t *testing.T) { - code, errorCode := serve(appCall{apps: fakeApps{app: delegatedApp(models.ClustersWrite), allowed: true}, path: "/clusters"}) - if code != http.StatusUnauthorized || errorCode != "user_token_required" { - t.Fatalf("got %d %s", code, errorCode) - } -} - -// Make sure a user token from another client, including the portal, is refused. -func TestDelegatedApp_RefusesTokenFromAnotherClient(t *testing.T) { - code, errorCode := serve(appCall{apps: fakeApps{app: delegatedApp(), allowed: true}, userToken: "other-client-token", path: "/me"}) - if code != http.StatusUnauthorized || errorCode != "invalid_user_token" { - t.Fatalf("got %d %s", code, errorCode) - } -} - -// Make sure an app can't act for a user who hasn't allowed it. -func TestDelegatedApp_NeedsUsersAllow(t *testing.T) { - code, errorCode := serve(appCall{apps: fakeApps{app: delegatedApp()}, userToken: "user-token", path: "/me"}) - if code != http.StatusForbidden || errorCode != "app_not_authorized" { - t.Fatalf("got %d %s", code, errorCode) - } -} - -// Make sure a delegated app can call a privileged route only when both the app and the user have the privilege. -func TestDelegatedApp_GetsOnlyPrivilegesBothHold(t *testing.T) { - tests := []struct { - name string - app []models.PrivilegeKey - user []models.PrivilegeKey - want int - }{ - {"both hold it", []models.PrivilegeKey{models.ClustersWrite}, []models.PrivilegeKey{models.ClustersWrite}, http.StatusOK}, - {"only the app", []models.PrivilegeKey{models.ClustersWrite}, nil, http.StatusForbidden}, - {"only the user", nil, []models.PrivilegeKey{models.ClustersWrite}, http.StatusForbidden}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - call := appCall{apps: fakeApps{app: delegatedApp(tt.app...), allowed: true}, user: fakeUser{privileges: tt.user}, userToken: "user-token", path: "/clusters"} - if code, errorCode := serve(call); code != tt.want { - t.Fatalf("got %d %s, want %d", code, errorCode, tt.want) - } - }) - } -} - -// Make sure a delegated app can use the user's own routes, including the profile, but can't allow or remove apps for them. -func TestDelegatedApp_CannotManageAppAuthorizations(t *testing.T) { - call := appCall{apps: fakeApps{app: delegatedApp(), allowed: true}, userToken: "user-token"} - for _, path := range []string{"/me/certificates", "/me"} { - call.path = path - if code, errorCode := serve(call); code != http.StatusOK { - t.Errorf("%s: got %d %s", path, code, errorCode) +// Make sure an app can't use any route without a privilege, such as /me or a scoped route, +// since those work on a person's own data and an app never acts as a person. +func TestApp_RefusedOnRoutesWithoutAPrivilege(t *testing.T) { + for _, route := range []struct{ method, path string }{ + {http.MethodGet, "/me/certificates"}, + {http.MethodGet, "/projects/p1"}, + {http.MethodGet, "/me"}, + } { + if code, errorCode := serve(appWith(models.ClustersWrite), route.method, route.path); code != http.StatusForbidden || errorCode != "app_not_allowed" { + t.Errorf("%s %s: got %d %s", route.method, route.path, code, errorCode) } } - call.path = "/me/app-authorizations" - if code, errorCode := serve(call); code != http.StatusForbidden || errorCode != "app_not_allowed" { - t.Errorf("app authorizations: got %d %s", code, errorCode) - } -} - -// Make sure a delegated app cannot accept a user agreement for the user, even though it can read the profile on the same kind of route. -func TestDelegatedApp_CannotAcceptAgreement(t *testing.T) { - call := appCall{apps: fakeApps{app: delegatedApp(), allowed: true}, userToken: "user-token", method: http.MethodPost, path: "/me/agreements/a1/accept"} - if code, errorCode := serve(call); code != http.StatusForbidden || errorCode != "app_not_allowed" { - t.Fatalf("got %d %s", code, errorCode) - } -} - -// Make sure a service app can't use a route that depends on the user's relation to the resource. -func TestServiceApp_RefusedOnScopedRoutes(t *testing.T) { - code, errorCode := serve(appCall{apps: fakeApps{app: serviceApp(models.ClustersWrite)}, path: "/projects/p1"}) - if code != http.StatusForbidden || errorCode != "app_needs_user" { - t.Fatalf("got %d %s", code, errorCode) - } -} - -// Make sure a delegated app can't act for a user who still has a user agreement to accept. -func TestDelegatedApp_RefusedWhileAgreementPending(t *testing.T) { - call := appCall{apps: fakeApps{app: delegatedApp(), allowed: true}, user: fakeUser{consentPending: true}, userToken: "user-token", path: "/me"} - if code, errorCode := serve(call); code != http.StatusForbidden || errorCode != "consent_required" { - t.Fatalf("got %d %s", code, errorCode) - } -} - -// Make sure a delegated app can't act for someone who has never signed in to the portal. -func TestDelegatedApp_RefusedForUserNeverSignedIn(t *testing.T) { - call := appCall{apps: fakeApps{app: delegatedApp(), allowed: true}, user: fakeUser{err: ErrNotLinked}, userToken: "user-token", path: "/me"} - if code, errorCode := serve(call); code != http.StatusForbidden || errorCode != "user_not_signed_in" { - t.Fatalf("got %d %s", code, errorCode) - } -} - -// Make sure delegated apps are refused when no app client is configured. -func TestDelegatedApp_RefusedWhenAppsClientOff(t *testing.T) { - call := appCall{apps: fakeApps{app: delegatedApp(), allowed: true}, userToken: "user-token", appsClientOff: true, path: "/me"} - if code, errorCode := serve(call); code != http.StatusUnauthorized || errorCode != "invalid_user_token" { - 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 := serve(appCall{apps: fakeApps{err: ErrInvalidAppToken}, path: "/clusters"}); code != http.StatusUnauthorized || errorCode != "invalid_token" { + if code, errorCode := serve(fakeApps{err: ErrInvalidAppToken}, http.MethodGet, "/clusters"); code != http.StatusUnauthorized || errorCode != "invalid_token" { t.Errorf("unknown token: got %d %s", code, errorCode) } - if code, errorCode := serve(appCall{apps: fakeApps{err: ErrAppDisabled}, path: "/clusters"}); code != http.StatusForbidden || errorCode != "app_disabled" { + if code, errorCode := serve(fakeApps{err: ErrAppDisabled}, http.MethodGet, "/clusters"); code != http.StatusForbidden || errorCode != "app_disabled" { t.Errorf("disabled app: got %d %s", code, errorCode) } } + +// Make sure a call without an app token, such as a person's sign-in token, skips the app path. +func TestAppMiddleware_PassesOtherTokensOn(t *testing.T) { + nonAppCalls := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusTeapot) }) + handler := AppMiddleware(appWith(models.ClustersWrite), http.NotFoundHandler(), nonAppCalls) + req := httptest.NewRequest(http.MethodGet, "/clusters", nil) + req.Header.Set("Authorization", "Bearer user-token") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusTeapot { + t.Fatalf("got %d", rec.Code) + } +} diff --git a/pkg/identity/identity.go b/pkg/identity/identity.go index cc89035a3..91dd34f1d 100644 --- a/pkg/identity/identity.go +++ b/pkg/identity/identity.go @@ -39,12 +39,9 @@ type Caller struct { AppKey string } -// IsApp reports whether an app made the call, as itself or for a user. +// IsApp reports whether an app made the call. func (c *Caller) IsApp() bool { return c.AppID != "" } -// IsServiceApp reports whether an app is calling as itself, with no user. -func (c *Caller) IsServiceApp() bool { return c.AppID != "" && c.UserID == "" } - // Requester is who made the call app or a user. func (c *Caller) Requester() string { if c.IsApp() { @@ -78,7 +75,6 @@ type UserResolver interface { type AppResolver interface { ResolveApp(ctx context.Context, token string) (*models.App, error) - IsAppAuthorized(ctx context.Context, appID, userID string) (bool, error) } type ctxKey string diff --git a/pkg/identity/middleware.go b/pkg/identity/middleware.go index 01641dcc4..fa1b315a6 100644 --- a/pkg/identity/middleware.go +++ b/pkg/identity/middleware.go @@ -22,7 +22,6 @@ import ( "errors" "log/slog" "net/http" - "slices" "strings" "github.com/apache/airavata-custos/pkg/models" @@ -83,12 +82,9 @@ func Middleware(verifier TokenVerifier, resolver UserResolver, public, withoutUs // AppTokenPrefix marks a Custos issued app token (cak_ - custos app key). const AppTokenPrefix = "cak_" -// UserTokenHeader carries the user's token for a delegated app. -const UserTokenHeader = "X-User-Token" - // AppMiddleware handles calls made with an app token. Other calls go to nonAppCalls. -// A nil userTokens turns off delegated apps. -func AppMiddleware(apps AppResolver, userTokens TokenVerifier, users UserResolver, next, nonAppCalls http.Handler) http.Handler { +// An app always calls as itself, with its own privileges, never as a user. +func AppMiddleware(apps AppResolver, next, nonAppCalls 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) { @@ -109,86 +105,14 @@ func AppMiddleware(apps AppResolver, userTokens TokenVerifier, users UserResolve writeJSONError(w, http.StatusServiceUnavailable, "auth_lookup_failed", "Identity resolution failed") return } - switch app.Mode { - case models.AppService: - serveServiceApp(w, req, app, next) - case models.AppDelegated: - serveDelegatedApp(w, req, app, apps, userTokens, users, next) - default: - slog.ErrorContext(req.Context(), "app has an unknown mode", "app", app.Key, "mode", app.Mode) - writeJSONError(w, http.StatusInternalServerError, "internal_error", "App has an unknown mode") - } + ctx := WithCaller(req.Context(), &Caller{AppID: app.ID, AppKey: app.Key}) + next.ServeHTTP(w, req.WithContext(withPrivileges(ctx, app.Privileges))) }) } -// A service app acts as itself with its own privileges, and never for a user. -func serveServiceApp(w http.ResponseWriter, req *http.Request, app *models.App, next http.Handler) { - if req.Header.Get(UserTokenHeader) != "" { - writeJSONError(w, http.StatusForbidden, "user_token_not_allowed", "A service app cannot act for a user") - return - } - ctx := WithCaller(req.Context(), &Caller{AppID: app.ID, AppKey: app.Key}) - next.ServeHTTP(w, req.WithContext(withPrivileges(ctx, app.Privileges))) -} - -// A delegated app acts as the user, with only the privileges both hold. -func serveDelegatedApp(w http.ResponseWriter, req *http.Request, app *models.App, apps AppResolver, userTokens TokenVerifier, users UserResolver, next http.Handler) { - userToken := req.Header.Get(UserTokenHeader) - if userToken == "" { - writeJSONError(w, http.StatusUnauthorized, "user_token_required", "This app must send the user's token") - return - } - if userTokens == nil { - writeJSONError(w, http.StatusUnauthorized, "invalid_user_token", "Invalid or expired user token") - return - } - claims, err := userTokens.Verify(req.Context(), userToken) - if err != nil { - writeJSONError(w, http.StatusUnauthorized, "invalid_user_token", "Invalid or expired user token") - return - } - user, userPrivileges, err := users.ResolveCaller(req.Context(), claims) - if errors.Is(err, ErrNotLinked) { - writeJSONError(w, http.StatusForbidden, "user_not_signed_in", "The user has not signed in to Custos yet") - return - } - if errors.Is(err, ErrUserDisabled) { - writeJSONError(w, http.StatusForbidden, "user_disabled", "User account is disabled") - return - } - if err != nil { - slog.ErrorContext(req.Context(), "identity resolution failed", "sub", claims.Sub, "app", app.Key, "error", err.Error()) - writeJSONError(w, http.StatusServiceUnavailable, "auth_lookup_failed", "Identity resolution failed") - return - } - if user.NeedsOnboarding || user.ConsentPending { - writeJSONError(w, http.StatusForbidden, "consent_required", "The user must accept the user agreement first") - return - } - allowed, err := apps.IsAppAuthorized(req.Context(), app.ID, user.UserID) - if err != nil { - slog.ErrorContext(req.Context(), "app grant lookup failed", "app", app.Key, "error", err.Error()) - writeJSONError(w, http.StatusServiceUnavailable, "auth_lookup_failed", "Identity resolution failed") - return - } - if !allowed { - writeJSONError(w, http.StatusForbidden, "app_not_authorized", "The user has not allowed this app") - return - } - var privileges []models.PrivilegeKey - for _, privilege := range userPrivileges { - if slices.Contains(app.Privileges, privilege) { - privileges = append(privileges, privilege) - } - } - ctx := WithClaims(req.Context(), claims) - ctx = WithCaller(ctx, &Caller{UserID: user.UserID, Email: user.Email, AppID: app.ID, AppKey: app.Key}) - next.ServeHTTP(w, req.WithContext(withPrivileges(ctx, privileges))) -} - // 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, RequireAuthUsersOnly, RequireScoped, or Public. +// RequireAuth, RequireAuthWithoutUserConsent, RequireScoped, or Public. type Router struct { mux *http.ServeMux publicMux *http.ServeMux @@ -200,16 +124,7 @@ func NewRouter(mux *http.ServeMux) *Router { return &Router{mux: mux, publicMux: http.NewServeMux(), withoutUserConsentMux: http.NewServeMux()} } -func refuseServiceApps(handler http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, req *http.Request) { - if caller := CallerFromContext(req.Context()); caller != nil && caller.IsServiceApp() { - writeJSONError(w, http.StatusForbidden, "app_needs_user", "This route needs a user") - return - } - handler(w, req) - } -} - +// Routes without a privilege work on the caller's own data, so an app can't use them. func refuseApps(handler http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { if caller := CallerFromContext(req.Context()); caller != nil && caller.IsApp() { @@ -241,11 +156,6 @@ func (r *Router) Public(pattern string, handler http.HandlerFunc) { // RequireAuth registers a handler that requires a verified caller but no // specific privilege. (e.g., caller looking up their own data). func (r *Router) RequireAuth(pattern string, handler http.HandlerFunc) { - r.mux.HandleFunc(pattern, refuseServiceApps(handler)) -} - -// RequireAuthUsersOnly registers a route only the user can call, never an app. -func (r *Router) RequireAuthUsersOnly(pattern string, handler http.HandlerFunc) { r.mux.HandleFunc(pattern, refuseApps(handler)) } @@ -254,7 +164,7 @@ func (r *Router) RequireAuthUsersOnly(pattern string, handler http.HandlerFunc) // and returns false to deny, or returns true to run handler. The policy is a // required argument, so a scoped route cannot be registered without one. func (r *Router) RequireScoped(pattern string, authorize func(http.ResponseWriter, *http.Request) bool, handler http.HandlerFunc) { - r.mux.HandleFunc(pattern, refuseServiceApps(func(w http.ResponseWriter, req *http.Request) { + r.mux.HandleFunc(pattern, refuseApps(func(w http.ResponseWriter, req *http.Request) { if !authorize(w, req) { return } @@ -265,13 +175,7 @@ func (r *Router) RequireScoped(pattern string, authorize func(http.ResponseWrite // RequireAuthWithoutUserConsent registers a handler that signed-in callers // can reach before accepting the user agreement. Handlers read ClaimsFromContext. func (r *Router) RequireAuthWithoutUserConsent(pattern string, handler http.HandlerFunc) { - if strings.HasPrefix(pattern, http.MethodGet+" ") { - // A delegated app can read the user's profile here. A service app has no user, so it can't. - r.mux.HandleFunc(pattern, refuseServiceApps(handler)) - } else { - // Only the user can accept an agreement or finish onboarding, never an app. - r.mux.HandleFunc(pattern, refuseApps(handler)) - } + r.mux.HandleFunc(pattern, refuseApps(handler)) r.withoutUserConsentMux.HandleFunc(pattern, func(http.ResponseWriter, *http.Request) {}) } diff --git a/pkg/models/app.go b/pkg/models/app.go index 3bd508b6c..7bf47e221 100644 --- a/pkg/models/app.go +++ b/pkg/models/app.go @@ -28,21 +28,13 @@ const ( AppDeleted AppStatus = "DELETED" ) -type AppMode string - -const ( - AppService AppMode = "SERVICE" - AppDelegated AppMode = "DELEGATED" -) - -// App is a tool that calls Custos with its own token, on the same routes as users. +// App is a tool that calls Custos as itself with its own token, never as a user. 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"` Status AppStatus `json:"status" db:"status"` - Mode AppMode `json:"mode" db:"mode"` SecretHash string `json:"-" db:"secret_hash"` SecretHint string `json:"secret_hint" db:"secret_hint"` CreatedBy string `json:"created_by" db:"created_by"` diff --git a/pkg/service/app.go b/pkg/service/app.go index 2d7e44ccc..5afebc037 100644 --- a/pkg/service/app.go +++ b/pkg/service/app.go @@ -34,20 +34,18 @@ import ( ) const ( - appAuditCreated = "APP_CREATED" - appAuditUpdated = "APP_UPDATED" - appAuditDisabled = "APP_DISABLED" - appAuditEnabled = "APP_ENABLED" - appAuditSecretIssued = "APP_SECRET_ISSUED" - appAuditAuthorized = "APP_AUTHORIZED" - appAuditAuthorizationRemoved = "APP_AUTHORIZATION_REMOVED" - appAuditDeleted = "APP_DELETED" + appAuditCreated = "APP_CREATED" + appAuditUpdated = "APP_UPDATED" + appAuditDisabled = "APP_DISABLED" + appAuditEnabled = "APP_ENABLED" + appAuditSecretIssued = "APP_SECRET_ISSUED" + appAuditDeleted = "APP_DELETED" appNameMaxLength = 100 appSecretHintLength = 4 ) -// The token splits on "." and the certificate key ID splits on ":", so an app key can have neither. +// The token splits on ".", so an app key can't have one. var appKeyRegex = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`) func hashAppSecret(secret string) string { @@ -77,12 +75,10 @@ func validateAppName(name string) (string, error) { return name, nil } -func validateAppAccess(mode models.AppMode, privileges []models.PrivilegeKey) error { - if mode != models.AppService && mode != models.AppDelegated { - return fmt.Errorf("%w: mode must be %s or %s", ErrInvalidInput, models.AppService, models.AppDelegated) - } - if mode == models.AppService && len(privileges) == 0 { - return fmt.Errorf("%w: a service app needs at least one privilege", ErrInvalidInput) +// An app with no privileges could not call anything. +func validateAppPrivileges(privileges []models.PrivilegeKey) error { + if len(privileges) == 0 { + return fmt.Errorf("%w: an app needs at least one privilege", ErrInvalidInput) } for _, privilege := range privileges { if !models.IsAppPrivilege(privilege) { @@ -110,11 +106,6 @@ func (s *Service) ListApps(ctx context.Context) ([]models.App, error) { return slices.DeleteFunc(apps, func(a models.App) bool { return a.Status == models.AppDeleted }), nil } -// ListAppNames includes deleted apps, since older records still point at their keys. -func (s *Service) ListAppNames(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 { @@ -126,13 +117,8 @@ func (s *Service) GetApp(ctx context.Context, id string) (*models.App, error) { return a, nil } -// CountAppAuthorizations is how many users have allowed the app. -func (s *Service) CountAppAuthorizations(ctx context.Context, appID string) (int, error) { - return s.apps.CountGrants(ctx, appID) -} - // CreateApp The returned token cannot be read again. -func (s *Service) CreateApp(ctx context.Context, key, name, description string, mode models.AppMode, privileges []models.PrivilegeKey, actorID string) (*models.App, string, error) { +func (s *Service) CreateApp(ctx context.Context, key, name, description string, privileges []models.PrivilegeKey, actorID string) (*models.App, string, error) { if err := validateAppKey(key); err != nil { return nil, "", err } @@ -142,7 +128,7 @@ func (s *Service) CreateApp(ctx context.Context, key, name, description string, } slices.Sort(privileges) privileges = slices.Compact(privileges) - if err := validateAppAccess(mode, privileges); err != nil { + if err := validateAppPrivileges(privileges); err != nil { return nil, "", err } a := &models.App{ @@ -151,7 +137,6 @@ func (s *Service) CreateApp(ctx context.Context, key, name, description string, Name: name, Description: description, Status: models.AppActive, - Mode: mode, CreatedBy: actorID, Privileges: privileges, } @@ -163,7 +148,7 @@ func (s *Service) CreateApp(ctx context.Context, key, name, description string, 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, "mode": a.Mode, "privileges": a.Privileges}) + return s.writeAuditTx(ctx, tx, "app", appAuditCreated, a.ID, map[string]any{"actor_id": actorID, "name": a.Name, "privileges": a.Privileges}) }); err != nil { return nil, "", err } @@ -213,8 +198,7 @@ func (s *Service) EnableApp(ctx context.Context, id, actorID string) (*models.Ap return s.changeApp(ctx, id, actorID, appAuditEnabled, func(a *models.App) { a.Status = models.AppActive }) } -// DeleteApp soft deletes a disabled app and removes every user's authorizations. -// The row is kept so the app key is never reused. +// DeleteApp soft deletes a disabled app. The row is kept so the app key is never reused. func (s *Service) DeleteApp(ctx context.Context, id, actorID string) error { return s.inTx(ctx, func(tx *sql.Tx) error { if err := s.assertHasPrivilegeTx(ctx, tx, actorID, models.AppsManage); err != nil { @@ -230,16 +214,12 @@ func (s *Service) DeleteApp(ctx context.Context, id, actorID string) error { if a.Status != models.AppDisabled { return fmt.Errorf("%w: disable the app before deleting it", ErrInUse) } - removed, err := s.apps.DeleteAllGrants(ctx, tx, id) - if err != nil { - return fmt.Errorf("delete app grants: %w", err) - } // Clear the secret so the old token can never work again even if the status is changed back. a.Status, a.SecretHash = models.AppDeleted, "" if err := s.apps.Update(ctx, tx, a); err != nil { return fmt.Errorf("delete app: %w", err) } - return s.writeAuditTx(ctx, tx, "app", appAuditDeleted, id, map[string]any{"actor_id": actorID, "key": a.Key, "name": a.Name, "grants_removed": removed}) + return s.writeAuditTx(ctx, tx, "app", appAuditDeleted, id, map[string]any{"actor_id": actorID, "key": a.Key, "name": a.Name}) }) } @@ -268,63 +248,3 @@ func (s *Service) ResolveApp(ctx context.Context, token string) (*models.App, er a.Privileges = slices.DeleteFunc(a.Privileges, func(p models.PrivilegeKey) bool { return !models.IsAppPrivilege(p) }) return a, nil } - -// AppAuthorization is one app a user can allow. -type AppAuthorization struct { - App models.App - Authorized bool -} - -func (s *Service) ListAppAuthorizations(ctx context.Context, userID string) ([]AppAuthorization, error) { - apps, err := s.apps.List(ctx) - if err != nil { - return nil, fmt.Errorf("list apps: %w", err) - } - granted, err := s.apps.ListGrantedAppIDs(ctx, userID) - if err != nil { - return nil, fmt.Errorf("list app grants: %w", err) - } - var authorizations []AppAuthorization - for _, a := range apps { - if a.Status == models.AppActive && a.Mode == models.AppDelegated { - authorizations = append(authorizations, AppAuthorization{App: a, Authorized: slices.Contains(granted, a.ID)}) - } - } - return authorizations, nil -} - -func (s *Service) AuthorizeApp(ctx context.Context, appID, userID string) error { - a, err := s.GetApp(ctx, appID) - if err != nil { - return err - } - if a.Status != models.AppActive { - return fmt.Errorf("%w: this app is disabled", ErrInvalidInput) - } - if a.Mode != models.AppDelegated { - return fmt.Errorf("%w: this app is not delegated", ErrInvalidInput) - } - return s.inTx(ctx, func(tx *sql.Tx) error { - if err := s.apps.CreateGrant(ctx, tx, appID, userID); err != nil { - return fmt.Errorf("insert app grant: %w", err) - } - return s.writeAuditTx(ctx, tx, "app", appAuditAuthorized, appID, map[string]any{"user_id": userID}) - }) -} - -func (s *Service) RemoveAppAuthorization(ctx context.Context, appID, userID string) error { - return s.inTx(ctx, func(tx *sql.Tx) error { - removed, err := s.apps.DeleteGrant(ctx, tx, appID, userID) - if err != nil { - return fmt.Errorf("delete app grant: %w", err) - } - if !removed { - return nil - } - return s.writeAuditTx(ctx, tx, "app", appAuditAuthorizationRemoved, appID, map[string]any{"user_id": userID}) - }) -} - -func (s *Service) IsAppAuthorized(ctx context.Context, appID, userID string) (bool, error) { - return s.apps.HasGrant(ctx, appID, userID) -} diff --git a/pkg/service/app_integration_test.go b/pkg/service/app_integration_test.go index 58170122d..f2517f674 100644 --- a/pkg/service/app_integration_test.go +++ b/pkg/service/app_integration_test.go @@ -35,19 +35,10 @@ import ( const testAppPrivilege models.PrivilegeKey = "test:items:create" -func registerTestAppPrivilege() { +// testAppPrivileges registers the test key as allowed for apps and returns it as an app's privileges. +func testAppPrivileges() []models.PrivilegeKey { models.AllowForApps(testAppPrivilege) -} - -// newServiceApp creates a service app named temp-tool. -func newServiceApp(t *testing.T, svc *Service, adminID string) *models.App { - t.Helper() - registerTestAppPrivilege() - app, _, err := svc.CreateApp(ctx(), "temp-tool", "Temp Tool", "", models.AppService, []models.PrivilegeKey{testAppPrivilege}, adminID) - if err != nil { - t.Fatalf("create service app: %v", err) - } - return app + return []models.PrivilegeKey{testAppPrivilege} } func seedAppAdmin(t *testing.T, database *sqlx.DB) string { @@ -64,15 +55,14 @@ func seedAppAdmin(t *testing.T, database *sqlx.DB) string { func newTestApp(t *testing.T, svc *Service, adminID string) (*models.App, string) { t.Helper() - registerTestAppPrivilege() - app, token, err := svc.CreateApp(ctx(), "test-gateway", "Test Gateway", "", models.AppDelegated, []models.PrivilegeKey{testAppPrivilege}, adminID) + app, token, err := svc.CreateApp(ctx(), "test-gateway", "Test Gateway", "", testAppPrivileges(), adminID) if err != nil { t.Fatalf("create app: %v", err) } return app, token } -// Make sure the token from creation finds the app with its mode and privileges, and the secret isn't stored. +// Make sure the token from creation finds the app with its privileges, and the secret isn't stored. func TestApp_TokenAuthenticatesAndSecretIsNotStored(t *testing.T) { database := setupTestDB(t) svc := newTestService(database) @@ -82,7 +72,7 @@ func TestApp_TokenAuthenticatesAndSecretIsNotStored(t *testing.T) { if err != nil { t.Fatalf("resolve: %v", err) } - if resolved.ID != app.ID || resolved.Mode != models.AppDelegated || !slices.Equal(resolved.Privileges, []models.PrivilegeKey{testAppPrivilege}) { + if resolved.ID != app.ID || !slices.Equal(resolved.Privileges, []models.PrivilegeKey{testAppPrivilege}) { t.Fatalf("app = %+v", resolved) } _, secret, _ := strings.Cut(token, ".") @@ -138,20 +128,20 @@ func TestApp_CreateRefusesDuplicateKeyAndName(t *testing.T) { {"test-gateway", "Another Gateway"}, {"another-gateway", "Test Gateway"}, } { - if _, _, err := svc.CreateApp(ctx(), app.key, app.name, "", models.AppDelegated, nil, adminID); !errors.Is(err, ErrAlreadyExists) { + if _, _, err := svc.CreateApp(ctx(), app.key, app.name, "", testAppPrivileges(), 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. +// Make sure an app key that would break the token is refused. func TestApp_CreateRefusesBadAppKey(t *testing.T) { database := setupTestDB(t) svc := newTestService(database) adminID := seedAppAdmin(t, database) for _, key := range []string{"has.dot", "has:colon", "Upper", ""} { - if _, _, err := svc.CreateApp(ctx(), key, "Test Gateway", "", models.AppDelegated, nil, adminID); !errors.Is(err, ErrInvalidInput) { + if _, _, err := svc.CreateApp(ctx(), key, "Test Gateway", "", testAppPrivileges(), adminID); !errors.Is(err, ErrInvalidInput) { t.Errorf("%q: %v", key, err) } } @@ -197,131 +187,36 @@ func TestApp_DisabledAppIsRefused(t *testing.T) { } } -// createTestApp tries to create an app with the given mode and privileges. -func createTestApp(t *testing.T, mode models.AppMode, privileges ...models.PrivilegeKey) error { +// createTestApp tries to create an app with the given privileges. +func createTestApp(t *testing.T, privileges ...models.PrivilegeKey) error { t.Helper() database := setupTestDB(t) svc := newTestService(database) - registerTestAppPrivilege() - _, _, err := svc.CreateApp(ctx(), "test-gateway", "Test Gateway", "", mode, privileges, seedAppAdmin(t, database)) + _, _, err := svc.CreateApp(ctx(), "test-gateway", "Test Gateway", "", privileges, seedAppAdmin(t, database)) return err } // Make sure an app can't be given a privilege that isn't allowed for apps, such as managing users. func TestApp_CreateRefusesPrivilegeNotAllowedForApps(t *testing.T) { - if err := createTestApp(t, models.AppDelegated, models.UsersWrite); !errors.Is(err, ErrInvalidInput) { + if err := createTestApp(t, models.UsersWrite); !errors.Is(err, ErrInvalidInput) { t.Fatalf("got %v", err) } } -// Make sure a service app needs at least one privilege, since without one it can't call anything. -func TestApp_CreateRefusesServiceAppWithoutPrivileges(t *testing.T) { - if err := createTestApp(t, models.AppService); !errors.Is(err, ErrInvalidInput) { +// Make sure an app needs at least one privilege, since without one it can't call anything. +func TestApp_CreateRefusesAppWithoutPrivileges(t *testing.T) { + if err := createTestApp(t); !errors.Is(err, ErrInvalidInput) { t.Fatalf("got %v", err) } } -// Make sure an app can't be created with a mode other than service or delegated. -func TestApp_CreateRefusesUnknownMode(t *testing.T) { - if err := createTestApp(t, "OTHER", testAppPrivilege); !errors.Is(err, ErrInvalidInput) { - t.Fatalf("got %v", err) - } -} - -// Make sure a user can allow an app and remove it again. -func TestApp_UserCanAuthorizeAndRemove(t *testing.T) { - database := setupTestDB(t) - svc := newTestService(database) - app, _ := newTestApp(t, svc, seedAppAdmin(t, database)) - userID := seedUser(t, database, "[email protected]") - - if err := svc.AuthorizeApp(ctx(), app.ID, userID); err != nil { - t.Fatal(err) - } - if authorized, err := svc.IsAppAuthorized(ctx(), app.ID, userID); err != nil || !authorized { - t.Fatalf("after allow: %v %v", authorized, err) - } - if err := svc.RemoveAppAuthorization(ctx(), app.ID, userID); err != nil { - t.Fatal(err) - } - if authorized, err := svc.IsAppAuthorized(ctx(), app.ID, userID); err != nil || authorized { - t.Fatalf("after remove: %v %v", authorized, err) - } -} - -// Make sure the member list only shows active delegated apps. -func TestApp_AuthorizationListShowsOnlyActiveDelegatedApps(t *testing.T) { - database := setupTestDB(t) - svc := newTestService(database) - adminID := seedAppAdmin(t, database) - app, _ := newTestApp(t, svc, adminID) - newServiceApp(t, svc, adminID) - userID := seedUser(t, database, "[email protected]") - if err := svc.AuthorizeApp(ctx(), app.ID, userID); err != nil { - t.Fatal(err) - } - - listed, err := svc.ListAppAuthorizations(ctx(), userID) - if err != nil || len(listed) != 1 || listed[0].App.ID != app.ID || !listed[0].Authorized { - t.Fatalf("listed %+v, err %v", listed, err) - } - if _, err := svc.DisableApp(ctx(), app.ID, adminID); err != nil { - t.Fatal(err) - } - if listed, err := svc.ListAppAuthorizations(ctx(), userID); err != nil || len(listed) != 0 { - t.Fatalf("disabled app listed %+v, err %v", listed, err) - } - if authorized, err := svc.IsAppAuthorized(ctx(), app.ID, userID); err != nil || !authorized { - t.Fatalf("allow lost when disabled: %v %v", authorized, err) - } -} - -// Make sure a user's allowed apps move to the surviving user when two users are merged. -func TestApp_AuthorizationMovesOnUserMerge(t *testing.T) { - database := setupTestDB(t) - svc := newTestService(database) - app, _ := newTestApp(t, svc, seedAppAdmin(t, database)) - retiring := seedUser(t, database, "[email protected]") - survivor := seedUser(t, database, "[email protected]") - if err := svc.AuthorizeApp(ctx(), app.ID, retiring); err != nil { - t.Fatal(err) - } - - if _, err := svc.MergeUsers(ctx(), survivor, retiring); err != nil { - t.Fatal(err) - } - - if authorized, err := svc.IsAppAuthorized(ctx(), app.ID, survivor); err != nil || !authorized { - t.Fatalf("survivor: %v %v", authorized, err) - } -} - -// Make sure a service app or a disabled app can't be allowed. -func TestApp_CannotAuthorizeAppOutsideTheList(t *testing.T) { - database := setupTestDB(t) - svc := newTestService(database) - adminID := seedAppAdmin(t, database) - disabled, _ := newTestApp(t, svc, adminID) - if _, err := svc.DisableApp(ctx(), disabled.ID, adminID); err != nil { - t.Fatal(err) - } - service := newServiceApp(t, svc, adminID) - userID := seedUser(t, database, "[email protected]") - - for _, appID := range []string{disabled.ID, service.ID} { - if err := svc.AuthorizeApp(ctx(), appID, userID); !errors.Is(err, ErrInvalidInput) { - t.Errorf("%s: got %v", appID, 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) userID := seedUser(t, database, "[email protected]") - if _, _, err := svc.CreateApp(ctx(), "test-gateway", "Test Gateway", "", models.AppDelegated, nil, userID); err == nil { + if _, _, err := svc.CreateApp(ctx(), "test-gateway", "Test Gateway", "", testAppPrivileges(), userID); err == nil { t.Fatal("created an app without core:apps:manage") } } @@ -347,14 +242,14 @@ func TestApp_AdminRoleCannotManageApps(t *testing.T) { } } -// Make sure a change made through an app records the app in the audit trail, next to the user. +// Make sure a change made through an app records the app in the audit trail. func TestApp_AuditRecordsTheApp(t *testing.T) { database := setupTestDB(t) svc := newTestService(database) adminID := seedAppAdmin(t, database) app, _ := newTestApp(t, svc, adminID) - viaApp := identity.WithCaller(ctx(), &identity.Caller{UserID: adminID, AppID: app.ID, AppKey: "gateway"}) + viaApp := identity.WithCaller(ctx(), &identity.Caller{AppID: app.ID, AppKey: "gateway"}) if _, err := svc.DisableApp(viaApp, app.ID, adminID); err != nil { t.Fatal(err) } @@ -380,16 +275,12 @@ func TestApp_DeleteNeedsTheAppDisabled(t *testing.T) { } } -// Make sure a deleted app can never be used or changed again and loses every user's authorizations. +// Make sure a deleted app can never be used or changed again. func TestApp_DeletedAppCannotBeUsedAgain(t *testing.T) { database := setupTestDB(t) svc := newTestService(database) adminID := seedAppAdmin(t, database) app, token := newTestApp(t, svc, adminID) - userID := seedUser(t, database, "[email protected]") - if err := svc.AuthorizeApp(ctx(), app.ID, userID); err != nil { - t.Fatal(err) - } if _, err := svc.DisableApp(ctx(), app.ID, adminID); err != nil { t.Fatal(err) } @@ -407,16 +298,13 @@ func TestApp_DeletedAppCannotBeUsedAgain(t *testing.T) { if _, _, err := svc.IssueAppSecret(ctx(), app.ID, adminID); !errors.Is(err, ErrNotFound) { t.Errorf("new secret: %v", err) } - if authorized, err := svc.IsAppAuthorized(ctx(), app.ID, userID); err != nil || authorized { - t.Errorf("allow kept: %v %v", authorized, err) - } if apps, err := svc.ListApps(ctx()); err != nil || len(apps) != 0 { t.Errorf("still listed: %v %v", apps, err) } } // Make sure a deleted app's key is never given to another app, so older records that store the key, -// such as certificates, keep pointing at the right app. Its name is free to use again. +// such as audit rows, keep pointing at the right app. Its name is free to use again. func TestApp_DeletedAppKeepsItsKey(t *testing.T) { database := setupTestDB(t) svc := newTestService(database) @@ -429,14 +317,10 @@ func TestApp_DeletedAppKeepsItsKey(t *testing.T) { t.Fatal(err) } - if _, _, err := svc.CreateApp(ctx(), app.Key, "Another Gateway", "", models.AppDelegated, nil, adminID); !errors.Is(err, ErrAlreadyExists) { + if _, _, err := svc.CreateApp(ctx(), app.Key, "Another Gateway", "", testAppPrivileges(), adminID); !errors.Is(err, ErrAlreadyExists) { t.Errorf("same key: %v", err) } - if _, _, err := svc.CreateApp(ctx(), "new-gateway", app.Name, "", models.AppDelegated, nil, adminID); err != nil { + if _, _, err := svc.CreateApp(ctx(), "new-gateway", app.Name, "", testAppPrivileges(), adminID); err != nil { t.Errorf("same name: %v", err) } - names, err := svc.ListAppNames(ctx()) - if err != nil || !slices.ContainsFunc(names, func(a models.App) bool { return a.Key == app.Key && a.Name == app.Name }) { - t.Errorf("name of the deleted app missing: %v %v", names, err) - } } diff --git a/pkg/service/interface.go b/pkg/service/interface.go index 810537be4..cf1627b94 100644 --- a/pkg/service/interface.go +++ b/pkg/service/interface.go @@ -326,20 +326,14 @@ type CoreService interface { type AppService interface { ListApps(ctx context.Context) ([]models.App, error) - ListAppNames(ctx context.Context) ([]models.App, error) GetApp(ctx context.Context, id string) (*models.App, error) - CountAppAuthorizations(ctx context.Context, appID string) (int, error) DeleteApp(ctx context.Context, id, actorID string) error - CreateApp(ctx context.Context, key, name, description string, mode models.AppMode, privileges []models.PrivilegeKey, actorID string) (*models.App, string, error) + CreateApp(ctx context.Context, key, name, description string, privileges []models.PrivilegeKey, 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) (*models.App, error) - ListAppAuthorizations(ctx context.Context, userID string) ([]AppAuthorization, error) - AuthorizeApp(ctx context.Context, appID, userID string) error - RemoveAppAuthorization(ctx context.Context, appID, userID string) error - IsAppAuthorized(ctx context.Context, appID, userID string) (bool, error) } // Compile-time assertion that *Service satisfies the aggregate CoreService. diff --git a/pkg/service/mock.go b/pkg/service/mock.go index c552f6f69..4871aa1e8 100644 --- a/pkg/service/mock.go +++ b/pkg/service/mock.go @@ -34,9 +34,6 @@ var _ CoreService = &CoreServiceMock{} // AttachResourceToAllocationFunc: func(ctx context.Context, allocationID string, resourceID string, resourceAmount int64, resourceTime int64) (*models.ComputeAllocationResourceMapping, error) { // panic("mock out the AttachResourceToAllocation method") // }, -// AuthorizeAppFunc: func(ctx context.Context, appID string, userID string) error { -// panic("mock out the AuthorizeApp method") -// }, // BootstrapSuperAdminFunc: func(ctx context.Context, email string, source string) error { // panic("mock out the BootstrapSuperAdmin method") // }, @@ -46,10 +43,7 @@ var _ CoreService = &CoreServiceMock{} // CompleteOnboardingFunc: func(ctx context.Context, claims *identity.Claims, in OnboardingInput) (*models.User, error) { // panic("mock out the CompleteOnboarding method") // }, -// CountAppAuthorizationsFunc: func(ctx context.Context, appID string) (int, error) { -// panic("mock out the CountAppAuthorizations method") -// }, -// CreateAppFunc: func(ctx context.Context, key string, name string, description string, mode models.AppMode, privileges []models.PrivilegeKey, actorID string) (*models.App, string, error) { +// CreateAppFunc: func(ctx context.Context, key string, name string, description string, privileges []models.PrivilegeKey, actorID string) (*models.App, string, error) { // panic("mock out the CreateApp method") // }, // CreateAuditEventFunc: func(ctx context.Context, e *models.AuditEvent) (*models.AuditEvent, error) { @@ -298,9 +292,6 @@ var _ CoreService = &CoreServiceMock{} // HasPrivilegeFunc: func(ctx context.Context, userID string, privilege models.PrivilegeKey) (bool, error) { // panic("mock out the HasPrivilege method") // }, -// IsAppAuthorizedFunc: func(ctx context.Context, appID string, userID string) (bool, error) { -// panic("mock out the IsAppAuthorized method") -// }, // IsProjectParticipantFunc: func(ctx context.Context, projectID string, userID string) (bool, error) { // panic("mock out the IsProjectParticipant method") // }, @@ -319,12 +310,6 @@ var _ CoreService = &CoreServiceMock{} // ListAllocationsForUserFunc: func(ctx context.Context, userID string) ([]models.ComputeAllocationMembership, error) { // panic("mock out the ListAllocationsForUser method") // }, -// ListAppAuthorizationsFunc: func(ctx context.Context, userID string) ([]AppAuthorization, error) { -// panic("mock out the ListAppAuthorizations method") -// }, -// ListAppNamesFunc: func(ctx context.Context) ([]models.App, error) { -// panic("mock out the ListAppNames method") -// }, // ListAppsFunc: func(ctx context.Context) ([]models.App, error) { // panic("mock out the ListApps method") // }, @@ -448,9 +433,6 @@ var _ CoreService = &CoreServiceMock{} // PublishUserAgreementFunc: func(ctx context.Context, id string, actorID string) (*models.UserAgreement, error) { // panic("mock out the PublishUserAgreement method") // }, -// RemoveAppAuthorizationFunc: func(ctx context.Context, appID string, userID string) error { -// panic("mock out the RemoveAppAuthorization method") -// }, // RemovePrivilegeFromRoleFunc: func(ctx context.Context, roleID string, privilege models.PrivilegeKey, actorID string) error { // panic("mock out the RemovePrivilegeFromRole method") // }, @@ -551,9 +533,6 @@ type CoreServiceMock struct { // AttachResourceToAllocationFunc mocks the AttachResourceToAllocation method. AttachResourceToAllocationFunc func(ctx context.Context, allocationID string, resourceID string, resourceAmount int64, resourceTime int64) (*models.ComputeAllocationResourceMapping, error) - // AuthorizeAppFunc mocks the AuthorizeApp method. - AuthorizeAppFunc func(ctx context.Context, appID string, userID string) error - // BootstrapSuperAdminFunc mocks the BootstrapSuperAdmin method. BootstrapSuperAdminFunc func(ctx context.Context, email string, source string) error @@ -563,11 +542,8 @@ type CoreServiceMock struct { // CompleteOnboardingFunc mocks the CompleteOnboarding method. CompleteOnboardingFunc func(ctx context.Context, claims *identity.Claims, in OnboardingInput) (*models.User, error) - // CountAppAuthorizationsFunc mocks the CountAppAuthorizations method. - CountAppAuthorizationsFunc func(ctx context.Context, appID string) (int, error) - // CreateAppFunc mocks the CreateApp method. - CreateAppFunc func(ctx context.Context, key string, name string, description string, mode models.AppMode, privileges []models.PrivilegeKey, actorID string) (*models.App, string, error) + CreateAppFunc func(ctx context.Context, key string, name string, description string, privileges []models.PrivilegeKey, actorID string) (*models.App, string, error) // CreateAuditEventFunc mocks the CreateAuditEvent method. CreateAuditEventFunc func(ctx context.Context, e *models.AuditEvent) (*models.AuditEvent, error) @@ -815,9 +791,6 @@ type CoreServiceMock struct { // HasPrivilegeFunc mocks the HasPrivilege method. HasPrivilegeFunc func(ctx context.Context, userID string, privilege models.PrivilegeKey) (bool, error) - // IsAppAuthorizedFunc mocks the IsAppAuthorized method. - IsAppAuthorizedFunc func(ctx context.Context, appID string, userID string) (bool, error) - // IsProjectParticipantFunc mocks the IsProjectParticipant method. IsProjectParticipantFunc func(ctx context.Context, projectID string, userID string) (bool, error) @@ -836,12 +809,6 @@ type CoreServiceMock struct { // ListAllocationsForUserFunc mocks the ListAllocationsForUser method. ListAllocationsForUserFunc func(ctx context.Context, userID string) ([]models.ComputeAllocationMembership, error) - // ListAppAuthorizationsFunc mocks the ListAppAuthorizations method. - ListAppAuthorizationsFunc func(ctx context.Context, userID string) ([]AppAuthorization, error) - - // ListAppNamesFunc mocks the ListAppNames method. - ListAppNamesFunc func(ctx context.Context) ([]models.App, error) - // ListAppsFunc mocks the ListApps method. ListAppsFunc func(ctx context.Context) ([]models.App, error) @@ -965,9 +932,6 @@ type CoreServiceMock struct { // PublishUserAgreementFunc mocks the PublishUserAgreement method. PublishUserAgreementFunc func(ctx context.Context, id string, actorID string) (*models.UserAgreement, error) - // RemoveAppAuthorizationFunc mocks the RemoveAppAuthorization method. - RemoveAppAuthorizationFunc func(ctx context.Context, appID string, userID string) error - // RemovePrivilegeFromRoleFunc mocks the RemovePrivilegeFromRole method. RemovePrivilegeFromRoleFunc func(ctx context.Context, roleID string, privilege models.PrivilegeKey, actorID string) error @@ -1093,15 +1057,6 @@ type CoreServiceMock struct { // ResourceTime is the resourceTime argument value. ResourceTime int64 } - // AuthorizeApp holds details about calls to the AuthorizeApp method. - AuthorizeApp []struct { - // Ctx is the ctx argument value. - Ctx context.Context - // AppID is the appID argument value. - AppID string - // UserID is the userID argument value. - UserID string - } // BootstrapSuperAdmin holds details about calls to the BootstrapSuperAdmin method. BootstrapSuperAdmin []struct { // Ctx is the ctx argument value. @@ -1129,13 +1084,6 @@ type CoreServiceMock struct { // In is the in argument value. In OnboardingInput } - // CountAppAuthorizations holds details about calls to the CountAppAuthorizations method. - CountAppAuthorizations []struct { - // Ctx is the ctx argument value. - Ctx context.Context - // AppID is the appID argument value. - AppID string - } // CreateApp holds details about calls to the CreateApp method. CreateApp []struct { // Ctx is the ctx argument value. @@ -1146,8 +1094,6 @@ type CoreServiceMock struct { Name string // Description is the description argument value. Description string - // Mode is the mode argument value. - Mode models.AppMode // Privileges is the privileges argument value. Privileges []models.PrivilegeKey // ActorID is the actorID argument value. @@ -1781,15 +1727,6 @@ type CoreServiceMock struct { // Privilege is the privilege argument value. Privilege models.PrivilegeKey } - // IsAppAuthorized holds details about calls to the IsAppAuthorized method. - IsAppAuthorized []struct { - // Ctx is the ctx argument value. - Ctx context.Context - // AppID is the appID argument value. - AppID string - // UserID is the userID argument value. - UserID string - } // IsProjectParticipant holds details about calls to the IsProjectParticipant method. IsProjectParticipant []struct { // Ctx is the ctx argument value. @@ -1834,18 +1771,6 @@ type CoreServiceMock struct { // UserID is the userID argument value. UserID string } - // ListAppAuthorizations holds details about calls to the ListAppAuthorizations method. - ListAppAuthorizations []struct { - // Ctx is the ctx argument value. - Ctx context.Context - // UserID is the userID argument value. - UserID string - } - // ListAppNames holds details about calls to the ListAppNames method. - ListAppNames []struct { - // Ctx is the ctx argument value. - Ctx context.Context - } // ListApps holds details about calls to the ListApps method. ListApps []struct { // Ctx is the ctx argument value. @@ -2131,15 +2056,6 @@ type CoreServiceMock struct { // ActorID is the actorID argument value. ActorID string } - // RemoveAppAuthorization holds details about calls to the RemoveAppAuthorization method. - RemoveAppAuthorization []struct { - // Ctx is the ctx argument value. - Ctx context.Context - // AppID is the appID argument value. - AppID string - // UserID is the userID argument value. - UserID string - } // RemovePrivilegeFromRole holds details about calls to the RemovePrivilegeFromRole method. RemovePrivilegeFromRole []struct { // Ctx is the ctx argument value. @@ -2382,11 +2298,9 @@ type CoreServiceMock struct { lockAddPrivilegeToRole sync.RWMutex lockAllocationRoleForUser sync.RWMutex lockAttachResourceToAllocation sync.RWMutex - lockAuthorizeApp sync.RWMutex lockBootstrapSuperAdmin sync.RWMutex lockCheckOnboardingUsername sync.RWMutex lockCompleteOnboarding sync.RWMutex - lockCountAppAuthorizations sync.RWMutex lockCreateApp sync.RWMutex lockCreateAuditEvent sync.RWMutex lockCreateComputeAllocation sync.RWMutex @@ -2470,15 +2384,12 @@ type CoreServiceMock struct { lockGrantPrivilege sync.RWMutex lockGrantRoleToUser sync.RWMutex lockHasPrivilege sync.RWMutex - lockIsAppAuthorized sync.RWMutex lockIsProjectParticipant sync.RWMutex lockIssueAppSecret sync.RWMutex lockLatestUsageTimeForCluster sync.RWMutex lockListAllAuditEvents sync.RWMutex lockListAllocationsForResource sync.RWMutex lockListAllocationsForUser sync.RWMutex - lockListAppAuthorizations sync.RWMutex - lockListAppNames sync.RWMutex lockListApps sync.RWMutex lockListAuditEventsByEntity sync.RWMutex lockListAuditEventsByEventType sync.RWMutex @@ -2520,7 +2431,6 @@ type CoreServiceMock struct { lockPendingUserAgreements sync.RWMutex lockPrivilegeCatalog sync.RWMutex lockPublishUserAgreement sync.RWMutex - lockRemoveAppAuthorization sync.RWMutex lockRemovePrivilegeFromRole sync.RWMutex lockRemoveUserAgreement sync.RWMutex lockResolveApp sync.RWMutex @@ -2722,46 +2632,6 @@ func (mock *CoreServiceMock) AttachResourceToAllocationCalls() []struct { return calls } -// AuthorizeApp calls AuthorizeAppFunc. -func (mock *CoreServiceMock) AuthorizeApp(ctx context.Context, appID string, userID string) error { - if mock.AuthorizeAppFunc == nil { - panic("CoreServiceMock.AuthorizeAppFunc: method is nil but CoreService.AuthorizeApp was just called") - } - callInfo := struct { - Ctx context.Context - AppID string - UserID string - }{ - Ctx: ctx, - AppID: appID, - UserID: userID, - } - mock.lockAuthorizeApp.Lock() - mock.calls.AuthorizeApp = append(mock.calls.AuthorizeApp, callInfo) - mock.lockAuthorizeApp.Unlock() - return mock.AuthorizeAppFunc(ctx, appID, userID) -} - -// AuthorizeAppCalls gets all the calls that were made to AuthorizeApp. -// Check the length with: -// -// len(mockedCoreService.AuthorizeAppCalls()) -func (mock *CoreServiceMock) AuthorizeAppCalls() []struct { - Ctx context.Context - AppID string - UserID string -} { - var calls []struct { - Ctx context.Context - AppID string - UserID string - } - mock.lockAuthorizeApp.RLock() - calls = mock.calls.AuthorizeApp - mock.lockAuthorizeApp.RUnlock() - return calls -} - // BootstrapSuperAdmin calls BootstrapSuperAdminFunc. func (mock *CoreServiceMock) BootstrapSuperAdmin(ctx context.Context, email string, source string) error { if mock.BootstrapSuperAdminFunc == nil { @@ -2882,44 +2752,8 @@ func (mock *CoreServiceMock) CompleteOnboardingCalls() []struct { return calls } -// CountAppAuthorizations calls CountAppAuthorizationsFunc. -func (mock *CoreServiceMock) CountAppAuthorizations(ctx context.Context, appID string) (int, error) { - if mock.CountAppAuthorizationsFunc == nil { - panic("CoreServiceMock.CountAppAuthorizationsFunc: method is nil but CoreService.CountAppAuthorizations was just called") - } - callInfo := struct { - Ctx context.Context - AppID string - }{ - Ctx: ctx, - AppID: appID, - } - mock.lockCountAppAuthorizations.Lock() - mock.calls.CountAppAuthorizations = append(mock.calls.CountAppAuthorizations, callInfo) - mock.lockCountAppAuthorizations.Unlock() - return mock.CountAppAuthorizationsFunc(ctx, appID) -} - -// CountAppAuthorizationsCalls gets all the calls that were made to CountAppAuthorizations. -// Check the length with: -// -// len(mockedCoreService.CountAppAuthorizationsCalls()) -func (mock *CoreServiceMock) CountAppAuthorizationsCalls() []struct { - Ctx context.Context - AppID string -} { - var calls []struct { - Ctx context.Context - AppID string - } - mock.lockCountAppAuthorizations.RLock() - calls = mock.calls.CountAppAuthorizations - mock.lockCountAppAuthorizations.RUnlock() - return calls -} - // CreateApp calls CreateAppFunc. -func (mock *CoreServiceMock) CreateApp(ctx context.Context, key string, name string, description string, mode models.AppMode, privileges []models.PrivilegeKey, actorID string) (*models.App, string, error) { +func (mock *CoreServiceMock) CreateApp(ctx context.Context, key string, name string, description string, privileges []models.PrivilegeKey, actorID string) (*models.App, string, error) { if mock.CreateAppFunc == nil { panic("CoreServiceMock.CreateAppFunc: method is nil but CoreService.CreateApp was just called") } @@ -2928,7 +2762,6 @@ func (mock *CoreServiceMock) CreateApp(ctx context.Context, key string, name str Key string Name string Description string - Mode models.AppMode Privileges []models.PrivilegeKey ActorID string }{ @@ -2936,14 +2769,13 @@ func (mock *CoreServiceMock) CreateApp(ctx context.Context, key string, name str Key: key, Name: name, Description: description, - Mode: mode, Privileges: privileges, ActorID: actorID, } mock.lockCreateApp.Lock() mock.calls.CreateApp = append(mock.calls.CreateApp, callInfo) mock.lockCreateApp.Unlock() - return mock.CreateAppFunc(ctx, key, name, description, mode, privileges, actorID) + return mock.CreateAppFunc(ctx, key, name, description, privileges, actorID) } // CreateAppCalls gets all the calls that were made to CreateApp. @@ -2955,7 +2787,6 @@ func (mock *CoreServiceMock) CreateAppCalls() []struct { Key string Name string Description string - Mode models.AppMode Privileges []models.PrivilegeKey ActorID string } { @@ -2964,7 +2795,6 @@ func (mock *CoreServiceMock) CreateAppCalls() []struct { Key string Name string Description string - Mode models.AppMode Privileges []models.PrivilegeKey ActorID string } @@ -6034,46 +5864,6 @@ func (mock *CoreServiceMock) HasPrivilegeCalls() []struct { return calls } -// IsAppAuthorized calls IsAppAuthorizedFunc. -func (mock *CoreServiceMock) IsAppAuthorized(ctx context.Context, appID string, userID string) (bool, error) { - if mock.IsAppAuthorizedFunc == nil { - panic("CoreServiceMock.IsAppAuthorizedFunc: method is nil but CoreService.IsAppAuthorized was just called") - } - callInfo := struct { - Ctx context.Context - AppID string - UserID string - }{ - Ctx: ctx, - AppID: appID, - UserID: userID, - } - mock.lockIsAppAuthorized.Lock() - mock.calls.IsAppAuthorized = append(mock.calls.IsAppAuthorized, callInfo) - mock.lockIsAppAuthorized.Unlock() - return mock.IsAppAuthorizedFunc(ctx, appID, userID) -} - -// IsAppAuthorizedCalls gets all the calls that were made to IsAppAuthorized. -// Check the length with: -// -// len(mockedCoreService.IsAppAuthorizedCalls()) -func (mock *CoreServiceMock) IsAppAuthorizedCalls() []struct { - Ctx context.Context - AppID string - UserID string -} { - var calls []struct { - Ctx context.Context - AppID string - UserID string - } - mock.lockIsAppAuthorized.RLock() - calls = mock.calls.IsAppAuthorized - mock.lockIsAppAuthorized.RUnlock() - return calls -} - // IsProjectParticipant calls IsProjectParticipantFunc. func (mock *CoreServiceMock) IsProjectParticipant(ctx context.Context, projectID string, userID string) (bool, error) { if mock.IsProjectParticipantFunc == nil { @@ -6294,74 +6084,6 @@ func (mock *CoreServiceMock) ListAllocationsForUserCalls() []struct { return calls } -// ListAppAuthorizations calls ListAppAuthorizationsFunc. -func (mock *CoreServiceMock) ListAppAuthorizations(ctx context.Context, userID string) ([]AppAuthorization, error) { - if mock.ListAppAuthorizationsFunc == nil { - panic("CoreServiceMock.ListAppAuthorizationsFunc: method is nil but CoreService.ListAppAuthorizations was just called") - } - callInfo := struct { - Ctx context.Context - UserID string - }{ - Ctx: ctx, - UserID: userID, - } - mock.lockListAppAuthorizations.Lock() - mock.calls.ListAppAuthorizations = append(mock.calls.ListAppAuthorizations, callInfo) - mock.lockListAppAuthorizations.Unlock() - return mock.ListAppAuthorizationsFunc(ctx, userID) -} - -// ListAppAuthorizationsCalls gets all the calls that were made to ListAppAuthorizations. -// Check the length with: -// -// len(mockedCoreService.ListAppAuthorizationsCalls()) -func (mock *CoreServiceMock) ListAppAuthorizationsCalls() []struct { - Ctx context.Context - UserID string -} { - var calls []struct { - Ctx context.Context - UserID string - } - mock.lockListAppAuthorizations.RLock() - calls = mock.calls.ListAppAuthorizations - mock.lockListAppAuthorizations.RUnlock() - return calls -} - -// ListAppNames calls ListAppNamesFunc. -func (mock *CoreServiceMock) ListAppNames(ctx context.Context) ([]models.App, error) { - if mock.ListAppNamesFunc == nil { - panic("CoreServiceMock.ListAppNamesFunc: method is nil but CoreService.ListAppNames was just called") - } - callInfo := struct { - Ctx context.Context - }{ - Ctx: ctx, - } - mock.lockListAppNames.Lock() - mock.calls.ListAppNames = append(mock.calls.ListAppNames, callInfo) - mock.lockListAppNames.Unlock() - return mock.ListAppNamesFunc(ctx) -} - -// ListAppNamesCalls gets all the calls that were made to ListAppNames. -// Check the length with: -// -// len(mockedCoreService.ListAppNamesCalls()) -func (mock *CoreServiceMock) ListAppNamesCalls() []struct { - Ctx context.Context -} { - var calls []struct { - Ctx context.Context - } - mock.lockListAppNames.RLock() - calls = mock.calls.ListAppNames - mock.lockListAppNames.RUnlock() - return calls -} - // ListApps calls ListAppsFunc. func (mock *CoreServiceMock) ListApps(ctx context.Context) ([]models.App, error) { if mock.ListAppsFunc == nil { @@ -7833,46 +7555,6 @@ func (mock *CoreServiceMock) PublishUserAgreementCalls() []struct { return calls } -// RemoveAppAuthorization calls RemoveAppAuthorizationFunc. -func (mock *CoreServiceMock) RemoveAppAuthorization(ctx context.Context, appID string, userID string) error { - if mock.RemoveAppAuthorizationFunc == nil { - panic("CoreServiceMock.RemoveAppAuthorizationFunc: method is nil but CoreService.RemoveAppAuthorization was just called") - } - callInfo := struct { - Ctx context.Context - AppID string - UserID string - }{ - Ctx: ctx, - AppID: appID, - UserID: userID, - } - mock.lockRemoveAppAuthorization.Lock() - mock.calls.RemoveAppAuthorization = append(mock.calls.RemoveAppAuthorization, callInfo) - mock.lockRemoveAppAuthorization.Unlock() - return mock.RemoveAppAuthorizationFunc(ctx, appID, userID) -} - -// RemoveAppAuthorizationCalls gets all the calls that were made to RemoveAppAuthorization. -// Check the length with: -// -// len(mockedCoreService.RemoveAppAuthorizationCalls()) -func (mock *CoreServiceMock) RemoveAppAuthorizationCalls() []struct { - Ctx context.Context - AppID string - UserID string -} { - var calls []struct { - Ctx context.Context - AppID string - UserID string - } - mock.lockRemoveAppAuthorization.RLock() - calls = mock.calls.RemoveAppAuthorization - mock.lockRemoveAppAuthorization.RUnlock() - return calls -} - // RemovePrivilegeFromRole calls RemovePrivilegeFromRoleFunc. func (mock *CoreServiceMock) RemovePrivilegeFromRole(ctx context.Context, roleID string, privilege models.PrivilegeKey, actorID string) error { if mock.RemovePrivilegeFromRoleFunc == nil { diff --git a/pkg/service/user_merge.go b/pkg/service/user_merge.go index 91b163d71..62332336e 100644 --- a/pkg/service/user_merge.go +++ b/pkg/service/user_merge.go @@ -129,9 +129,6 @@ func (s *Service) MergeUsersTx(ctx context.Context, tx *sql.Tx, survivingID, ret if err := s.projMemberships.ReassignUser(ctx, tx, retiringID, survivingID); err != nil { return fmt.Errorf("reassign project memberships: %w", err) } - if err := s.apps.ReassignGrants(ctx, tx, retiringID, survivingID); err != nil { - return fmt.Errorf("reassign app grants: %w", err) - } if err := s.users.UpdateStatus(ctx, tx, retiringID, models.UserMerged); err != nil { return err }
