This is an automated email from the ASF dual-hosted git repository. yasithdev pushed a commit to branch temp-account-access in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit 588b480c4506565d903e2ce233c6f921f89f916b Author: Yasith Jayawardana <[email protected]> AuthorDate: Wed Nov 11 02:13:01 2026 -0500 Add temp account access --- .env.example | 3 + CONFIG.md | 6 +- api/core.openapi.yaml | 13 ++ cmd/server/main.go | 1 + config/custos.yaml | 4 + connectors/TempAccount/internal/handlers.go | 164 ++------------------- .../internal/handlers_integration_test.go | 101 +++++++------ connectors/TempAccount/internal/privileges.go | 29 ---- docs/architecture.md | 2 +- docs/privileges.md | 9 +- internal/config/config.go | 9 +- internal/server/privilege.go | 8 + internal/server/privilege_integration_test.go | 3 + pkg/service/cluster_access.go | 84 +++++++++++ pkg/service/cluster_access_integration_test.go | 125 ++++++++++++++++ pkg/service/service.go | 2 + pkg/service/user.go | 5 + web/scripts/gen-api.mts | 2 +- web/scripts/spec-supplement.mts | 54 +------ 19 files changed, 338 insertions(+), 286 deletions(-) diff --git a/.env.example b/.env.example index 10d630f9a..ad4543be9 100644 --- a/.env.example +++ b/.env.example @@ -42,6 +42,9 @@ OIDC_AUDIENCE=custos-api # Shared across connectors that need to know which cluster they belong to. CUSTOS_CLUSTER_ID=00000000-0000-0000-0000-000000000001 +# Cluster login that temporary accounts share. Empty turns temporary access off. +SHARED_LOGIN_USERNAME= + # Grants super_admin to the user with this email on first boot. Idempotent. # Bundled Keycloak: keep the default (matches the seeded realm user). # External OIDC: use your own email. A PENDING super_admin user is created diff --git a/CONFIG.md b/CONFIG.md index 710c2ef91..f67632a02 100644 --- a/CONFIG.md +++ b/CONFIG.md @@ -92,6 +92,9 @@ core: cache_ttl: "30s" users: reserved_usernames: [root, daemon, slurm, ...] + shared_login: + cluster_id: "${CUSTOS_CLUSTER_ID}" + username: "${SHARED_LOGIN_USERNAME}" ``` | Key | Default | Notes | @@ -103,6 +106,7 @@ core: | `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.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. | +| `core.users.shared_login` | empty | `cluster_id` and `username` of the cluster account every temporary (`VIRTUAL`) user logs in as. It is an ordinary approved, provisioned account. Empty → temporary users have no cluster access. | ## Connectors @@ -141,4 +145,4 @@ To add a connector type, follow [docs/contributing/writing-a-connector.md](docs/ ### Temporary accounts and analytics -The `temp-account` and `analytics` connectors take no keys beyond `type` and `enabled`. +The `temp-account` and `analytics` connectors take no keys beyond `type` and `enabled`. What a temporary account can log in as is set by `core.users.shared_login`. diff --git a/api/core.openapi.yaml b/api/core.openapi.yaml index ab6927c7d..d6b33e108 100644 --- a/api/core.openapi.yaml +++ b/api/core.openapi.yaml @@ -123,6 +123,10 @@ definitions: type: object CallerProfileResponse: properties: + cluster_access: + items: + $ref: '#/definitions/ClusterLogin' + type: array cluster_accounts: items: $ref: '#/definitions/CallerClusterAccount' @@ -224,6 +228,15 @@ definitions: user_id: type: string type: object + ClusterLogin: + properties: + compute_cluster_id: + type: string + local_username: + type: string + shared: + type: boolean + type: object ComputeAllocation: properties: compute_cluster_id: diff --git a/cmd/server/main.go b/cmd/server/main.go index 6412c1bfa..1da5896bd 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -154,6 +154,7 @@ func run() error { } svc.SetIdentityCacheTTL(cfg.Core.Auth.CacheTTL) svc.SetReservedUsernames(cfg.Core.Users.ReservedUsernames) + svc.SetSharedLogin(cfg.Core.Users.SharedLogin.ClusterID, cfg.Core.Users.SharedLogin.Username) // identity.Middleware sits in front of the router-backed server, so every // gated route sees a verified caller + privilege set on ctx. diff --git a/config/custos.yaml b/config/custos.yaml index 5aaff2055..ecd5bbb6c 100644 --- a/config/custos.yaml +++ b/config/custos.yaml @@ -27,6 +27,10 @@ core: audience: "${OIDC_AUDIENCE}" cache_ttl: "30s" users: + # The cluster account every temporary (VIRTUAL) user logs in as. Leave the username empty for none. + shared_login: + cluster_id: "${CUSTOS_CLUSTER_ID}" + username: "${SHARED_LOGIN_USERNAME}" # Names a user cannot choose as their cluster login. reserved_usernames: - root diff --git a/connectors/TempAccount/internal/handlers.go b/connectors/TempAccount/internal/handlers.go index 9fd394901..6adc364ad 100644 --- a/connectors/TempAccount/internal/handlers.go +++ b/connectors/TempAccount/internal/handlers.go @@ -39,177 +39,35 @@ func NewHandlers(coreService *service.Service) *Handlers { // RegisterRoutes attaches the TempAccount connector's HTTP endpoints to router. func (h *Handlers) RegisterRoutes(router *identity.Router) { - router.RequirePrivilege("POST /connectors/temp-account/create", AccountsWrite, h.createTempAccount) - router.RequirePrivilege("POST /connectors/temp-account/assign-allocation", AccountsWrite, h.assignAllocationToTempAccount) - router.RequirePrivilege("POST /connectors/temp-account/update-allocation", AccountsWrite, h.updateAllocationToTempAccount) - router.RequirePrivilege("DELETE /connectors/temp-account/remove/{user_id}", AccountsWrite, h.removeTempAccount) - router.RequirePrivilege("GET /connectors/temp-account/membership/{user_id}", AccountsRead, h.getAllocationMembershipForTempUser) router.RequireApp("POST /connectors/temp-account/app/create", AppActionCreateUser, h.createTempAccount) } +// createTempAccount returns the temp account for the email, creating a PENDING +// one when there is none, so a repeat is safe. func (h *Handlers) createTempAccount(w http.ResponseWriter, r *http.Request) { var u models.User if err := common.DecodeJSON(r, &u); err != nil { common.WriteError(w, http.StatusBadRequest, err) return } - if u.Type != models.UserTypeVirtual { common.WriteError(w, http.StatusBadRequest, errors.New("User type must be VIRTUAL")) return } + // Core assigns both. Only a PENDING user can bind a first sign-in. + u.ID, u.Status = "", "" - created, err := h.coreService.CreateUser(r.Context(), &u) - - if err != nil { - common.WriteServiceError(w, err) - return - } - common.WriteJSON(w, http.StatusCreated, created) -} - -func (h *Handlers) removeTempAccount(w http.ResponseWriter, r *http.Request) { - userID := r.PathValue("user_id") - if userID == "" { - common.WriteError(w, http.StatusBadRequest, errors.New("user_id query parameter is required")) - return - } - - user, err := h.coreService.GetUser(r.Context(), userID) - if err != nil { - common.WriteServiceError(w, err) - return - } - if user == nil { - common.WriteError(w, http.StatusNotFound, errors.New("user not found")) - return - } - - if user.Type != models.UserTypeVirtual { - common.WriteError(w, http.StatusBadRequest, errors.New("User type must be VIRTUAL")) - return - } - - // Users are never deleted. Deleting accounts here publishes the cluster delete events. - if _, err := h.coreService.UpdateUserStatus(r.Context(), userID, models.UserInactive); err != nil { - common.WriteServiceError(w, err) - return - } - accounts, err := h.coreService.ListComputeClusterUsersByUser(r.Context(), userID) - if err != nil { - common.WriteServiceError(w, err) - return - } - for _, a := range accounts { - if err := h.coreService.DeleteComputeClusterUser(r.Context(), a.ID); err != nil { - common.WriteServiceError(w, err) - return + status := http.StatusCreated + user, err := h.coreService.CreateUser(r.Context(), &u) + if errors.Is(err, service.ErrAlreadyExists) { + // Only a temp account is handed back. Any other user's record stays private. + if held, lookupErr := h.coreService.GetUserByEmail(r.Context(), u.Email); lookupErr == nil && held.Type == models.UserTypeVirtual { + status, user, err = http.StatusOK, held, nil } } - w.WriteHeader(http.StatusNoContent) -} - -func (h *Handlers) assignAllocationToTempAccount(w http.ResponseWriter, r *http.Request) { - var m models.ComputeAllocationMembership - if err := common.DecodeJSON(r, &m); err != nil { - common.WriteError(w, http.StatusBadRequest, err) - return - } - - if m.UserID == "" || m.ComputeAllocationID == "" { - common.WriteError(w, http.StatusBadRequest, errors.New("UserID and ComputeAllocationID must be provided")) - return - } - - // In future, we may want to check that the user already has a membership to an allocation - // If that's the case, prevent user from getting membershup to multiple allocations, which TempAccount connector doesn't support. - - user, err := h.coreService.GetUser(r.Context(), m.UserID) - - if err != nil { - common.WriteServiceError(w, err) - return - } - - if user.Type != models.UserTypeVirtual { - common.WriteError(w, http.StatusBadRequest, errors.New("User type must be VIRTUAL")) - return - } - - assigned, err := h.coreService.CreateComputeAllocationMembership(r.Context(), &m) - - if err != nil { - common.WriteServiceError(w, err) - return - } - common.WriteJSON(w, http.StatusOK, assigned) -} - -func (h *Handlers) updateAllocationToTempAccount(w http.ResponseWriter, r *http.Request) { - var m models.ComputeAllocationMembership - if err := common.DecodeJSON(r, &m); err != nil { - common.WriteError(w, http.StatusBadRequest, err) - return - } - - existing, err := h.coreService.GetComputeAllocationMembership(r.Context(), m.ID) if err != nil { common.WriteServiceError(w, err) return } - - user, err := h.coreService.GetUser(r.Context(), existing.UserID) - if err != nil { - common.WriteServiceError(w, err) - return - } - - if user.Type != models.UserTypeVirtual { - common.WriteError(w, http.StatusBadRequest, errors.New("User type must be VIRTUAL")) - return - } - - m.UserID = existing.UserID - updated, err := h.coreService.UpdateComputeAllocationMembership(r.Context(), &m) - - if err != nil { - common.WriteServiceError(w, err) - return - } - common.WriteJSON(w, http.StatusOK, updated) -} - -func (h *Handlers) getAllocationMembershipForTempUser(w http.ResponseWriter, r *http.Request) { - userID := r.PathValue("user_id") - if userID == "" { - common.WriteError(w, http.StatusBadRequest, errors.New("user_id query parameter is required")) - return - } - - user, err := h.coreService.GetUser(r.Context(), userID) - if err != nil { - common.WriteServiceError(w, err) - return - } - if user == nil { - common.WriteError(w, http.StatusNotFound, errors.New("user not found")) - return - } - - if user.Type != models.UserTypeVirtual { - common.WriteError(w, http.StatusBadRequest, errors.New("User type must be VIRTUAL")) - return - } - - memberships, err := h.coreService.ListAllocationsForUser(r.Context(), userID) - if err != nil { - common.WriteServiceError(w, err) - return - } - if memberships == nil { - common.WriteError(w, http.StatusNotFound, errors.New("membership not found for user")) - return - } - - common.WriteJSON(w, http.StatusOK, memberships) + common.WriteJSON(w, status, user) } diff --git a/connectors/TempAccount/internal/handlers_integration_test.go b/connectors/TempAccount/internal/handlers_integration_test.go index 0905b90e8..7b35d28a2 100644 --- a/connectors/TempAccount/internal/handlers_integration_test.go +++ b/connectors/TempAccount/internal/handlers_integration_test.go @@ -20,10 +20,11 @@ package internal import ( - "context" + "encoding/json" "net/http" "net/http/httptest" "strings" + "sync" "testing" "github.com/google/uuid" @@ -35,59 +36,77 @@ import ( "github.com/apache/airavata-custos/pkg/service" ) -func TestHandlers_UpdateAllocationKeepsVirtualUser(t *testing.T) { +func newTestHandlers(t *testing.T) (*Handlers, *service.Service) { + t.Helper() database := dbtest.Open(t, dbtest.CoreDSN(t)) - ctx := tracingtest.Context() - bus, err := events.New(ctx, database) + bus, err := events.New(tracingtest.Context(), database) if err != nil { t.Fatal(err) } svc := service.New(database, bus) - org, _ := svc.CreateOrganization(ctx, &models.Organization{Name: "Example University"}) - cluster, _ := svc.CreateComputeCluster(ctx, &models.ComputeCluster{Name: uuid.NewString()}) - virtual, _ := svc.CreateUser(ctx, &models.User{OrganizationID: org.ID, Email: uuid.NewString() + "@example.edu", Type: models.UserTypeVirtual}) - project, _ := svc.CreateProject(ctx, &models.Project{Title: "Example Project", ProjectPIID: virtual.ID}) - alloc, _ := svc.CreateComputeAllocation(ctx, &models.ComputeAllocation{ProjectID: project.ID, Name: "example", ComputeClusterID: cluster.ID}) - m, _ := svc.CreateComputeAllocationMembership(ctx, &models.ComputeAllocationMembership{ComputeAllocationID: alloc.ID, UserID: virtual.ID}) + return NewHandlers(svc), svc +} +func postCreate(h *Handlers, body string) (int, models.User) { rec := httptest.NewRecorder() - NewHandlers(svc).updateAllocationToTempAccount(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"id": "`+m.ID+`", "user_id": "`+uuid.NewString()+`"}`))) - if stored, _ := svc.GetComputeAllocationMembership(ctx, m.ID); rec.Code != http.StatusOK || stored.UserID != virtual.ID { - t.Fatalf("status %d, stored user %s", rec.Code, stored.UserID) - } + h.createTempAccount(rec, httptest.NewRequestWithContext(tracingtest.Context(), http.MethodPost, "/", strings.NewReader(body))) + var u models.User + _ = json.NewDecoder(rec.Body).Decode(&u) + return rec.Code, u } -// Make sure removing a temp account keeps the user INACTIVE and deletes its cluster account. -func TestHandlers_RemoveKeepsUserAndDeletesClusterAccounts(t *testing.T) { - database := dbtest.Open(t, dbtest.CoreDSN(t)) - ctx := tracingtest.Context() - bus, err := events.New(ctx, database) - if err != nil { - t.Fatal(err) +// Make sure a repeated create returns the first user, and that the caller cannot pick the id or the status. +func TestCreateTempAccount_RepeatReturnsTheSameUser(t *testing.T) { + h, svc := newTestHandlers(t) + org, _ := svc.CreateOrganization(tracingtest.Context(), &models.Organization{Name: "Example University"}) + body := `{"id": "chosen", "status": "ACTIVE", "type": "VIRTUAL", "organization_id": "` + org.ID + `", "email": "` + uuid.NewString() + `@example.edu"}` + + code, first := postCreate(h, body) + if code != http.StatusCreated || first.ID == "chosen" || first.Status != models.UserPending || first.Type != models.UserTypeVirtual { + t.Fatalf("first create: status %d, user %+v", code, first) } - bus.SubscribeComputeClusterUserDeleted("test-subscriber", func(context.Context, models.ComputeClusterUser) error { return nil }) - svc := service.New(database, bus) - org, _ := svc.CreateOrganization(ctx, &models.Organization{Name: "Example University"}) - cluster, _ := svc.CreateComputeCluster(ctx, &models.ComputeCluster{Name: uuid.NewString()}) - virtual, _ := svc.CreateUser(ctx, &models.User{OrganizationID: org.ID, Email: uuid.NewString() + "@example.edu", Type: models.UserTypeVirtual}) - account, _ := svc.CreateComputeClusterUser(ctx, &models.ComputeClusterUser{ComputeClusterID: cluster.ID, UserID: virtual.ID, LocalUsername: "temp-" + uuid.NewString()[:8]}) + if code, again := postCreate(h, body); code != http.StatusOK || again.ID != first.ID { + t.Fatalf("repeat create: status %d, user %+v, want 200 and %s", code, again, first.ID) + } + if code, _ := postCreate(h, strings.Replace(body, "VIRTUAL", "CLUSTER_LOCAL", 1)); code != http.StatusBadRequest { + t.Fatalf("non-virtual create: status %d, want 400", code) + } + regular, _ := svc.CreateUser(tracingtest.Context(), &models.User{OrganizationID: org.ID, Email: uuid.NewString() + "@example.edu"}) + if code, got := postCreate(h, strings.Replace(body, first.Email, regular.Email, 1)); code != http.StatusConflict || got.ID != "" { + t.Fatalf("create over a regular user: status %d, user %+v, want 409 and no user", code, got) + } +} - req := httptest.NewRequestWithContext(ctx, http.MethodDelete, "/", nil) - req.SetPathValue("user_id", virtual.ID) - rec := httptest.NewRecorder() - NewHandlers(svc).removeTempAccount(rec, req) +// Make sure simultaneous creates for one email all answer with the one user. +func TestCreateTempAccount_SimultaneousCreatesMakeOneUser(t *testing.T) { + h, svc := newTestHandlers(t) + org, _ := svc.CreateOrganization(tracingtest.Context(), &models.Organization{Name: "Example University"}) + body := `{"type": "VIRTUAL", "organization_id": "` + org.ID + `", "email": "` + uuid.NewString() + `@example.edu"}` - if rec.Code != http.StatusNoContent { - t.Fatalf("status %d: %s", rec.Code, rec.Body) - } - if u, err := svc.GetUser(ctx, virtual.ID); err != nil || u.Status != models.UserInactive { - t.Fatalf("user: got %+v, %v, want INACTIVE", u, err) + const n = 10 + codes, ids := make([]int, n), make([]string, n) + var wg sync.WaitGroup + for i := range n { + wg.Go(func() { + var u models.User + codes[i], u = postCreate(h, body) + ids[i] = u.ID + }) } - if accounts, _ := svc.ListComputeClusterUsersByUser(ctx, virtual.ID); len(accounts) != 0 { - t.Fatalf("cluster accounts left: %+v", accounts) + wg.Wait() + + created := 0 + for i := range n { + if codes[i] == http.StatusCreated { + created++ + } else if codes[i] != http.StatusOK { + t.Fatalf("create %d: status %d", i, codes[i]) + } + if ids[i] == "" || ids[i] != ids[0] { + t.Fatalf("create %d: user %q, want %q", i, ids[i], ids[0]) + } } - var deletes int - if err := database.Get(&deletes, "SELECT COUNT(*) FROM events WHERE event_type = $1 AND payload->>'id' = $2", events.ComputeClusterUserDeleteEvent, account.ID); err != nil || deletes != 1 { - t.Fatalf("delete events for the account: got %d, %v, want 1", deletes, err) + if created != 1 { + t.Fatalf("created %d users, want 1", created) } } diff --git a/connectors/TempAccount/internal/privileges.go b/connectors/TempAccount/internal/privileges.go deleted file mode 100644 index 5a4391b28..000000000 --- a/connectors/TempAccount/internal/privileges.go +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package internal - -import "github.com/apache/airavata-custos/pkg/models" - -const ( - AccountsRead models.PrivilegeKey = "temp-account:accounts:read" - AccountsWrite models.PrivilegeKey = "temp-account:accounts:write" -) - -func init() { - models.Register(AccountsRead, AccountsWrite) -} diff --git a/docs/architecture.md b/docs/architecture.md index d6f619bd4..938b93229 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -103,7 +103,7 @@ shutdown the HTTP server gets 15 seconds to finish in-flight requests. The serve | `vast-storage-provisioner` | `connectors/Storage/VAST-Provisioner` | Creates directories, views and quotas on VAST | | `email-notifier` | `connectors/Notification/Email` | Emails users about their cluster account requests | | `analytics` | `connectors/Analytics` | Usage summaries and job lists for allocation participants | -| `temp-account` | `connectors/TempAccount` | Creates temporary accounts and assigns them allocations | +| `temp-account` | `connectors/TempAccount` | Lets an app create temporary accounts | | `signer` | `connectors/Signer` | Decides who may have an SSH certificate and calls the signer to issue and revoke them | `connectors/SLURM/Rest-Client` is the shared `slurmrestd` client library, not a connector. `GET /connectors` lists diff --git a/docs/privileges.md b/docs/privileges.md index 28a131f36..e1df97437 100644 --- a/docs/privileges.md +++ b/docs/privileges.md @@ -38,7 +38,7 @@ A key exists only once it is registered with `models.Register(...)`. Grants and | Segment | Meaning | Examples | |----------|--------------------------------------------------------------------------------------------|-------------------------------------| -| `owner` | The component that defines and checks the key: `core`, or the connector's short name | `core`, `amie`, `temp-account` | +| `owner` | The component that defines and checks the key: `core`, or the connector's short name | `core`, `amie`, `signer` | | `scope` | The resource inside that owner | `clusters`, `packets`, `agreements` | | `action` | The verb: `read` for reads, `write` for mutations, `grant` or `manage` for meta operations | `read`, `write`, `grant`, `manage` | @@ -92,13 +92,6 @@ These routes need a verified caller but no key. | `amie:unmapped:read` | `GET /connectors/amie/unmapped` | | `amie:unmapped:write` | `POST /connectors/amie/unmapped/{id}/link` | -## TempAccount connector (`connectors/TempAccount/internal/privileges.go`) - -| Privilege | Routes it gates | -|-------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `temp-account:accounts:read` | `GET /connectors/temp-account/membership/{user_id}` | -| `temp-account:accounts:write` | `POST /connectors/temp-account/create`<br>`POST /connectors/temp-account/assign-allocation`<br>`POST /connectors/temp-account/update-allocation`<br>`DELETE /connectors/temp-account/remove/{user_id}` | - ## Signer connector (`connectors/Signer/internal/privileges.go`) | Privilege | Routes it gates | diff --git a/internal/config/config.go b/internal/config/config.go index 97a50d80b..f42778fb4 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -49,7 +49,14 @@ type CoreConfig struct { } type UsersConfig struct { - ReservedUsernames []string `yaml:"reserved_usernames"` + ReservedUsernames []string `yaml:"reserved_usernames"` + SharedLogin SharedLoginConfig `yaml:"shared_login"` +} + +// SharedLoginConfig names the cluster account every VIRTUAL user logs in as. +type SharedLoginConfig struct { + ClusterID string `yaml:"cluster_id"` + Username string `yaml:"username"` } type DatabaseConfig struct { diff --git a/internal/server/privilege.go b/internal/server/privilege.go index e6f60cc87..d99b02eef 100644 --- a/internal/server/privilege.go +++ b/internal/server/privilege.go @@ -25,6 +25,7 @@ import ( "github.com/apache/airavata-custos/pkg/common" "github.com/apache/airavata-custos/pkg/identity" "github.com/apache/airavata-custos/pkg/models" + "github.com/apache/airavata-custos/pkg/service" ) // @Summary Get caller's effective privileges @@ -61,6 +62,7 @@ type CallerProfileResponse struct { Privileges []models.PrivilegeKey `json:"privileges"` Roles []CallerRoleGrant `json:"roles"` ClusterAccounts []CallerClusterAccount `json:"cluster_accounts"` + ClusterAccess []service.ClusterLogin `json:"cluster_access"` Consent consentView `json:"consent"` Onboarding onboardingView `json:"onboarding"` } @@ -131,6 +133,11 @@ func (s *Server) getCallerProfile(w http.ResponseWriter, r *http.Request) { common.WriteServiceError(w, err) return } + access, err := s.svc.ClusterAccess(r.Context(), caller.UserID) + if err != nil { + common.WriteServiceError(w, err) + return + } onboarding := onboardingView{Required: caller.NeedsOnboarding} if caller.NeedsOnboarding { if onboarding.UsernameEditable, err = s.svc.UsernameEditable(r.Context(), user, accounts); err != nil { @@ -155,6 +162,7 @@ func (s *Server) getCallerProfile(w http.ResponseWriter, r *http.Request) { Privileges: keys, Roles: roles, ClusterAccounts: clusterAccounts, + ClusterAccess: access, Consent: consentView{Pending: pending}, Onboarding: onboarding, }) diff --git a/internal/server/privilege_integration_test.go b/internal/server/privilege_integration_test.go index 3d751e830..99a425849 100644 --- a/internal/server/privilege_integration_test.go +++ b/internal/server/privilege_integration_test.go @@ -120,6 +120,9 @@ func TestGetCallerProfile_ReturnsUserAndPrivileges(t *testing.T) { if body.Roles == nil || len(body.Roles) != 0 { t.Errorf("roles: got %v, want empty array", body.Roles) } + if body.ClusterAccess == nil || len(body.ClusterAccess) != 0 { + t.Errorf("cluster_access: got %v, want empty array", body.ClusterAccess) + } } func TestGetCallerProfile_IncludesOwnRoles(t *testing.T) { diff --git a/pkg/service/cluster_access.go b/pkg/service/cluster_access.go new file mode 100644 index 000000000..d10a02aa9 --- /dev/null +++ b/pkg/service/cluster_access.go @@ -0,0 +1,84 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Cluster access is derived on every call and never stored. A VIRTUAL user +// logs in as the shared login until they hold an account of their own on its +// cluster, and falls back to it if that account goes away. Nothing flips on +// the user, so no write can leave access out of step with the accounts. +package service + +import ( + "context" + "fmt" + + "github.com/apache/airavata-custos/pkg/models" +) + +// ClusterLogin is a login a user may use on a cluster. +type ClusterLogin struct { + ComputeClusterID string `json:"compute_cluster_id"` + LocalUsername string `json:"local_username"` + Shared bool `json:"shared"` +} + +// SetSharedLogin names the cluster account every VIRTUAL user logs in as. +func (s *Service) SetSharedLogin(clusterID, username string) { + s.sharedClusterID, s.sharedUsername = clusterID, username +} + +// ClusterAccess returns the logins the user may use now. A user who is not +// ACTIVE, or has an agreement to accept, has none. +func (s *Service) ClusterAccess(ctx context.Context, userID string) ([]ClusterLogin, error) { + logins := []ClusterLogin{} + user, err := s.GetUser(ctx, userID) + if err != nil { + return nil, err + } + if user.Status != models.UserActive { + return logins, nil + } + if pending, err := s.PendingUserAgreements(ctx, userID); err != nil || len(pending) > 0 { + return logins, err + } + accounts, err := s.clusterUsers.FindByUser(ctx, userID) + if err != nil { + return nil, fmt.Errorf("list cluster accounts: %w", err) + } + ownOnSharedCluster := false + for _, a := range accounts { + if !usable(&a) { + continue + } + logins = append(logins, ClusterLogin{ComputeClusterID: a.ComputeClusterID, LocalUsername: a.LocalUsername}) + ownOnSharedCluster = ownOnSharedCluster || a.ComputeClusterID == s.sharedClusterID + } + if user.Type != models.UserTypeVirtual || ownOnSharedCluster { + return logins, nil + } + shared, err := s.clusterUsers.FindByClusterAndLocalUsername(ctx, s.sharedClusterID, s.sharedUsername) + if err != nil { + return nil, fmt.Errorf("lookup shared login: %w", err) + } + if usable(shared) { + logins = append(logins, ClusterLogin{ComputeClusterID: shared.ComputeClusterID, LocalUsername: shared.LocalUsername, Shared: true}) + } + return logins, nil +} + +func usable(a *models.ComputeClusterUser) bool { + return a != nil && a.ApprovalStatus == models.ClusterAccountApproved && a.ProvisionedAt != nil +} diff --git a/pkg/service/cluster_access_integration_test.go b/pkg/service/cluster_access_integration_test.go new file mode 100644 index 000000000..8ace99f65 --- /dev/null +++ b/pkg/service/cluster_access_integration_test.go @@ -0,0 +1,125 @@ +//go:build integration + +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package service + +import ( + "slices" + "testing" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + + "github.com/apache/airavata-custos/pkg/models" +) + +func seedVirtualUser(t *testing.T, database *sqlx.DB) string { + t.Helper() + id := seedUser(t, database, uuid.NewString()+"@example.edu") + if _, err := database.Exec("UPDATE users SET type = $1 WHERE id = $2", models.UserTypeVirtual, id); err != nil { + t.Fatalf("make user virtual: %v", err) + } + return id +} + +// seedApprovedAccount creates an approved cluster account, provisioned or not. +func seedApprovedAccount(t *testing.T, svc *Service, clusterID, userID string, provisioned bool) *models.ComputeClusterUser { + t.Helper() + cu, err := svc.CreateComputeClusterUser(ctx(), &models.ComputeClusterUser{ + ComputeClusterID: clusterID, + UserID: userID, + LocalUsername: "u-" + uuid.NewString()[:8], + ApprovalStatus: models.ClusterAccountApproved, + ReviewedBy: &userID, + }) + if err != nil { + t.Fatalf("create cluster account: %v", err) + } + if provisioned { + if err := svc.MarkComputeClusterUserProvisioned(ctx(), cu.ID); err != nil { + t.Fatalf("mark provisioned: %v", err) + } + } + return cu +} + +func wantAccess(t *testing.T, svc *Service, userID string, want ...ClusterLogin) { + t.Helper() + got, err := svc.ClusterAccess(ctx(), userID) + if err != nil { + t.Fatalf("cluster access: %v", err) + } + if got == nil || !slices.Equal(got, want) { + t.Fatalf("cluster access: got %+v, want %+v", got, want) + } +} + +// Make sure a temp user logs in as the shared login exactly while they are +// active, have accepted the terms and hold no account of their own on its cluster. +func TestClusterAccess(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + cluster, err := svc.CreateComputeCluster(ctx(), &models.ComputeCluster{Name: "access-" + uuid.NewString()[:8]}) + if err != nil { + t.Fatalf("create cluster: %v", err) + } + operator := seedUser(t, database, uuid.NewString()+"@example.edu") + sharedAccount := seedApprovedAccount(t, svc, cluster.ID, operator, true) + svc.SetSharedLogin(cluster.ID, sharedAccount.LocalUsername) + shared := ClusterLogin{ComputeClusterID: cluster.ID, LocalUsername: sharedAccount.LocalUsername, Shared: true} + + temp := seedVirtualUser(t, database) + wantAccess(t, svc, temp, shared) + wantAccess(t, svc, operator, ClusterLogin{ComputeClusterID: cluster.ID, LocalUsername: sharedAccount.LocalUsername}) + wantAccess(t, svc, seedUser(t, database, uuid.NewString()+"@example.edu")) + + if _, err := svc.UpdateUserStatus(ctx(), temp, models.UserInactive); err != nil { + t.Fatalf("disable: %v", err) + } + wantAccess(t, svc, temp) + if _, err := svc.UpdateUserStatus(ctx(), temp, models.UserActive); err != nil { + t.Fatalf("enable: %v", err) + } + + // Their own account takes over once it is provisioned, and gives way again when it is removed. + own := seedApprovedAccount(t, svc, cluster.ID, temp, false) + wantAccess(t, svc, temp, shared) + if err := svc.MarkComputeClusterUserProvisioned(ctx(), own.ID); err != nil { + t.Fatalf("mark provisioned: %v", err) + } + wantAccess(t, svc, temp, ClusterLogin{ComputeClusterID: cluster.ID, LocalUsername: own.LocalUsername}) + if err := svc.DeleteComputeClusterUser(ctx(), own.ID); err != nil { + t.Fatalf("delete account: %v", err) + } + wantAccess(t, svc, temp, shared) + + aup := seedPublishedAgreement(t, svc, seedAgreementManager(t, database), "1.0") + wantAccess(t, svc, temp) + if _, err := svc.AcceptUserAgreement(ctx(), temp, aup.ID); err != nil { + t.Fatalf("accept: %v", err) + } + wantAccess(t, svc, temp, shared) + + // A shared login that is not provisioned gives no access. + pending := seedApprovedAccount(t, svc, cluster.ID, seedUser(t, database, uuid.NewString()+"@example.edu"), false) + svc.SetSharedLogin(cluster.ID, pending.LocalUsername) + wantAccess(t, svc, temp) + svc.SetSharedLogin("", "") + wantAccess(t, svc, temp) +} diff --git a/pkg/service/service.go b/pkg/service/service.go index 528d80ed0..61ca288a8 100644 --- a/pkg/service/service.go +++ b/pkg/service/service.go @@ -40,6 +40,8 @@ type Service struct { db *sqlx.DB eventBus *events.Bus reservedUsernames map[string]bool + sharedClusterID string + sharedUsername string orgs store.OrganizationStore users store.UserStore projs store.ProjectStore diff --git a/pkg/service/user.go b/pkg/service/user.go index b25999c32..2cb54549d 100644 --- a/pkg/service/user.go +++ b/pkg/service/user.go @@ -23,6 +23,7 @@ import ( "errors" "fmt" "log/slog" + "strings" "github.com/apache/airavata-custos/pkg/events" "github.com/apache/airavata-custos/pkg/models" @@ -41,6 +42,10 @@ func (s *Service) CreateUser(ctx context.Context, user *models.User) (*models.Us } return s.eventBus.Publish(ctx, tx, events.UserCreateEvent, user) }); err != nil { + // Another create took the email after the check above. + if strings.Contains(err.Error(), "uq_users_email") { + return nil, fmt.Errorf("%w: user with email %q", ErrAlreadyExists, user.Email) + } return nil, fmt.Errorf("create user: %w", err) } return user, nil diff --git a/web/scripts/gen-api.mts b/web/scripts/gen-api.mts index fffeb46f9..672c37d35 100644 --- a/web/scripts/gen-api.mts +++ b/web/scripts/gen-api.mts @@ -46,7 +46,7 @@ async function main() { for (const mod of modules) { const spec: unknown = parse(readFileSync(mod.input, "utf8")); if (!isNode(spec)) throw new Error(`gen-api: ${mod.input} is not an OpenAPI document`); - supplement(mod.name, spec, go, repoRoot); + supplement(mod.name, spec, go); const report = applyPresence(spec, go); settle(mod.name, spec); console.log(`gen-api: ${mod.name} presence ${JSON.stringify(report)}`); diff --git a/web/scripts/spec-supplement.mts b/web/scripts/spec-supplement.mts index 051dd2b99..5d1282c71 100644 --- a/web/scripts/spec-supplement.mts +++ b/web/scripts/spec-supplement.mts @@ -1,12 +1,9 @@ /** * What the portal states about the API beyond master's swag specs, read off master's handlers. * Responses a handler writes as a map literal carry every key, so each is listed with the Go value - * behind it: nullable only where a nil slice or pointer can reach the encoder. The TempAccount - * connector ships no spec, so its routes are added to core over the core models its handlers decode - * and encode. Drift fails generation: a key set that no longer matches, or a route its handler lost. + * behind it: nullable only where a nil slice or pointer can reach the encoder. + * Drift fails generation: a key set that no longer matches. */ -import { readFileSync } from "node:fs"; -import path from "node:path"; import { type GoIndex, type Node, at, isNode } from "./go-presence.mts"; const ref = (name: string) => ({ $ref: `#/definitions/${name}` }); @@ -141,35 +138,6 @@ function struct(go: GoIndex, name: string, properties: Node): Node { }; } -const userPath = [{ in: "path", name: "user_id", required: true, type: "string" }]; -const body = (name: string) => [{ in: "body", name: "body", required: true, schema: ref(name) }]; -const answers = (code: number, schema?: unknown) => ({ - [code]: schema ? { description: "OK", schema } : { description: "No Content" }, -}); -const membership = { - parameters: body("ComputeAllocationMembership"), - responses: answers(200, ref("ComputeAllocationMembership")), -}; - -// connectors/TempAccount/internal/handlers.go: a VIRTUAL core user and its core memberships. -const tempAccountRoutes: Record<string, Node> = { - "/connectors/temp-account/create": { - post: { parameters: body("User"), responses: answers(201, ref("User")) }, - }, - "/connectors/temp-account/assign-allocation": { post: membership }, - "/connectors/temp-account/update-allocation": { post: membership }, - "/connectors/temp-account/remove/{user_id}": { - delete: { parameters: userPath, responses: answers(204) }, - }, - // A user without memberships answers 404, so a 200 list is never nil. - "/connectors/temp-account/membership/{user_id}": { - get: { - parameters: userPath, - responses: answers(200, array(ref("ComputeAllocationMembership"))), - }, - }, -}; - const success = (spec: Node, op: string) => { const [method = "", route = ""] = op.split(" "); return at(spec, "paths", route, method.toLowerCase(), "responses", "200"); @@ -201,7 +169,7 @@ export function settle(module: string, spec: Node): void { } /** Applies the supplement for one gen-api module to its parsed spec, in place. */ -export function supplement(module: string, spec: Node, go: GoIndex, repoRoot: string): void { +export function supplement(module: string, spec: Node, go: GoIndex): void { for (const [op, [annotated, returned]] of Object.entries(retyped[module] ?? {})) { const response = success(spec, op); if (!isNode(response) || at(response, "schema", "items", "$ref") !== ref(annotated).$ref) { @@ -223,20 +191,4 @@ export function supplement(module: string, spec: Node, go: GoIndex, repoRoot: st } Object.assign(response, { schema: stated }); } - if (module !== "core") return; - const handlers = readFileSync( - path.join(repoRoot, "connectors", "TempAccount", "internal", "handlers.go"), - "utf8", - ); - const paths = at(spec, "paths"); - if (!isNode(paths)) throw new Error("spec-supplement: the core spec has no paths"); - for (const [route, item] of Object.entries(tempAccountRoutes)) { - for (const method of Object.keys(item)) { - const pattern = `"${method.toUpperCase()} ${route}"`; - if (!handlers.includes(pattern) || paths[route]) { - throw new Error(`spec-supplement: ${pattern} is gone from the handlers or now in the spec`); - } - } - paths[route] = item; - } }
