diff --git a/AGENTS.md b/AGENTS.md index 340828567..ea5f07801 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,7 +92,7 @@ Custom JWT claims: user_id, user_roles, user_permissions, org_role, org_permissi ### 2.3 Impersonation -Owner organization only (Staff and Owner user roles carry `impersonate:users`). `POST /api/impersonate` mints a JWT with the target user's permissions, expiring with the remaining consent window (not a fixed hour). Requires the target to have opted-in via `POST /api/impersonate/consent` (1-168h, default 1h; revoked with DELETE). All sessions and actions are audited via `impersonation_audit` middleware. No self-impersonation, no chaining. An account holding the Owner user role is never a target. `DELETE /api/impersonate` revokes the impersonation token and re-mints the impersonator's session from its current state (a suspended impersonator gets 401); `GET /api/impersonate/status` re-checks the target's consent before handing out a token. The consent and sessions endpoints refuse impersonation tokens (`DisableOnImpersonate`): they belong to the real account only. +Owner organization only (Staff and Owner user roles carry `impersonate:users`). `POST /api/impersonate` mints a JWT with the target user's permissions, expiring after `IMPERSONATION_SESSION_DURATION` (default 1h, capped at 168h). The target's consent is not asked: any active user is a target, across the whole hierarchy. All sessions and actions are audited via `impersonation_audit` middleware. No self-impersonation, no chaining. An account holding the Owner user role is never a target. `POST /api/impersonate/extend` (impersonation token only, never an API key) restarts the session for a full duration with a new token and revokes the presented one, re-checking the impersonator's `impersonate:users` and the target from their current state; it is audited as `session_extended`. `DELETE /api/impersonate` revokes the impersonation token and re-mints the impersonator's session from its current state (a suspended impersonator gets 401); `GET /api/impersonate/status` hands out a token for the active session. The sessions endpoints refuse impersonation tokens (`DisableOnImpersonate`): they belong to the real account only. --- @@ -226,6 +226,7 @@ Embedded in the custom JWT at exchange time. No external calls during request ha - `middleware.RequireResourcePermission("systems")` — HTTP-verb-aware: `read:` on GET, `manage:` on **POST/PUT/PATCH/DELETE alike** (`middleware/rbac.go`). `destroy:` is never derived from the verb — an endpoint that needs it says so explicitly, e.g. `middleware.RequirePermission("destroy:systems")` on `/systems/:id/destroy` - `middleware.RequireResourcePermissionOrSelf("resellers")` — as above, plus a GET on the caller's own organization is always allowed (org roles carry permissions for the levels *below*, so without this a reseller could not read itself) - `middleware.PreventSelfModification()` — blocks a user from acting on their own account for dangerous verbs +- Soft-deleted objects belong to the Owner organization: outside it, a list or export with `status=deleted` gets 403 (`methods.rejectDeletedStatusOutsideOwnerOrg`) and the `/:id/restore` routes are gated by `middleware.RequireOrgRole(models.OwnerOrgRole)`. For everyone else, Delete is final - Hierarchy check for cross-org reads/writes: `local.UserService.IsOrganizationInHierarchy(orgRole, userOrgID, targetOrgID)` - RBAC filtering in SQL: `helpers.AppendOrgFilter(query, orgRole, orgID, tableAlias, args, nextArgIdx)` uses `GetAllowedOrgIDsForFilter` (cached org-ID set) for non-owner roles @@ -270,7 +271,7 @@ Entities synced with Logto (orgs, users) carry both `id` (DB UUID) and `logto_id ### 6.2 Error messages -User-facing errors are **lowercase**. Example: `"the user has revoked consent for impersonation. please exit impersonation mode."` +User-facing errors are **lowercase**. Example: `"cannot impersonate while already impersonating another user. exit current impersonation first."` Field validation errors (`response.ValidationError` with a 400/409/422 status) are not shown to users as written: the frontend turns each one into an i18n key, `._` (`getValidationIssues` in `frontend/src/lib/validation.ts`). The dots of a nested key become underscores (`custom_data.vat` gives `custom_data_vat`); the message is lowercased and its spaces become underscores, while any other character stays as it is. Therefore: diff --git a/backend/.env.example b/backend/.env.example index 18a61d1f7..41c144273 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -118,6 +118,10 @@ REDIS_URL=redis://localhost:6379 # changes trigger a run on their own; 0 disables the periodic loop. #THIRD_PARTY_APPS_IDP_RECONCILE_INTERVAL=15m +# How long an impersonation session lasts before it expires (Go duration, +# default 1h, capped at 168h) +#IMPERSONATION_SESSION_DURATION=1h + # =========================================== # MIMIR CONFIGURATION (Optional) # =========================================== diff --git a/backend/README.md b/backend/README.md index 969805908..046f68d44 100644 --- a/backend/README.md +++ b/backend/README.md @@ -85,6 +85,9 @@ BACKUP_S3_USE_PATH_STYLE=false # Lifetime of a presigned download URL (capped server-side at 15m). #BACKUP_PRESIGN_TTL=5m +# Lifetime of an impersonation session (Go duration, capped server-side at 168h). +#IMPERSONATION_SESSION_DURATION=1h + # =========================================== # SMTP EMAIL CONFIGURATION (Optional) # =========================================== @@ -137,7 +140,7 @@ Templates are in `services/email/templates/` and support Go template syntax. Role pairing is enforced fail-closed by the API: inside the Owner organization only Staff is assignable, Staff is never assignable outside it, and the Owner user role is never assignable at all — it belongs solely to the bootstrap `owner` account seeded by `sync init` and is not returned by `GET /api/roles`. Staff holds all non-destructive technical scopes (including `impersonate:users` and `connect:systems`) but no `destroy:systems|users` and cannot manage the Owner organization's own membership; the Owner role adds those. ### User Impersonation -Requires the `impersonate:users` permission, held only by the Staff and Owner user roles: temporarily act as another user with 1-hour scoped JWT tokens. Consent of the target user is mandatory; reach is platform-wide by design. Prevents self-impersonation and token chaining. All actions are logged. +Requires the `impersonate:users` permission, held only by the Staff and Owner user roles: temporarily act as another user with scoped JWT tokens that expire after `IMPERSONATION_SESSION_DURATION` (default 1h). The target user's consent is not asked; reach is platform-wide by design. Prevents self-impersonation and token chaining. All actions are logged. - `POST /api/auth/impersonate` - Start impersonation - `POST /api/auth/exit-impersonation` - Exit impersonation diff --git a/backend/authz/README.md b/backend/authz/README.md index 893b0a006..a08251f52 100644 --- a/backend/authz/README.md +++ b/backend/authz/README.md @@ -176,22 +176,20 @@ and 3 below are **fixed**; finding 1 turned out not to be a defect. ### 1. Cross-hierarchy impersonation — INTENDED, spec states it -`POST /api/impersonate` checks the `impersonate:users` permission and the -target's consent but **not** whether the target is inside the caller's -hierarchy: an Owner-organization user reaches any consenting user of any +`POST /api/impersonate` checks the `impersonate:users` permission but **not** +whether the target is inside the caller's hierarchy, and it does not ask the +target's consent: an Owner-organization user reaches any active user of any distributor, reseller or customer — all 200. That is the design, not a defect. The Owner organization's staff must be able to support users of every distributor and reseller. The feature therefore has -two barriers, and the hierarchy is deliberately not one of them: +one barrier, and the hierarchy is deliberately not it: the caller must hold +`impersonate:users`, which only the **Staff** and **Owner** user roles carry — +both confined to the Owner organization (Staff is assignable only there, by an +Owner-role caller; Owner is never assignable at all). An Owner-role account is +never a target, and every session is audited. -1. the target must have consented; -2. the caller must hold `impersonate:users`, which only the **Staff** and - **Owner** user roles carry — both confined to the Owner organization (Staff - is assignable only there, by an Owner-role caller; Owner is never - assignable at all). - -**Barrier 2 is what protects the whole feature**, so that is where the suite +**That barrier is what protects the whole feature**, so that is where the suite asserts. Verified: a distributor Admin, a reseller Admin, a customer Admin and a Backoffice user are all refused when promoting a user to Staff *or* creating one — including when the role id is supplied directly rather than picked from diff --git a/backend/authz/routes.yml b/backend/authz/routes.yml index 84ac15cae..230ef6a23 100644 --- a/backend/authz/routes.yml +++ b/backend/authz/routes.yml @@ -152,25 +152,10 @@ routes: note: revoking somebody else's key must fail on ownership, not on a permission # =========================================================================== - # Impersonation. Consent is the caller's own business; impersonating somebody - # requires the dedicated impersonate:users permission, which only the Owner - # and Staff user roles carry - # holds in config.yml. + # Impersonation. Impersonating somebody requires the dedicated + # impersonate:users permission, which only the Owner and Staff user roles + # carry in config.yml; the target's consent is not asked. # =========================================================================== - - method: GET - path: /api/impersonate/consent - intent: authenticated - - - method: POST - path: /api/impersonate/consent - intent: authenticated - skip: mutates the caller's own consent state; exercised explicitly in the special layer - - - method: DELETE - path: /api/impersonate/consent - intent: authenticated - skip: mutates the caller's own consent state; exercised explicitly in the special layer - - method: GET path: /api/impersonate/status intent: authenticated @@ -184,6 +169,15 @@ routes: intent: authenticated note: exiting an impersonation the caller is not in is a no-op, not an authorization question + - method: POST + path: /api/impersonate/extend + intent: authenticated + note: | + Only an impersonation token has a session to extend: any other token gets + 400. The handler re-reads the impersonator and requires impersonate:users + from its current state; API keys are refused by RejectAPIKey, asserted in + the special layer. + - method: GET path: /api/impersonate/sessions intent: authenticated @@ -232,6 +226,8 @@ routes: - method: PATCH path: /api/systems/:id/restore intent: manage:systems + org_role: owner + note: soft-deleted objects are seen and restored by the Owner organization only - method: DELETE path: /api/systems/:id/destroy intent: destroy:systems @@ -242,6 +238,19 @@ routes: - method: PATCH path: /api/systems/:id/reactivate intent: manage:systems + - method: PUT + path: /api/systems/:id/favorite + intent: read:systems + note: | + Starring is a personal bookmark that changes nothing on the system, so it + needs only read access to it — a Reader may star what it can see. The + system must still be in the caller's scope. + - method: DELETE + path: /api/systems/:id/favorite + intent: read:systems + note: | + Removes only the caller's own star, so it may target a system that has + since left the caller's scope. - method: GET path: /api/systems/totals intent: read:systems @@ -651,6 +660,8 @@ routes: - method: PATCH path: /api/distributors/:id/restore intent: manage:distributors + org_role: owner + note: soft-deleted objects are seen and restored by the Owner organization only - method: DELETE path: /api/distributors/:id/destroy intent: destroy:distributors @@ -709,6 +720,8 @@ routes: - method: PATCH path: /api/resellers/:id/restore intent: manage:resellers + org_role: owner + note: soft-deleted objects are seen and restored by the Owner organization only - method: DELETE path: /api/resellers/:id/destroy intent: destroy:resellers @@ -797,6 +810,8 @@ routes: - method: PATCH path: /api/customers/:id/restore intent: manage:customers + org_role: owner + note: soft-deleted objects are seen and restored by the Owner organization only - method: DELETE path: /api/customers/:id/destroy intent: destroy:customers @@ -875,6 +890,8 @@ routes: - method: PATCH path: /api/users/:id/restore intent: manage:users + org_role: owner + note: soft-deleted objects are seen and restored by the Owner organization only - method: DELETE path: /api/users/:id/destroy intent: destroy:users diff --git a/backend/authz/scenarios.yml b/backend/authz/scenarios.yml index e48886af3..a9c781d95 100644 --- a/backend/authz/scenarios.yml +++ b/backend/authz/scenarios.yml @@ -276,6 +276,73 @@ scenarios: path: /api/customers/{org:d1r2c1}/suspend expect: denied + # =========================================================================== + # Soft-deleted objects belong to the Owner organization: it alone sees and + # restores them, and for everyone else a Delete is final. Outside it, a list + # or an export filtered on status=deleted is refused, and so is a restore, + # even of an object inside the caller's own hierarchy. + # =========================================================================== + - name: distributor cannot list deleted resellers + as: d1-admin + method: GET + path: /api/resellers?status=deleted + expect_status: [403] + - name: reseller cannot list deleted customers + as: d1r1-admin + method: GET + path: /api/customers?status=deleted + expect_status: [403] + - name: reseller cannot list deleted users + as: d1r1-admin + method: GET + path: /api/users?status=deleted + expect_status: [403] + - name: customer cannot list deleted systems + as: d1r1c1-admin + method: GET + path: /api/systems?status=deleted + expect_status: [403] + - name: reseller cannot list deleted systems among other statuses + as: d1r1-admin + method: GET + path: /api/systems?status=active&status=deleted + expect_status: [403] + - name: reseller cannot export deleted customers + as: d1r1-admin + method: GET + path: /api/customers/export?format=csv&status=deleted + expect_status: [403] + - name: distributor cannot export deleted systems + as: d1-admin + method: GET + path: /api/systems/export?format=csv&status=deleted + expect_status: [403] + - name: staff can list deleted customers + as: owner-staff + method: GET + path: /api/customers?status=deleted + expect: allowed + - name: staff can list deleted users + as: owner-staff + method: GET + path: /api/users?status=deleted + expect: allowed + - name: reseller cannot restore its own customer + as: d1r1-admin + method: PATCH + path: /api/customers/{org:d1r1c1}/restore + expect_status: [403] + - name: reseller cannot restore its own user + as: d1r1-admin + method: PATCH + path: /api/users/{user:d1r1c1-admin}/restore + expect_status: [403] + - name: customer cannot restore its own system + as: d1r1c1-admin + method: PATCH + path: /api/systems/{system:s-d1r1c1}/restore + expect_status: [403] + - name: reseller cannot restore an organization outside its hierarchy as: d1r1-admin method: PATCH diff --git a/backend/authz/special.yml b/backend/authz/special.yml index d4136a8b1..c1ad18431 100644 --- a/backend/authz/special.yml +++ b/backend/authz/special.yml @@ -5,24 +5,23 @@ # api_key — a myk_ token is bounded by BOTH its read/write mode and # the live permissions of the user who owns it, and is # refused outright on session-bound routes -# impersonate — needs impersonate:users AND the target's consent +# impersonate — needs impersonate:users, and nothing from the target # # IMPERSONATION IS DELIBERATELY CROSS-HIERARCHY. The Owner organization's -# staff must be able to support users of every distributor and reseller. So -# the design has exactly two barriers, and neither of them is the hierarchy: +# staff must be able to support users of every distributor and reseller, +# without asking them first. So the design has one barrier, and it is not the +# hierarchy: the caller must hold impersonate:users, which only the Owner and +# Staff user roles carry — both confined to the Owner organization. The +# handler also refuses the caller itself, an inactive user and any Owner-role +# account; every session is audited. # -# 1. the target must have consented; -# 2. the caller must hold impersonate:users, which only the Owner and Staff -# user roles carry — both confined to the Owner organization. +# The barrier is therefore what protects the whole feature, and it is asserted +# in scenarios.yml ("cannot promote a user to Owner"), not here. # -# Barrier 2 is therefore what protects the whole feature, and it is asserted in -# scenarios.yml ("cannot promote a user to Owner"), not here. -# -# The cases below assert both barriers, in both directions: consent missing means -# refused, consent present means allowed even across branches. The positive ones -# open real sessions, which the runner closes immediately with the token the -# response returns — otherwise a live session would block that persona with a 409 -# for an hour. setup/teardown exist to grant and revoke the target's consent. +# The cases below assert the reach, across branches and upwards. They open real +# sessions, which the runner closes immediately with the token the response +# returns — otherwise a live session would block that persona with a 409 for +# the rest of the session. cases: # =========================================================================== @@ -196,6 +195,30 @@ cases: expect: denied note: the owner of this key holds impersonate:users, so only RejectAPIKey can stop it + - name: key cannot extend an impersonation + kind: api_key + as: owner-staff + mode: write + method: POST + path: /api/impersonate/extend + expect: denied + note: | + A key is not an impersonation token, so the handler would answer 400 + anyway; the case pins that RejectAPIKey refuses it first, so a key never + reaches the session logic. + must_not_contain: ["not currently impersonating"] + + - name: key cannot star a system + kind: api_key + as: d1r1-admin + mode: write + method: PUT + path: /api/systems/{system:s-d1r1c1}/favorite + expect: denied + note: | + The owner of this key can read the system, so only RejectAPIKey can stop + it: favorites are a personal bookmark of an interactive session. + - name: key cannot change the owner's password kind: api_key as: d1r1-admin @@ -242,98 +265,39 @@ cases: note: the owner of this key holds manage:resellers, so only the Owner-organization gate in the handler can stop it # =========================================================================== - # Impersonation. Consent is checked first, so every case here says explicitly - # which barrier it is testing. + # Impersonation. No consent: an Owner-organization user with impersonate:users + # reaches any active user, whatever the branch. # =========================================================================== - - name: impersonation without the target's consent is refused - kind: impersonate - as: owner-staff - method: POST - path: /api/impersonate - body: '{"user_id":"{user:d1r1-reader}"}' - expect: denied - must_contain: ["consent"] - note: same organization, so consent is the only barrier left — and it must hold - - - name: a consenting user of another organization CAN be impersonated + - name: a user of another organization CAN be impersonated kind: impersonate - setup: - - as: d1r2-admin - method: POST - path: /api/impersonate/consent - body: '{"duration_hours":1}' as: owner-staff method: POST path: /api/impersonate body: '{"user_id":"{user:d1r2-admin}"}' expect: allowed - teardown: - - as: d1r2-admin - method: DELETE - path: /api/impersonate/consent note: | The feature this design exists for: reaching a user outside your own subtree - — here the sibling reseller's admin — with that user's consent. Asserted - positively so that adding a hierarchy check would show up as a regression in - legitimate support access rather than as a silent behaviour change. + — here the sibling reseller's admin. Asserted positively so that adding a + hierarchy check, or bringing back a consent, would show up as a regression + in legitimate support access rather than as a silent behaviour change. - - name: a consenting user of the parent organization CAN be impersonated + - name: a user of the parent organization CAN be impersonated kind: impersonate - setup: - - as: d1-admin - method: POST - path: /api/impersonate/consent - body: '{"duration_hours":1}' as: owner-staff method: POST path: /api/impersonate body: '{"user_id":"{user:d1-admin}"}' expect: allowed - teardown: - - as: d1-admin - method: DELETE - path: /api/impersonate/consent note: upward too — Nethesis Italia is a distributor, so its staff must reach peers and parents - - name: a consenting user of a different branch CAN be impersonated + - name: a user of a different branch CAN be impersonated kind: impersonate - setup: - - as: d2r1c1-admin - method: POST - path: /api/impersonate/consent - body: '{"duration_hours":1}' as: owner-staff method: POST path: /api/impersonate body: '{"user_id":"{user:d2r1c1-admin}"}' expect: allowed - teardown: - - as: d2r1c1-admin - method: DELETE - path: /api/impersonate/consent note: | Reach is platform-wide by design: impersonate:users lives only on the Owner and Staff user roles, both confined to the Owner organization, so - the containment is structural now — no partner user can hold it. Consent - remains the per-target barrier. - - - name: consent expiry is honoured — a revoked consent stops working - kind: impersonate - setup: - - as: d1r2-support - method: POST - path: /api/impersonate/consent - body: '{"duration_hours":1}' - - as: d1r2-support - method: DELETE - path: /api/impersonate/consent - as: owner-staff - method: POST - path: /api/impersonate - body: '{"user_id":"{user:d1r2-support}"}' - expect: denied - must_contain: ["consent"] - note: | - Granting then revoking must leave the target protected. Without this, a - consent that is written but never actually enforced on revocation would look - identical to a working one. + the containment is structural — no partner user can hold it. diff --git a/backend/cache/impersonation_sessions.go b/backend/cache/impersonation_sessions.go index 11711cc21..655744f95 100644 --- a/backend/cache/impersonation_sessions.go +++ b/backend/cache/impersonation_sessions.go @@ -11,6 +11,7 @@ package cache import ( "encoding/json" + "errors" "fmt" "time" @@ -175,6 +176,46 @@ func (m *ImpersonationSessionManager) ClearSession(impersonatorUserID string) er return nil } +// ErrImpersonationSessionNotFound means the impersonator has no active +// session with the given id: it expired, was exited, or was replaced. +var ErrImpersonationSessionNotFound = errors.New("impersonation session not found") + +// ExtendSession moves the expiry of the impersonator's active session to +// now + duration, keeping its id and start. It fails with +// ErrImpersonationSessionNotFound when sessionID is not the active session. +func (m *ImpersonationSessionManager) ExtendSession(impersonatorUserID, sessionID string, duration time.Duration) error { + if m.redis == nil { + logger.ComponentLogger("impersonation_sessions").Warn(). + Msg("Redis client not available - skipping session extension") + return nil // Fail-open, as CreateSession + } + + session, err := m.GetActiveSession(impersonatorUserID) + if err != nil { + return err + } + if session == nil || session.SessionID != sessionID { + return ErrImpersonationSessionNotFound + } + + session.ExpiresAt = time.Now().Add(duration) + sessionData, err := json.Marshal(session) + if err != nil { + return fmt.Errorf("failed to marshal session data: %w", err) + } + if err := m.redis.Set(m.getSessionKey(impersonatorUserID), string(sessionData), duration); err != nil { + return fmt.Errorf("failed to store session: %w", err) + } + + logger.ComponentLogger("impersonation_sessions").Info(). + Str("impersonator_user_id", impersonatorUserID). + Str("session_id", sessionID). + Time("expires_at", session.ExpiresAt). + Msg("Active impersonation session extended") + + return nil +} + // ClearSessionByID removes an active impersonation session by session ID // This is used when we need to clean up by session ID instead of impersonator ID func (m *ImpersonationSessionManager) ClearSessionByID(impersonatorUserID, sessionID string) error { diff --git a/backend/cmd/apitool/authz_lifecycle.go b/backend/cmd/apitool/authz_lifecycle.go index eb4985777..1dd50c91e 100644 --- a/backend/cmd/apitool/authz_lifecycle.go +++ b/backend/cmd/apitool/authz_lifecycle.go @@ -231,7 +231,13 @@ func (lc *lcRun) systemDeleteRestore() error { "PATCH", "/api/systems/"+s+"/restore", nil, "denied"); err != nil { return err } - if _, err := lc.expect("customer admin restores its own system", "d1r1c1-admin", + // Restoring is the Owner organization's alone: for a partner, a Delete is + // final, even on its own system. + if _, err := lc.expect("customer admin cannot restore its own system", "d1r1c1-admin", + "PATCH", "/api/systems/"+s+"/restore", nil, "denied"); err != nil { + return err + } + if _, err := lc.expect("staff restores the system", "owner-staff", "PATCH", "/api/systems/"+s+"/restore", nil, "allowed"); err != nil { return err } @@ -301,7 +307,11 @@ func (lc *lcRun) customerDeleteRestoreAndPromotion() error { return err } lc.routed("customer: no route while deleted", lcr, "lc-c@", false) - if _, err := lc.expect("reseller admin restores its customer", adminKey, + if _, err := lc.expect("reseller admin cannot restore its own customer", adminKey, + "PATCH", "/api/customers/"+lcc+"/restore", nil, "denied"); err != nil { + return err + } + if _, err := lc.expect("staff restores the customer", "owner-staff", "PATCH", "/api/customers/"+lcc+"/restore", nil, "allowed"); err != nil { return err } diff --git a/backend/cmd/apitool/authz_special.go b/backend/cmd/apitool/authz_special.go index 9b66ed393..59f2a9983 100644 --- a/backend/cmd/apitool/authz_special.go +++ b/backend/cmd/apitool/authz_special.go @@ -18,7 +18,7 @@ import ( // api_key — a myk_ token is capped by BOTH its read/write mode and // the live permissions of the user who owns it, and is // refused outright on session-bound routes -// impersonate — needs impersonate:users AND the target's consent +// impersonate — needs impersonate:users, and nothing from the target // SpecialSpec is one hand-written case. Kind selects the check; the remaining // fields are its parameters. @@ -34,16 +34,15 @@ type SpecialSpec struct { Expect string `yaml:"expect"` ExpectStatus []int `yaml:"expect_status"` // Setup runs before the case, as other personas, to establish the state the - // case needs — enabling a target's impersonation consent, for instance. A + // case needs, such as a record the case acts on. A // failing setup step makes the case REVIEW rather than a silent pass, because // a case whose precondition never happened proves nothing. Setup []SpecialStep `yaml:"setup"` - // Teardown always runs, so consent flags and sessions do not leak into the + // Teardown always runs, so the state a setup created does not leak into the // next case. Teardown []SpecialStep `yaml:"teardown"` // MustContain / MustNotContain assert on the response body. Used to pin down - // WHY something was refused: a cross-hierarchy impersonation that comes back - // with the consent message was not stopped by the hierarchy check. + // WHY something was refused, when several checks can refuse the same call. MustContain []string `yaml:"must_contain"` MustNotContain []string `yaml:"must_not_contain"` Note string `yaml:"note"` @@ -270,8 +269,7 @@ func (a *authzRunner) specialVerdict(sc SpecialSpec, p *persona, res *probeResul out := specialStatusVerdict(sc, p, res) // Content assertions pin down the REASON, which matters when several checks - // can refuse the same call: a cross-hierarchy impersonation refused with the - // consent message means the hierarchy check never ran. + // can refuse the same call. for _, needle := range sc.MustNotContain { resolved, err := a.resolve(needle, p) if err != nil { diff --git a/backend/configuration/configuration.go b/backend/configuration/configuration.go index 1117e7350..45003edc1 100644 --- a/backend/configuration/configuration.go +++ b/backend/configuration/configuration.go @@ -114,6 +114,10 @@ type Configuration struct { // trigger a run on their own; the loop catches config changes pushed by // sync and any failed push. 0 disables the loop. ThirdPartyAppsIdPReconcileInterval time.Duration `json:"third_party_apps_idp_reconcile_interval"` + + // ImpersonationSessionDuration is how long an impersonation session lasts + // before its token expires: the impersonator starts a new one after it. + ImpersonationSessionDuration time.Duration `json:"impersonation_session_duration"` } var Config = Configuration{} @@ -340,6 +344,18 @@ func Init() { Config.BackupS3UsePathStyle = parseBoolWithDefault("BACKUP_S3_USE_PATH_STYLE", false) Config.ThirdPartyAppsIdPReconcileInterval = parseDurationWithDefault("THIRD_PARTY_APPS_IDP_RECONCILE_INTERVAL", 15*time.Minute) + // Capped at a week, the longest window the former consent allowed, so a + // misconfigured env cannot mint a long-lived impersonation token. + impersonationDuration := parseDurationWithDefault("IMPERSONATION_SESSION_DURATION", time.Hour) + if impersonationDuration > 168*time.Hour { + logger.LogConfigLoad("env", "IMPERSONATION_SESSION_DURATION", false, fmt.Errorf("value %s exceeds the 168h hard cap, clamping", impersonationDuration)) + impersonationDuration = 168 * time.Hour + } + if impersonationDuration <= 0 { + impersonationDuration = time.Hour + } + Config.ImpersonationSessionDuration = impersonationDuration + // Cap the presigned URL lifetime at 15 minutes so a misconfigured // env can never mint long-lived bearer URLs to backup objects. ttl := parseDurationWithDefault("BACKUP_PRESIGN_TTL", 5*time.Minute) diff --git a/backend/database/migrations/062_system_favorites.sql b/backend/database/migrations/062_system_favorites.sql new file mode 100644 index 000000000..088b91ee4 --- /dev/null +++ b/backend/database/migrations/062_system_favorites.sql @@ -0,0 +1,17 @@ +-- Migration 062: favorite systems +-- +-- One row per system a user starred. Keyed on the Logto user ID rather than +-- users(id): the Owner account has no local users row. A destroyed system +-- takes its rows with it; a destroyed user is cleaned up by the backend. + +CREATE TABLE IF NOT EXISTS system_favorites ( + user_logto_id VARCHAR(255) NOT NULL, + system_id VARCHAR(255) NOT NULL REFERENCES systems(id) ON DELETE CASCADE, + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), + PRIMARY KEY (user_logto_id, system_id) +); + +CREATE INDEX IF NOT EXISTS idx_system_favorites_system_id ON system_favorites(system_id); + +COMMENT ON TABLE system_favorites IS 'Systems a user starred as favorites; personal, never shared with other users'; +COMMENT ON COLUMN system_favorites.user_logto_id IS 'Logto user ID of the user who starred the system (no FK: the Owner has no users row)'; diff --git a/backend/database/migrations/062_system_favorites_rollback.sql b/backend/database/migrations/062_system_favorites_rollback.sql new file mode 100644 index 000000000..d8fed7800 --- /dev/null +++ b/backend/database/migrations/062_system_favorites_rollback.sql @@ -0,0 +1,3 @@ +-- Rollback 062: drop favorite systems + +DROP TABLE IF EXISTS system_favorites; diff --git a/backend/database/migrations/063_drop_impersonation_consents.sql b/backend/database/migrations/063_drop_impersonation_consents.sql new file mode 100644 index 000000000..30721b9f1 --- /dev/null +++ b/backend/database/migrations/063_drop_impersonation_consents.sql @@ -0,0 +1,7 @@ +-- Migration 063: drop impersonation_consents +-- +-- Owner and Staff users impersonate without the target's consent: every +-- session is audited in impersonation_audit instead. The consent records have +-- no use left. + +DROP TABLE IF EXISTS impersonation_consents; diff --git a/backend/database/migrations/063_drop_impersonation_consents_rollback.sql b/backend/database/migrations/063_drop_impersonation_consents_rollback.sql new file mode 100644 index 000000000..8a7570f78 --- /dev/null +++ b/backend/database/migrations/063_drop_impersonation_consents_rollback.sql @@ -0,0 +1,28 @@ +-- Rollback 063: recreate impersonation_consents, empty +-- +-- The consent records dropped by 063 are not restored: users grant consent +-- again from their account page. + +CREATE TABLE IF NOT EXISTS impersonation_consents ( + id VARCHAR(255) PRIMARY KEY, + user_id VARCHAR(255) NOT NULL, + expires_at TIMESTAMP WITH TIME ZONE NOT NULL, + max_duration_minutes INTEGER NOT NULL DEFAULT 60, + active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW() +); + +COMMENT ON TABLE impersonation_consents IS 'User consents for allowing impersonation by Owner users'; +COMMENT ON COLUMN impersonation_consents.user_id IS 'User who granted consent for impersonation'; +COMMENT ON COLUMN impersonation_consents.expires_at IS 'Timestamp when consent expires and must be renewed'; +COMMENT ON COLUMN impersonation_consents.max_duration_minutes IS 'Maximum duration of impersonation session in minutes'; +COMMENT ON COLUMN impersonation_consents.active IS 'Whether consent is currently active (can be revoked)'; + +ALTER TABLE impersonation_consents +ADD CONSTRAINT impersonation_consents_user_id_fkey +FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE; + +CREATE INDEX IF NOT EXISTS idx_impersonation_consents_user_id ON impersonation_consents(user_id); +CREATE INDEX IF NOT EXISTS idx_impersonation_consents_active ON impersonation_consents(active); +CREATE INDEX IF NOT EXISTS idx_impersonation_consents_expires_at ON impersonation_consents(expires_at); +CREATE INDEX IF NOT EXISTS idx_impersonation_consents_user_active ON impersonation_consents(user_id, active); diff --git a/backend/database/migrations/064_add_systems_ui_url.sql b/backend/database/migrations/064_add_systems_ui_url.sql new file mode 100644 index 000000000..874a6e219 --- /dev/null +++ b/backend/database/migrations/064_add_systems_ui_url.sql @@ -0,0 +1,10 @@ +-- Migration 064: add systems.ui_url +-- +-- The address of the system's web interface, set by an admin when the default +-- one derived from the FQDN (https:///cluster-admin for NethServer, +-- https://:9090 for NethSecurity) does not open it. NULL means the +-- default, so it keeps following the FQDN of later inventories. + +ALTER TABLE systems ADD COLUMN IF NOT EXISTS ui_url VARCHAR(2048); + +COMMENT ON COLUMN systems.ui_url IS 'Custom address of the system web interface, set by an admin. NULL = the default derived from fqdn and type'; diff --git a/backend/database/migrations/064_add_systems_ui_url_rollback.sql b/backend/database/migrations/064_add_systems_ui_url_rollback.sql new file mode 100644 index 000000000..64a73f992 --- /dev/null +++ b/backend/database/migrations/064_add_systems_ui_url_rollback.sql @@ -0,0 +1,5 @@ +-- Rollback 064: drop systems.ui_url +-- +-- The custom addresses are lost: every system goes back to its default one. + +ALTER TABLE systems DROP COLUMN IF EXISTS ui_url; diff --git a/backend/database/schema.sql b/backend/database/schema.sql index 8ee06c0de..24e52bbf9 100644 --- a/backend/database/schema.sql +++ b/backend/database/schema.sql @@ -269,6 +269,7 @@ CREATE TABLE IF NOT EXISTS systems ( -- Metadata custom_data JSONB, -- Additional system metadata notes TEXT DEFAULT '', -- User notes/description + ui_url VARCHAR(2048), -- Custom web interface address (NULL = default from fqdn and type) created_by JSONB NOT NULL, -- {user_id, username, organization_id} who created the system -- Timestamps @@ -304,6 +305,7 @@ ALTER TABLE systems SET (autovacuum_analyze_scale_factor = 0.02); COMMENT ON TABLE systems IS 'NS8/NethSecurity systems registered for monitoring and inventory collection'; COMMENT ON COLUMN systems.type IS 'System type from inventory: ns8 (NethServer 8), nsec (NethSecurity)'; COMMENT ON COLUMN systems.status IS 'Heartbeat status: unknown (no data), active (heartbeat recent), inactive (heartbeat stale), unregistered (credentials refused), deleted'; +COMMENT ON COLUMN systems.ui_url IS 'Custom address of the system web interface, set by an admin. NULL = the default derived from fqdn and type'; COMMENT ON COLUMN systems.last_inventory_at IS 'Timestamp of last inventory received. NULL means no inventory received yet'; COMMENT ON COLUMN systems.suspended_at IS 'Suspension timestamp: NULL = active, non-NULL = suspended'; COMMENT ON COLUMN systems.suspended_by_org_id IS 'Organization that caused cascade suspension (for targeted reactivation)'; @@ -459,47 +461,6 @@ ALTER TABLE applications ADD CONSTRAINT chk_applications_org_type -- the default 10% scale factor, degrading the org count-query plans. See migration 038. ALTER TABLE applications SET (autovacuum_analyze_scale_factor = 0.02); --- ============================================================================= --- IMPERSONATION CONSENTS TABLE --- ============================================================================= --- User consents for allowing impersonation by Owner users --- Required for GDPR compliance and audit trail - -CREATE TABLE IF NOT EXISTS impersonation_consents ( - id VARCHAR(255) PRIMARY KEY, -- Unique consent ID - - -- User who gave consent - user_id VARCHAR(255) NOT NULL, -- FK to users table - - -- Consent validity - expires_at TIMESTAMP WITH TIME ZONE NOT NULL, -- When consent expires - max_duration_minutes INTEGER NOT NULL DEFAULT 60, -- Max impersonation session duration - - -- Status - active BOOLEAN NOT NULL DEFAULT TRUE, -- Whether consent is currently active - - -- Timestamps - created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW() -); - --- Table documentation -COMMENT ON TABLE impersonation_consents IS 'User consents for allowing impersonation by Owner users'; -COMMENT ON COLUMN impersonation_consents.user_id IS 'User who granted consent for impersonation'; -COMMENT ON COLUMN impersonation_consents.expires_at IS 'Timestamp when consent expires and must be renewed'; -COMMENT ON COLUMN impersonation_consents.max_duration_minutes IS 'Maximum duration of impersonation session in minutes'; -COMMENT ON COLUMN impersonation_consents.active IS 'Whether consent is currently active (can be revoked)'; - --- Foreign key constraint -ALTER TABLE impersonation_consents -ADD CONSTRAINT impersonation_consents_user_id_fkey -FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE; - --- Performance indexes -CREATE INDEX IF NOT EXISTS idx_impersonation_consents_user_id ON impersonation_consents(user_id); -CREATE INDEX IF NOT EXISTS idx_impersonation_consents_active ON impersonation_consents(active); -CREATE INDEX IF NOT EXISTS idx_impersonation_consents_expires_at ON impersonation_consents(expires_at); -CREATE INDEX IF NOT EXISTS idx_impersonation_consents_user_active ON impersonation_consents(user_id, active); - -- ============================================================================= -- IMPERSONATION AUDIT TABLE -- ============================================================================= @@ -520,7 +481,7 @@ CREATE TABLE IF NOT EXISTS impersonation_audit ( impersonated_name TEXT, -- Display name for display -- Action details - action_type VARCHAR(50) NOT NULL, -- start, end, api_call, error + action_type VARCHAR(50) NOT NULL, -- session_start, session_extended, session_end, api_call api_endpoint VARCHAR(255), -- API endpoint accessed (for api_call actions) http_method VARCHAR(10), -- HTTP method used request_data TEXT, -- Request body (sanitized) @@ -1460,3 +1421,22 @@ COMMENT ON COLUMN entitlement_seats.released_reason IS 'manual (freed by a user) COMMENT ON COLUMN entitlement_seats.released_by IS 'Actor snapshot of the user that freed the seat; NULL when collect freed it'; COMMENT ON COLUMN system_entitlements.renewal_stopped_at IS 'The shop must not renew this grant any more: it stays valid until valid_until. Cleared by an activation from a buyer that manages the system'; COMMENT ON COLUMN system_entitlements.renewal_stopped_reason IS 'Why the renewal stopped: customer_transferred, reseller_transferred or system_transferred (the buyer organization no longer manages what moved). NULL when renewing normally'; + +-- ============================================================================= +-- SYSTEM FAVORITES +-- ============================================================================= +-- Systems a user starred. Keyed on the Logto user ID rather than users(id): +-- the Owner account has no local users row. A destroyed system takes its rows +-- with it; a destroyed user is cleaned up by the backend. See migration 062. + +CREATE TABLE IF NOT EXISTS system_favorites ( + user_logto_id VARCHAR(255) NOT NULL, + system_id VARCHAR(255) NOT NULL REFERENCES systems(id) ON DELETE CASCADE, + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), + PRIMARY KEY (user_logto_id, system_id) +); + +CREATE INDEX IF NOT EXISTS idx_system_favorites_system_id ON system_favorites(system_id); + +COMMENT ON TABLE system_favorites IS 'Systems a user starred as favorites; personal, never shared with other users'; +COMMENT ON COLUMN system_favorites.user_logto_id IS 'Logto user ID of the user who starred the system (no FK: the Owner has no users row)'; diff --git a/backend/entities/local_system_favorites.go b/backend/entities/local_system_favorites.go new file mode 100644 index 000000000..ad9ae1c80 --- /dev/null +++ b/backend/entities/local_system_favorites.go @@ -0,0 +1,61 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package entities + +import ( + "database/sql" + "fmt" + + "github.com/nethesis/my/backend/database" +) + +// LocalSystemFavoriteRepository reads / writes system_favorites: the systems +// each user starred. Rows are keyed on the user's Logto ID. +type LocalSystemFavoriteRepository struct { + db *sql.DB +} + +func NewLocalSystemFavoriteRepository() *LocalSystemFavoriteRepository { + return &LocalSystemFavoriteRepository{db: database.DB} +} + +// Add stars the system for the user. Starring it again is a no-op. +func (r *LocalSystemFavoriteRepository) Add(userLogtoID, systemID string) error { + _, err := r.db.Exec( + `INSERT INTO system_favorites (user_logto_id, system_id) VALUES ($1, $2) + ON CONFLICT (user_logto_id, system_id) DO NOTHING`, + userLogtoID, systemID, + ) + if err != nil { + return fmt.Errorf("failed to add system favorite: %w", err) + } + return nil +} + +// Remove unstars the system for the user. Removing a missing row is a no-op. +func (r *LocalSystemFavoriteRepository) Remove(userLogtoID, systemID string) error { + _, err := r.db.Exec( + `DELETE FROM system_favorites WHERE user_logto_id = $1 AND system_id = $2`, + userLogtoID, systemID, + ) + if err != nil { + return fmt.Errorf("failed to remove system favorite: %w", err) + } + return nil +} + +// IsFavorite reports whether the user starred the system. +func (r *LocalSystemFavoriteRepository) IsFavorite(userLogtoID, systemID string) (bool, error) { + var exists bool + err := r.db.QueryRow( + `SELECT EXISTS (SELECT 1 FROM system_favorites WHERE user_logto_id = $1 AND system_id = $2)`, + userLogtoID, systemID, + ).Scan(&exists) + if err != nil { + return false, fmt.Errorf("failed to check system favorite: %w", err) + } + return exists, nil +} diff --git a/backend/entities/local_system_favorites_test.go b/backend/entities/local_system_favorites_test.go new file mode 100644 index 000000000..1f95cbc7d --- /dev/null +++ b/backend/entities/local_system_favorites_test.go @@ -0,0 +1,177 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package entities + +import ( + "context" + "database/sql/driver" + "errors" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/nethesis/my/backend/database" + "github.com/nethesis/my/backend/models" +) + +func setupSystemFavoritesMock(t *testing.T) (sqlmock.Sqlmock, func()) { + originalDB := database.DB + mockDB, mock, err := sqlmock.New() + require.NoError(t, err) + database.DB = mockDB + return mock, func() { + database.DB = originalDB + _ = mockDB.Close() + } +} + +func TestSystemFavoriteAdd_IsIdempotent(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectExec(`INSERT INTO system_favorites \(user_logto_id, system_id\) VALUES \(\$1, \$2\)\s+ON CONFLICT \(user_logto_id, system_id\) DO NOTHING`). + WithArgs("user-1", "sys-1"). + WillReturnResult(sqlmock.NewResult(0, 0)) + + require.NoError(t, NewLocalSystemFavoriteRepository().Add("user-1", "sys-1")) + assert.NoError(t, mock.ExpectationsWereMet()) +} + +func TestSystemFavoriteRemove_DeletesOnlyTheCallersRow(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectExec(`DELETE FROM system_favorites WHERE user_logto_id = \$1 AND system_id = \$2`). + WithArgs("user-1", "sys-1"). + WillReturnResult(sqlmock.NewResult(0, 1)) + + require.NoError(t, NewLocalSystemFavoriteRepository().Remove("user-1", "sys-1")) + assert.NoError(t, mock.ExpectationsWereMet()) +} + +func TestSystemFavoriteIsFavorite(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectQuery(`SELECT EXISTS \(SELECT 1 FROM system_favorites WHERE user_logto_id = \$1 AND system_id = \$2\)`). + WithArgs("user-1", "sys-1"). + WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) + + got, err := NewLocalSystemFavoriteRepository().IsFavorite("user-1", "sys-1") + require.NoError(t, err) + assert.True(t, got) + assert.NoError(t, mock.ExpectationsWereMet()) +} + +func TestSystemFavoriteAdd_WrapsError(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectExec(`INSERT INTO system_favorites`).WillReturnError(errors.New("fk violation")) + + err := NewLocalSystemFavoriteRepository().Add("user-1", "sys-1") + assert.ErrorContains(t, err, "failed to add system favorite") +} + +// captureSystemsListQuery runs the systems list as the Owner (no RBAC filter, +// so the only bound arguments are the favorites ones and paging), checks the +// arguments it bound and returns the SQL it sent. +func captureSystemsListQuery(t *testing.T, sortBy, sortDirection string, f models.SystemListFilters, wantArgs ...driver.Value) string { + t.Helper() + var gotSQL string + matcher := sqlmock.QueryMatcherFunc(func(_ string, actual string) error { + gotSQL = actual + return nil + }) + mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(matcher)) + require.NoError(t, err) + defer func() { _ = mockDB.Close() }() + + mock.ExpectQuery("").WithArgs(wantArgs...).WillReturnError(errors.New("stop")) + + repo := &LocalSystemRepository{db: mockDB} + _, _, err = repo.ListByCreatedByOrganizations(context.Background(), nil, 1, 50, "", sortBy, sortDirection, f) + require.ErrorContains(t, err, "stop") + return gotSQL +} + +func TestListSystems_FavoritesJoinIsScopedToTheCaller(t *testing.T) { + sql := captureSystemsListQuery(t, "", "asc", models.SystemListFilters{FavoritesOf: "user-1"}, "user-1", 50, 0) + + assert.Contains(t, sql, "LEFT JOIN system_favorites sf ON sf.system_id = s.id AND sf.user_logto_id = $1") + assert.Contains(t, sql, "(sf.system_id IS NOT NULL) as is_favorite") + assert.NotContains(t, sql, "AND (sf.system_id IS NOT NULL)") +} + +func TestListSystems_WithoutCallerNothingIsStarred(t *testing.T) { + sql := captureSystemsListQuery(t, "", "asc", models.SystemListFilters{}, 50, 0) + + assert.NotContains(t, sql, "system_favorites") + assert.Contains(t, sql, "FALSE as is_favorite") +} + +func TestListSystems_FavoritesOnlyFilter(t *testing.T) { + sql := captureSystemsListQuery(t, "", "asc", models.SystemListFilters{FavoritesOf: "user-1", FavoritesOnly: true}, "user-1", 50, 0) + + assert.Contains(t, sql, "s.deleted_at IS NULL AND (sf.system_id IS NOT NULL)") +} + +func TestListSystems_FavoritesOnlyWithoutCallerMatchesNothing(t *testing.T) { + sql := captureSystemsListQuery(t, "", "asc", models.SystemListFilters{FavoritesOnly: true}, 50, 0) + + assert.Contains(t, sql, "s.deleted_at IS NULL AND FALSE") +} + +func TestListSystems_SortByFavoriteAscendingListsFavoritesFirst(t *testing.T) { + sql := captureSystemsListQuery(t, "favorite", "asc", models.SystemListFilters{FavoritesOf: "user-1"}, "user-1", 50, 0) + + assert.Contains(t, sql, "ORDER BY (sf.system_id IS NULL) ASC, LOWER(s.name), s.id") +} + +func TestListSystems_SortByFavoriteDescendingListsFavoritesLast(t *testing.T) { + sql := captureSystemsListQuery(t, "favorite", "desc", models.SystemListFilters{FavoritesOf: "user-1"}, "user-1", 50, 0) + + assert.Contains(t, sql, "ORDER BY (sf.system_id IS NULL) DESC, LOWER(s.name), s.id") +} + +func TestUserHardDelete_RemovesTheUsersFavorites(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectQuery(`WITH deleted AS \(\s+DELETE FROM users WHERE logto_id = \$1 RETURNING logto_id\s+\), favorites AS \(\s+DELETE FROM system_favorites WHERE user_logto_id IN \(SELECT logto_id FROM deleted\)\s+\)\s+SELECT COUNT\(\*\) FROM deleted`). + WithArgs("user-1"). + WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + + require.NoError(t, NewLocalUserRepository().HardDelete("user-1")) + assert.NoError(t, mock.ExpectationsWereMet()) +} + +func TestUserHardDelete_UnknownUser(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectQuery(`WITH deleted AS`). + WithArgs("missing"). + WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0)) + + assert.EqualError(t, NewLocalUserRepository().HardDelete("missing"), "user not found") +} + +func TestUserHardDeleteByOrgID_RemovesTheirFavorites(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectQuery(`WITH deleted AS \(\s+DELETE FROM users WHERE organization_id = \$1 RETURNING logto_id\s+\), favorites AS \(\s+DELETE FROM system_favorites\s+WHERE user_logto_id IN \(SELECT logto_id FROM deleted WHERE logto_id IS NOT NULL\)\s+\)\s+SELECT logto_id FROM deleted WHERE logto_id IS NOT NULL`). + WithArgs("org-1"). + WillReturnRows(sqlmock.NewRows([]string{"logto_id"}).AddRow("user-1").AddRow("user-2")) + + ids, err := NewLocalUserRepository().HardDeleteByOrgID("org-1") + require.NoError(t, err) + assert.Equal(t, []string{"user-1", "user-2"}, ids) + assert.NoError(t, mock.ExpectationsWereMet()) +} diff --git a/backend/entities/local_systems.go b/backend/entities/local_systems.go index b630f3aaf..6c0e01763 100644 --- a/backend/entities/local_systems.go +++ b/backend/entities/local_systems.go @@ -66,7 +66,7 @@ func (r *LocalSystemRepository) getByID(id string, includeDeleted bool) (*models // idx_inventory_records_system_id_created_at. query := ` SELECT s.id, s.name, s.type, s.status, s.fqdn, s.ipv4_address, s.ipv6_address, s.version, - s.system_key, s.organization_id, s.custom_data, s.notes, s.created_at, s.updated_at, s.created_by, s.registered_at, s.unregistered_at, s.suspended_at, s.suspended_by_org_id, h.last_heartbeat, s.last_inventory_at, s.update_available, + s.system_key, s.organization_id, s.custom_data, s.notes, s.ui_url, s.created_at, s.updated_at, s.created_by, s.registered_at, s.unregistered_at, s.suspended_at, s.suspended_by_org_id, h.last_heartbeat, s.last_inventory_at, s.update_available, h.created_at as first_heartbeat, (SELECT MIN(ir.created_at) FROM inventory_records ir WHERE ir.system_id = s.id) as first_inventory, COALESCE(uo.name, 'Owner') as organization_name, @@ -89,7 +89,7 @@ func (r *LocalSystemRepository) getByID(id string, includeDeleted bool) (*models err := r.db.QueryRow(query, id).Scan( &system.ID, &system.Name, &system.Type, &system.Status, &fqdn, &ipv4Address, &ipv6Address, &version, &system.SystemKey, &system.Organization.LogtoID, - &customDataJSON, &system.Notes, &system.CreatedAt, &system.UpdatedAt, &createdByJSON, ®isteredAt, &unregisteredAt, &suspendedAt, &suspendedByOrgID, &lastHeartbeat, &lastInventory, &system.UpdateAvailable, + &customDataJSON, &system.Notes, &system.UIURL, &system.CreatedAt, &system.UpdatedAt, &createdByJSON, ®isteredAt, &unregisteredAt, &suspendedAt, &suspendedByOrgID, &lastHeartbeat, &lastInventory, &system.UpdateAvailable, &firstHeartbeat, &firstInventory, &organizationName, &organizationType, &organizationDBID, ) @@ -420,6 +420,22 @@ func (r *LocalSystemRepository) ListByCreatedByOrganizations(ctx context.Context args = append(args, addonArgs...) } + // The caller's favorites: a LEFT JOIN on their own rows only, so it adds + // no row and never widens the RBAC scope built above. + favoriteJoin := "" + favoriteExpr := "FALSE" + // sorts favorites first in ascending order, the sort's default direction + favoriteSortExpr := "TRUE" + if f.FavoritesOf != "" { + args = append(args, f.FavoritesOf) + favoriteJoin = fmt.Sprintf("LEFT JOIN system_favorites sf ON sf.system_id = s.id AND sf.user_logto_id = $%d", len(args)) + favoriteExpr = "(sf.system_id IS NOT NULL)" + favoriteSortExpr = "(sf.system_id IS NULL)" + } + if f.FavoritesOnly { + whereClause += " AND " + favoriteExpr + } + // Build ORDER BY clause orderBy := "s.created_at DESC" if sortBy != "" { @@ -435,6 +451,7 @@ func (r *LocalSystemRepository) ListByCreatedByOrganizations(ctx context.Context "creator_name": "LOWER(s.created_by ->> 'name')", "organization_name": "LOWER(uo.name)", "managed_by": systemManagedBySortExpression, + "favorite": favoriteSortExpr, } if column, exists := columnMap[sortBy]; exists { @@ -443,9 +460,10 @@ func (r *LocalSystemRepository) ListByCreatedByOrganizations(ctx context.Context direction = "DESC" } orderBy = fmt.Sprintf("%s %s", column, direction) - // many systems share one manager: fall back to their name, so - // OFFSET paging does not repeat or skip a row across a tie - if sortBy == "managed_by" { + // many systems share one manager, or one favorite flag: fall + // back to their name, so OFFSET paging does not repeat or skip + // a row across a tie + if sortBy == "managed_by" || sortBy == "favorite" { orderBy += ", LOWER(s.name), s.id" } } @@ -454,18 +472,20 @@ func (r *LocalSystemRepository) ListByCreatedByOrganizations(ctx context.Context // Single query with COUNT(*) OVER() to get total count + paginated results query := fmt.Sprintf(` SELECT s.id, s.name, s.type, s.status, s.fqdn, s.ipv4_address, s.ipv6_address, s.version, - s.system_key, s.organization_id, s.custom_data, s.notes, s.created_at, s.updated_at, s.deleted_at, s.registered_at, s.unregistered_at, s.suspended_at, s.suspended_by_org_id, s.created_by, h.last_heartbeat, s.last_inventory_at, s.update_available, + s.system_key, s.organization_id, s.custom_data, s.notes, s.ui_url, s.created_at, s.updated_at, s.deleted_at, s.registered_at, s.unregistered_at, s.suspended_at, s.suspended_by_org_id, s.created_by, h.last_heartbeat, s.last_inventory_at, s.update_available, COALESCE(uo.name, 'Owner') as organization_name, COALESCE(uo.org_type, 'owner') as organization_type, COALESCE(uo.db_id, '') as organization_db_id, + %s as is_favorite, COUNT(*) OVER() as total_count FROM systems s LEFT JOIN system_heartbeats h ON s.id = h.system_id LEFT JOIN unified_organizations uo ON s.organization_id = uo.logto_id + %s WHERE %s ORDER BY %s LIMIT $%d OFFSET $%d - `, whereClause, orderBy, len(args)+1, len(args)+2) + `, favoriteExpr, favoriteJoin, whereClause, orderBy, len(args)+1, len(args)+2) listArgs := make([]interface{}, len(args)+2) copy(listArgs, args) @@ -491,8 +511,9 @@ func (r *LocalSystemRepository) ListByCreatedByOrganizations(ctx context.Context err := rows.Scan( &system.ID, &system.Name, &system.Type, &system.Status, &fqdn, &ipv4Address, &ipv6Address, &version, &system.SystemKey, &system.Organization.LogtoID, - &customDataJSON, &system.Notes, &system.CreatedAt, &system.UpdatedAt, &deletedAt, ®isteredAt, &unregisteredAt, &suspendedAt, &suspendedByOrgID, &createdByJSON, &lastHeartbeat, &lastInventory, &system.UpdateAvailable, + &customDataJSON, &system.Notes, &system.UIURL, &system.CreatedAt, &system.UpdatedAt, &deletedAt, ®isteredAt, &unregisteredAt, &suspendedAt, &suspendedByOrgID, &createdByJSON, &lastHeartbeat, &lastInventory, &system.UpdateAvailable, &organizationName, &organizationType, &organizationDBID, + &system.IsFavorite, &totalCount, ) if err != nil { diff --git a/backend/entities/local_users.go b/backend/entities/local_users.go index 48075f483..eba4afe95 100644 --- a/backend/entities/local_users.go +++ b/backend/entities/local_users.go @@ -1525,35 +1525,43 @@ func (r *LocalUserRepository) Restore(logtoID string) error { return nil } -// HardDelete permanently deletes a user by logto_id +// HardDelete permanently deletes a user by logto_id, together with the +// systems the user starred: system_favorites has no foreign key to users +// (the Owner has no users row), so the same statement removes them. func (r *LocalUserRepository) HardDelete(logtoID string) error { - query := `DELETE FROM users WHERE logto_id = $1` - - result, err := r.db.Exec(query, logtoID) - if err != nil { + query := `WITH deleted AS ( + DELETE FROM users WHERE logto_id = $1 RETURNING logto_id + ), favorites AS ( + DELETE FROM system_favorites WHERE user_logto_id IN (SELECT logto_id FROM deleted) + ) + SELECT COUNT(*) FROM deleted` + + var deleted int + if err := r.db.QueryRow(query, logtoID).Scan(&deleted); err != nil { return fmt.Errorf("failed to hard-delete user: %w", err) } - rowsAffected, err := result.RowsAffected() - if err != nil { - return fmt.Errorf("failed to get rows affected: %w", err) - } - - if rowsAffected == 0 { + if deleted == 0 { return fmt.Errorf("user not found") } return nil } -// HardDeleteByOrgID permanently deletes all users belonging to an organization +// HardDeleteByOrgID permanently deletes all users belonging to an organization, +// together with the systems they starred (see HardDelete). // Returns the logto_ids of deleted users for Logto cleanup func (r *LocalUserRepository) HardDeleteByOrgID(orgLogtoID string) ([]string, error) { - // First get the logto_ids of users that will be deleted (for Logto cleanup) - selectQuery := `SELECT logto_id FROM users WHERE organization_id = $1 AND logto_id IS NOT NULL` - rows, err := r.db.Query(selectQuery, orgLogtoID) + query := `WITH deleted AS ( + DELETE FROM users WHERE organization_id = $1 RETURNING logto_id + ), favorites AS ( + DELETE FROM system_favorites + WHERE user_logto_id IN (SELECT logto_id FROM deleted WHERE logto_id IS NOT NULL) + ) + SELECT logto_id FROM deleted WHERE logto_id IS NOT NULL` + rows, err := r.db.Query(query, orgLogtoID) if err != nil { - return nil, fmt.Errorf("failed to query users for hard-delete: %w", err) + return nil, fmt.Errorf("failed to hard-delete users by org: %w", err) } defer func() { _ = rows.Close() }() @@ -1569,13 +1577,6 @@ func (r *LocalUserRepository) HardDeleteByOrgID(orgLogtoID string) ([]string, er return nil, fmt.Errorf("error iterating users: %w", err) } - // Hard-delete all users for this org - deleteQuery := `DELETE FROM users WHERE organization_id = $1` - _, err = r.db.Exec(deleteQuery, orgLogtoID) - if err != nil { - return nil, fmt.Errorf("failed to hard-delete users by org: %w", err) - } - return logtoIDs, nil } diff --git a/backend/main.go b/backend/main.go index e4d9c986d..c6c5ad311 100644 --- a/backend/main.go +++ b/backend/main.go @@ -199,21 +199,13 @@ func main() { // Authentication endpoints customAuth.POST("/auth/logout", middleware.RejectAPIKey(), middleware.DisableOnImpersonate(), methods.Logout) - // Consent-based impersonation endpoints (no audit to avoid recursion) + // Impersonation endpoints (no audit to avoid recursion) impersonateGroup := customAuth.Group("/impersonate", middleware.RejectAPIKey()) { - // Consent management endpoints - // Consent belongs to the account itself: with an impersonation token - // these would act as the target, letting the impersonator grant (or - // renew) the very consent the feature hinges on. - impersonateGroup.POST("/consent", middleware.DisableOnImpersonate(), methods.EnableImpersonationConsent) - impersonateGroup.DELETE("/consent", middleware.DisableOnImpersonate(), methods.DisableImpersonationConsent) - impersonateGroup.GET("/consent", middleware.DisableOnImpersonate(), methods.GetImpersonationConsentStatus) - - // Impersonation endpoints impersonateGroup.GET("/status", methods.GetImpersonationStatus) - impersonateGroup.POST("", middleware.RequirePermission("impersonate:users"), methods.ImpersonateUserWithConsent) // Only users with impersonate:users permission + impersonateGroup.POST("", middleware.RequirePermission("impersonate:users"), methods.ImpersonateUser) // Only users with impersonate:users permission impersonateGroup.DELETE("", methods.ExitImpersonationWithAudit) + impersonateGroup.POST("/extend", methods.ExtendImpersonation) // impersonation token only; the handler checks the impersonator // Session management endpoints impersonateGroup.GET("/sessions", middleware.DisableOnImpersonate(), methods.GetImpersonationSessions) @@ -248,6 +240,20 @@ func main() { // =========================================== // SYSTEMS - resource-based permission validation (read:systems for GET, manage:systems for POST/PUT/DELETE) // =========================================== + // Favorites: personal stars on a system. Starring changes nothing on the + // system, so read:systems is enough for every verb. Interactive sessions + // only: an API key is for automation, and an impersonator must not leave + // stars in the target's account. + systemFavoritesGroup := customAuthWithAudit.Group("/systems/:id/favorite", + middleware.RejectAPIKey(), + middleware.DisableOnImpersonate(), + middleware.RequirePermission("read:systems"), + ) + { + systemFavoritesGroup.PUT("", methods.AddSystemFavorite) + systemFavoritesGroup.DELETE("", methods.RemoveSystemFavorite) + } + systemsGroup := customAuthWithAudit.Group("/systems", middleware.RequireResourcePermission("systems")) { // CRUD operations @@ -261,7 +267,7 @@ func main() { systemsGroup.GET("/:id/transfer", middleware.RequirePermission("manage:systems"), methods.GetSystemTransferPreview) // Restore and destroy endpoints - systemsGroup.PATCH("/:id/restore", methods.RestoreSystem) // Restore soft-deleted system (manage:systems required) + systemsGroup.PATCH("/:id/restore", middleware.RequireOrgRole(models.OwnerOrgRole), methods.RestoreSystem) // Restore soft-deleted system (manage:systems required) systemsGroup.DELETE("/:id/destroy", middleware.RequirePermission("destroy:systems"), methods.DestroySystem) // Permanently delete system (destroy:systems required) // Suspend and reactivate endpoints @@ -474,7 +480,7 @@ func main() { distributorsGroup.DELETE("/:id", methods.DeleteDistributor) // Soft-delete distributor (manage:distributors required) // Restore and destroy endpoints (cascade to users and systems) - distributorsGroup.PATCH("/:id/restore", methods.RestoreDistributor) // Restore soft-deleted distributor and cascade-deleted users/systems + distributorsGroup.PATCH("/:id/restore", middleware.RequireOrgRole(models.OwnerOrgRole), methods.RestoreDistributor) // Restore soft-deleted distributor and cascade-deleted users/systems distributorsGroup.DELETE("/:id/destroy", middleware.RequirePermission("destroy:distributors"), methods.DestroyDistributor) // Permanently delete distributor and all hierarchy (destroy:distributors required) // Suspend and reactivate endpoints (cascade to users) @@ -509,7 +515,7 @@ func main() { resellersGroup.DELETE("/:id", methods.DeleteReseller) // Soft-delete reseller (manage:resellers required) // Restore and destroy endpoints (cascade to users and systems) - resellersGroup.PATCH("/:id/restore", methods.RestoreReseller) // Restore soft-deleted reseller and cascade-deleted users/systems + resellersGroup.PATCH("/:id/restore", middleware.RequireOrgRole(models.OwnerOrgRole), methods.RestoreReseller) // Restore soft-deleted reseller and cascade-deleted users/systems resellersGroup.DELETE("/:id/destroy", middleware.RequirePermission("destroy:resellers"), methods.DestroyReseller) // Permanently delete reseller and all hierarchy (destroy:resellers required) // Suspend and reactivate endpoints (cascade to users) @@ -553,7 +559,7 @@ func main() { customersGroup.DELETE("/:id", methods.DeleteCustomer) // Soft-delete customer (manage:customers required) // Restore and destroy endpoints (cascade to users and systems) - customersGroup.PATCH("/:id/restore", methods.RestoreCustomer) // Restore soft-deleted customer and cascade-deleted users/systems + customersGroup.PATCH("/:id/restore", middleware.RequireOrgRole(models.OwnerOrgRole), methods.RestoreCustomer) // Restore soft-deleted customer and cascade-deleted users/systems customersGroup.DELETE("/:id/destroy", middleware.RequirePermission("destroy:customers"), methods.DestroyCustomer) // Permanently delete customer and all hierarchy (destroy:customers required) // Suspend and reactivate endpoints (cascade to users) @@ -593,7 +599,7 @@ func main() { usersGroup.DELETE("/:id", middleware.PreventSelfModification(), methods.DeleteUser) // Soft-delete user (manage:users required, prevent self-modification) // Restore and destroy endpoints - usersGroup.PATCH("/:id/restore", middleware.PreventSelfModification(), methods.RestoreUser) // Restore soft-deleted user (manage:users required, prevent self-modification) + usersGroup.PATCH("/:id/restore", middleware.RequireOrgRole(models.OwnerOrgRole), middleware.PreventSelfModification(), methods.RestoreUser) // Restore soft-deleted user (manage:users required, prevent self-modification) usersGroup.DELETE("/:id/destroy", middleware.RequirePermission("destroy:users"), middleware.PreventSelfModification(), methods.DestroyUser) // Permanently delete user (destroy:users required, prevent self-modification) // Suspend and reactivate endpoints (manage:users required, prevent self-modification) diff --git a/backend/methods/customers.go b/backend/methods/customers.go index 705201c98..6e3eb89b3 100644 --- a/backend/methods/customers.go +++ b/backend/methods/customers.go @@ -197,6 +197,9 @@ func GetCustomers(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } createdBy := c.QueryArray("created_by") ownedBy := c.QueryArray("organization_id") diff --git a/backend/methods/customers_export.go b/backend/methods/customers_export.go index 9d64995d1..fb3f48ea3 100644 --- a/backend/methods/customers_export.go +++ b/backend/methods/customers_export.go @@ -47,6 +47,9 @@ func ExportCustomers(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } // For export, we don't use pagination - get all matching customers (with limit) sortBy := c.DefaultQuery("sort_by", "created_at") diff --git a/backend/methods/deleted_objects.go b/backend/methods/deleted_objects.go new file mode 100644 index 000000000..75ecd55e6 --- /dev/null +++ b/backend/methods/deleted_objects.go @@ -0,0 +1,33 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package methods + +import ( + "net/http" + "strings" + + "github.com/gin-gonic/gin" + + "github.com/nethesis/my/backend/models" + "github.com/nethesis/my/backend/response" +) + +// rejectDeletedStatusOutsideOwnerOrg refuses a listing or an export filtered +// on soft-deleted objects to a caller outside the Owner organization. Seeing +// them, and restoring them, belongs to the Owner organization: for everyone +// else a Delete is final. It reports whether it wrote the refusal. +func rejectDeletedStatusOutsideOwnerOrg(c *gin.Context, orgRole string, statuses []string) bool { + if models.IsGlobalOrgRole(orgRole) { + return false + } + for _, status := range statuses { + if strings.EqualFold(status, "deleted") { + c.JSON(http.StatusForbidden, response.Forbidden("deleted objects are visible to the owner organization only", nil)) + return true + } + } + return false +} diff --git a/backend/methods/deleted_objects_unit_test.go b/backend/methods/deleted_objects_unit_test.go new file mode 100644 index 000000000..2acaa673d --- /dev/null +++ b/backend/methods/deleted_objects_unit_test.go @@ -0,0 +1,49 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package methods + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" +) + +func TestRejectDeletedStatusOutsideOwnerOrg(t *testing.T) { + gin.SetMode(gin.TestMode) + + tests := []struct { + name string + orgRole string + statuses []string + rejected bool + }{ + {"owner organization asks for deleted", "owner", []string{"deleted"}, false}, + {"owner organization in another case", "Owner", []string{"enabled", "deleted"}, false}, + {"distributor asks for deleted", "distributor", []string{"deleted"}, true}, + {"reseller asks for deleted among others", "reseller", []string{"enabled", "DELETED"}, true}, + {"customer asks for active systems", "customer", []string{"active", "suspended"}, false}, + {"customer asks for no status", "customer", nil, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + + rejected := rejectDeletedStatusOutsideOwnerOrg(c, tt.orgRole, tt.statuses) + + assert.Equal(t, tt.rejected, rejected) + if tt.rejected { + assert.Equal(t, http.StatusForbidden, w.Code) + } else { + assert.False(t, c.Writer.Written()) + } + }) + } +} diff --git a/backend/methods/distributors.go b/backend/methods/distributors.go index d54db334c..7cee9a0c2 100644 --- a/backend/methods/distributors.go +++ b/backend/methods/distributors.go @@ -164,6 +164,9 @@ func GetDistributors(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } createdBy := c.QueryArray("created_by") // Create service diff --git a/backend/methods/distributors_export.go b/backend/methods/distributors_export.go index 550557a37..e2a43e40e 100644 --- a/backend/methods/distributors_export.go +++ b/backend/methods/distributors_export.go @@ -47,6 +47,9 @@ func ExportDistributors(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } // For export, we don't use pagination - get all matching distributors (with limit) sortBy := c.DefaultQuery("sort_by", "created_at") diff --git a/backend/methods/impersonate.go b/backend/methods/impersonate.go index bc2c410e7..baa54bb98 100644 --- a/backend/methods/impersonate.go +++ b/backend/methods/impersonate.go @@ -29,171 +29,14 @@ import ( ) // ============================================================================= -// CONSENT MANAGEMENT ENDPOINTS +// IMPERSONATION ENDPOINTS // ============================================================================= -// EnableImpersonationConsent allows a user to enable consent for being impersonated -// POST /api/impersonate/consent -func EnableImpersonationConsent(c *gin.Context) { - // Get current user context - user, ok := helpers.GetUserFromContext(c) - if !ok { - return - } - - // Parse request body - var req models.EnableConsentRequest - if err := c.ShouldBindJSON(&req); err != nil { - logger.RequestLogger(c, "impersonate").Warn(). - Err(err). - Str("operation", "enable_consent_parse_request"). - Str("user_id", user.ID). - Msg("Invalid enable consent request JSON") - - c.JSON(http.StatusBadRequest, response.BadRequest( - "invalid request body: "+err.Error(), - nil, - )) - return - } - - // Set default duration if not provided - if req.DurationHours == 0 { - req.DurationHours = 1 // Default to 1 hour - } - - // Create impersonation service - impersonationService := local.NewImpersonationService() - - // Enable consent - consent, err := impersonationService.EnableConsent(user.ID, req.DurationHours) - if err != nil { - logger.RequestLogger(c, "impersonate").Error(). - Err(err). - Str("operation", "enable_consent"). - Str("user_id", user.ID). - Int("duration_hours", req.DurationHours). - Msg("Failed to enable impersonation consent") - - c.JSON(http.StatusInternalServerError, response.InternalServerError( - "failed to enable consent: "+err.Error(), - nil, - )) - return - } - - // Log consent enabling - logger.RequestLogger(c, "impersonate").Info(). - Str("operation", "consent_enabled"). - Str("user_id", user.ID). - Str("username", user.Username). - Str("consent_id", consent.ID). - Int("duration_hours", req.DurationHours). - Time("expires_at", consent.ExpiresAt). - Msg("User enabled impersonation consent") - - c.JSON(http.StatusOK, response.OK( - "impersonation consent enabled successfully", - gin.H{ - "consent": consent, - }, - )) -} - -// DisableImpersonationConsent allows a user to disable consent for being impersonated -// DELETE /api/impersonate/consent -func DisableImpersonationConsent(c *gin.Context) { - // Get current user context - user, ok := helpers.GetUserFromContext(c) - if !ok { - return - } - - // Create impersonation service - impersonationService := local.NewImpersonationService() - - // Disable consent - err := impersonationService.DisableConsent(user.ID) - if err != nil { - logger.RequestLogger(c, "impersonate").Error(). - Err(err). - Str("operation", "disable_consent"). - Str("user_id", user.ID). - Msg("Failed to disable impersonation consent") - - c.JSON(http.StatusInternalServerError, response.InternalServerError( - "failed to disable consent: "+err.Error(), - nil, - )) - return - } - - // Log consent disabling - logger.RequestLogger(c, "impersonate").Info(). - Str("operation", "consent_disabled"). - Str("user_id", user.ID). - Str("username", user.Username). - Msg("User disabled impersonation consent") - - c.JSON(http.StatusOK, response.OK( - "impersonation consent disabled successfully", - nil, - )) -} - -// GetImpersonationConsentStatus gets the current consent status for the user -// GET /api/impersonate/consent -func GetImpersonationConsentStatus(c *gin.Context) { - // Get current user context - user, ok := helpers.GetUserFromContext(c) - if !ok { - return - } - - // Create impersonation service - impersonationService := local.NewImpersonationService() - - // Get consent status - consent, err := impersonationService.GetConsentStatus(user.ID) - if err != nil { - logger.RequestLogger(c, "impersonate").Error(). - Err(err). - Str("operation", "get_consent_status"). - Str("user_id", user.ID). - Msg("Failed to get impersonation consent status") - - c.JSON(http.StatusInternalServerError, response.InternalServerError( - "failed to get consent status: "+err.Error(), - nil, - )) - return - } - - if consent == nil { - c.JSON(http.StatusOK, response.OK( - "no active impersonation consent", - gin.H{ - "consent": nil, - }, - )) - return - } - - c.JSON(http.StatusOK, response.OK( - "consent status retrieved successfully", - gin.H{ - "consent": consent, - }, - )) -} - -// ============================================================================= -// IMPERSONATION ENDPOINTS (Updated with Consent Validation) -// ============================================================================= - -// ImpersonateUserWithConsent allows owner users to impersonate another user (only if consent is active) +// ImpersonateUser lets a user holding impersonate:users act as another user, +// for configuration.Config.ImpersonationSessionDuration. The target's +// consent is not required: every session is audited instead. // POST /api/impersonate -func ImpersonateUserWithConsent(c *gin.Context) { +func ImpersonateUser(c *gin.Context) { // Get current user context user, ok := helpers.GetUserFromContext(c) if !ok { @@ -337,79 +180,13 @@ func ImpersonateUserWithConsent(c *gin.Context) { // Create impersonation service impersonationService := local.NewImpersonationService() - // Check if target user has active consent (using database UUID for consent table FK) - canBeImpersonated, err := impersonationService.CanBeImpersonated(targetUser.ID) - if err != nil { - logger.RequestLogger(c, "impersonate").Error(). - Err(err). - Str("operation", "check_consent"). - Str("user_id", user.ID). - Str("target_user_id", targetUser.ID). - Msg("Failed to check impersonation consent") - - c.JSON(http.StatusInternalServerError, response.InternalServerError( - "failed to check impersonation consent: "+err.Error(), - nil, - )) - return - } - - if !canBeImpersonated { - logger.RequestLogger(c, "impersonate").Warn(). - Str("operation", "impersonate_no_consent"). - Str("user_id", user.ID). - Str("target_user_id", targetUser.ID). - Msg("Attempted to impersonate user without active consent") - - c.JSON(http.StatusForbidden, response.Forbidden( - "target user has not provided consent for impersonation or consent has expired", - nil, - )) - return - } - - // Get consent details to determine token duration (using database UUID) - consent, err := impersonationService.GetConsentStatus(targetUser.ID) - if err != nil || consent == nil { - logger.RequestLogger(c, "impersonate").Error(). - Err(err). - Str("operation", "get_consent_details"). - Str("user_id", user.ID). - Str("target_user_id", targetUser.ID). - Msg("Failed to get consent details for impersonation") - - c.JSON(http.StatusInternalServerError, response.InternalServerError( - "failed to get consent details: "+err.Error(), - nil, - )) - return - } - - // Calculate remaining duration from consent expiration time - // This ensures that multiple impersonation sessions within the same consent period - // all expire at the original consent expiration time, not extended durations - remainingDuration := time.Until(consent.ExpiresAt) - if remainingDuration <= 0 { - // Consent has expired (shouldn't happen due to earlier CanBeImpersonated check, but safety check) - logger.RequestLogger(c, "impersonate").Warn(). - Str("operation", "consent_expired_during_impersonation"). - Str("user_id", user.ID). - Str("target_user_id", targetUser.ID). - Time("consent_expires_at", consent.ExpiresAt). - Msg("Consent expired between validation and token generation") - - c.JSON(http.StatusForbidden, response.Forbidden( - "consent has expired", - nil, - )) - return - } + sessionDuration := configuration.Config.ImpersonationSessionDuration + expiresAt := time.Now().Add(sessionDuration) // Generate session ID for audit tracking sessionID := uuid.New().String() - // Generate impersonation token with remaining duration from consent - impersonationToken, err := jwt.GenerateImpersonationTokenWithDuration(*targetUser, *user, sessionID, remainingDuration) + impersonationToken, err := jwt.GenerateImpersonationTokenWithDuration(*targetUser, *user, sessionID, sessionDuration) if err != nil { logger.RequestLogger(c, "impersonate").Error(). Err(err). @@ -428,7 +205,7 @@ func ImpersonateUserWithConsent(c *gin.Context) { // Create active session in Redis to prevent duplicate impersonation // Store logto_id as ImpersonatedUserID for consistency with GetUserForImpersonation - err = sessionManager.CreateSession(user.ID, sessionID, *targetUser.LogtoID, remainingDuration) + err = sessionManager.CreateSession(user.ID, sessionID, *targetUser.LogtoID, sessionDuration) if err != nil { logger.RequestLogger(c, "impersonate").Warn(). Err(err). @@ -463,7 +240,7 @@ func ImpersonateUserWithConsent(c *gin.Context) { // Log successful impersonation start logger.RequestLogger(c, "impersonate").Info(). - Str("operation", "impersonation_started_with_consent"). + Str("operation", "impersonation_started"). Str("impersonator_user_id", user.ID). Str("impersonator_username", user.Username). Str("impersonated_user_id", targetUser.ID). @@ -471,17 +248,17 @@ func ImpersonateUserWithConsent(c *gin.Context) { Str("session_id", sessionID). Str("impersonator_org", user.OrganizationID). Str("impersonated_org", targetUser.OrganizationID). - Int64("remaining_duration_seconds", int64(remainingDuration.Seconds())). - Time("consent_expires_at", consent.ExpiresAt). - Msg("User impersonation started successfully with consent") + Int64("duration_seconds", int64(sessionDuration.Seconds())). + Time("expires_at", expiresAt). + Msg("User impersonation started successfully") c.JSON(http.StatusOK, response.OK( "impersonation started successfully", gin.H{ "is_impersonating": true, "token": impersonationToken, - "expires_in": int64(remainingDuration.Seconds()), // Remaining seconds until consent expires - "expires_at": consent.ExpiresAt, // ISO timestamp when consent expires + "expires_in": int64(sessionDuration.Seconds()), + "expires_at": expiresAt, "session_id": sessionID, "impersonated_user": targetUser, "impersonator": user, @@ -489,6 +266,150 @@ func ImpersonateUserWithConsent(c *gin.Context) { )) } +// ExtendImpersonation restarts the current impersonation session for a full +// configuration.Config.ImpersonationSessionDuration: same session, new token. +// Called with the impersonation token itself; API keys never reach it +// (RejectAPIKey on the group). The impersonator is re-read from its current +// state, so a user who lost impersonate:users cannot keep a session alive; the +// new token still names the impersonator as the session was started, since +// its id keys the session in Redis and the audit trail. +// POST /api/impersonate/extend +func ExtendImpersonation(c *gin.Context) { + isImpersonated, exists := c.Get("is_impersonated") + if !exists || !isImpersonated.(bool) { + c.JSON(http.StatusBadRequest, response.BadRequest("not currently impersonating a user", nil)) + return + } + + sessionIDStr, _ := c.Get("session_id") + sessionID, _ := sessionIDStr.(string) + impersonator, _ := c.Get("impersonated_by") + impersonatorUser, ok := impersonator.(*models.User) + impersonatedUser, hasTarget := helpers.GetUserFromContext(c) + if !hasTarget { + return // GetUserFromContext already answered + } + if !ok || impersonatorUser == nil || sessionID == "" || + impersonatorUser.LogtoID == nil || impersonatedUser.LogtoID == nil { + c.JSON(http.StatusInternalServerError, response.InternalServerError("invalid impersonation state", nil)) + return + } + + freshImpersonator, err := local.ResolveUserByLogtoID(*impersonatorUser.LogtoID) + if err != nil { + if errors.Is(err, local.ErrUserInactive) { + c.JSON(http.StatusUnauthorized, response.Unauthorized("account suspended or deleted", nil)) + return + } + logger.RequestLogger(c, "impersonate").Error(). + Err(err). + Str("operation", "extend_impersonation_resolve_impersonator"). + Str("impersonator_user_id", impersonatorUser.ID). + Msg("Failed to resolve impersonator for extending impersonation") + c.JSON(http.StatusInternalServerError, response.InternalServerError("failed to extend impersonation", nil)) + return + } + if !HasPermission(freshImpersonator.UserPermissions, freshImpersonator.OrgPermissions, "impersonate:users") { + logger.RequestLogger(c, "impersonate").Warn(). + Str("operation", "extend_impersonation_permission_lost"). + Str("impersonator_user_id", impersonatorUser.ID). + Str("session_id", sessionID). + Msg("Impersonator no longer holds impersonate:users") + c.JSON(http.StatusForbidden, response.Forbidden("insufficient permissions to impersonate users", nil)) + return + } + + // The target is re-read too: it may have been suspended, deleted or given + // the Owner user role since the session started, and the new token must + // carry its current permissions. + freshTarget, err := logto.GetUserForImpersonation(*impersonatedUser.LogtoID) + if err != nil { + c.JSON(http.StatusBadRequest, response.BadRequest("target user not found or inaccessible", nil)) + return + } + if models.HasOwnerUserRole(freshTarget.UserRoles) { + c.JSON(http.StatusForbidden, response.Forbidden("an Owner-role account cannot be impersonated", nil)) + return + } + + sessionDuration := configuration.Config.ImpersonationSessionDuration + expiresAt := time.Now().Add(sessionDuration) + + sessionManager := cache.NewImpersonationSessionManager() + if err := sessionManager.ExtendSession(impersonatorUser.ID, sessionID, sessionDuration); err != nil { + if errors.Is(err, cache.ErrImpersonationSessionNotFound) { + c.JSON(http.StatusBadRequest, response.BadRequest("impersonation session expired or ended", nil)) + return + } + logger.RequestLogger(c, "impersonate").Warn(). + Err(err). + Str("operation", "extend_active_session_failed"). + Str("session_id", sessionID). + Msg("Failed to extend active session - continuing (fail open)") + } + + impersonationToken, err := jwt.GenerateImpersonationTokenWithDuration(*freshTarget, *impersonatorUser, sessionID, sessionDuration) + if err != nil { + logger.RequestLogger(c, "impersonate").Error(). + Err(err). + Str("operation", "extend_impersonation_generate_token"). + Str("session_id", sessionID). + Msg("Failed to generate impersonation token") + c.JSON(http.StatusInternalServerError, response.InternalServerError("failed to extend impersonation", nil)) + return + } + + // The old token would otherwise stay valid until its own expiry + if presented := strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer "); presented != "" { + if blErr := cache.GetTokenBlacklist().BlacklistToken(presented, "impersonation extended"); blErr != nil { + logger.RequestLogger(c, "impersonate").Warn(). + Err(blErr). + Str("operation", "extend_impersonation_blacklist_failed"). + Str("session_id", sessionID). + Msg("Failed to revoke the previous impersonation token") + } + } + + auditEntry := &models.ImpersonationAuditEntry{ + SessionID: sessionID, + ImpersonatorUserID: helpers.GetEffectiveUserID(impersonatorUser), + ImpersonatedUserID: freshTarget.ID, + ActionType: "session_extended", + ImpersonatorUsername: impersonatorUser.Username, + ImpersonatedUsername: freshTarget.Username, + ImpersonatorName: impersonatorUser.Name, + ImpersonatedName: freshTarget.Name, + } + if err := local.NewImpersonationService().LogImpersonationAction(auditEntry); err != nil { + logger.RequestLogger(c, "impersonate").Warn(). + Err(err). + Str("operation", "log_session_extended"). + Str("session_id", sessionID). + Msg("Failed to log impersonation session extension") + } + + logger.RequestLogger(c, "impersonate").Info(). + Str("operation", "impersonation_extended"). + Str("impersonator_user_id", impersonatorUser.ID). + Str("impersonated_user_id", freshTarget.ID). + Str("session_id", sessionID). + Time("expires_at", expiresAt). + Msg("Impersonation session extended") + + c.JSON(http.StatusOK, response.OK( + "impersonation extended successfully", + gin.H{ + "is_impersonating": true, + "token": impersonationToken, + "expires_in": int64(sessionDuration.Seconds()), + "expires_at": expiresAt, + "session_id": sessionID, + "impersonated_user": freshTarget, + "impersonator": impersonatorUser, + }, + )) +} + // ExitImpersonationWithAudit allows user to exit impersonation mode and logs the session end // DELETE /api/impersonate func ExitImpersonationWithAudit(c *gin.Context) { @@ -550,9 +471,9 @@ func ExitImpersonationWithAudit(c *gin.Context) { impersonatedUser, _ := helpers.GetUserFromContext(c) - // The impersonation token dies here: its lifetime is the consent's (up to - // a week), so an exit that left it valid would leave a usable target - // identity in the caller's hands. The presented token is the one to burn. + // The impersonation token dies here: it would otherwise stay valid for the + // rest of the session (up to a week), leaving a usable target identity in + // the caller's hands. The presented token is the one to burn. if presented := strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer "); presented != "" { if blErr := cache.GetTokenBlacklist().BlacklistToken(presented, "impersonation exited"); blErr != nil { logger.RequestLogger(c, "impersonate").Warn(). @@ -786,31 +707,6 @@ func GetImpersonationStatus(c *gin.Context) { return } - // The session record alone is not enough to re-issue a token: the target - // may have revoked consent since it was opened. - stillConsenting, consentErr := local.NewImpersonationService().CanBeImpersonated(impersonatedUser.ID) - if consentErr != nil { - logger.RequestLogger(c, "impersonate").Error(). - Err(consentErr). - Str("operation", "status_consent_check_failed"). - Str("session_id", activeSession.SessionID). - Msg("Failed to re-check consent for the active session") - c.JSON(http.StatusServiceUnavailable, response.ServiceUnavailable("security service temporarily unavailable", nil)) - return - } - if !stillConsenting { - if err := sessionManager.ClearSession(user.ID); err != nil { - logger.RequestLogger(c, "impersonate").Warn().Err(err).Str("user_id", user.ID).Msg("Failed to clear session after consent revocation") - } - c.JSON(http.StatusOK, response.OK( - "not currently impersonating", - gin.H{ - "is_impersonating": false, - }, - )) - return - } - // Calculate remaining duration for the impersonation token remainingDuration := time.Until(activeSession.ExpiresAt) if remainingDuration <= 0 { diff --git a/backend/methods/impersonate_unit_test.go b/backend/methods/impersonate_unit_test.go new file mode 100644 index 000000000..9d94aca8b --- /dev/null +++ b/backend/methods/impersonate_unit_test.go @@ -0,0 +1,72 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package methods + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/nethesis/my/backend/models" + "github.com/stretchr/testify/assert" +) + +func TestIsImpersonationTarget(t *testing.T) { + callerLogto := "caller-logto" + otherLogto := "other-logto" + caller := &models.User{ID: "caller", LogtoID: &callerLogto} + now := time.Now() + + tests := []struct { + name string + account models.LocalUser + want bool + }{ + {"an active user", models.LocalUser{ID: "u1", LogtoID: &otherLogto, Roles: []models.UserRole{{Name: "Admin"}}}, true}, + {"the caller, by id", models.LocalUser{ID: "caller"}, false}, + {"the caller, by Logto id", models.LocalUser{ID: "u2", LogtoID: &callerLogto}, false}, + {"a suspended user", models.LocalUser{ID: "u3", SuspendedAt: &now}, false}, + {"a deleted user", models.LocalUser{ID: "u4", DeletedAt: &now}, false}, + {"an Owner-role account", models.LocalUser{ID: "u5", Roles: []models.UserRole{{Name: "Owner"}}}, false}, + {"an Owner-role account, any case", models.LocalUser{ID: "u6", Roles: []models.UserRole{{Name: "owner"}}}, false}, + {"a Staff user", models.LocalUser{ID: "u7", Roles: []models.UserRole{{Name: "Staff"}}}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, isImpersonationTarget(caller, &tt.account)) + }) + } +} + +func TestExtendImpersonation_RefusesWithoutAnImpersonation(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + setup func(c *gin.Context) + want int + }{ + {"a regular token", func(c *gin.Context) {}, http.StatusBadRequest}, + {"an impersonation token without a session", func(c *gin.Context) { + c.Set("is_impersonated", true) + c.Set("impersonated_by", &models.User{ID: "staff"}) + c.Set("user", &models.User{ID: "target"}) + }, http.StatusInternalServerError}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/api/impersonate/extend", nil) + tt.setup(c) + + ExtendImpersonation(c) + + assert.Equal(t, tt.want, w.Code) + }) + } +} diff --git a/backend/methods/resellers.go b/backend/methods/resellers.go index 3c8bdf98c..8d2a1257b 100644 --- a/backend/methods/resellers.go +++ b/backend/methods/resellers.go @@ -201,6 +201,9 @@ func GetResellers(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } createdBy := c.QueryArray("created_by") ownedBy := c.QueryArray("organization_id") diff --git a/backend/methods/resellers_export.go b/backend/methods/resellers_export.go index 004c4a066..40b912650 100644 --- a/backend/methods/resellers_export.go +++ b/backend/methods/resellers_export.go @@ -47,6 +47,9 @@ func ExportResellers(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } // For export, we don't use pagination - get all matching resellers (with limit) sortBy := c.DefaultQuery("sort_by", "created_at") diff --git a/backend/methods/system_favorites.go b/backend/methods/system_favorites.go new file mode 100644 index 000000000..053564ad9 --- /dev/null +++ b/backend/methods/system_favorites.go @@ -0,0 +1,104 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package methods + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "github.com/nethesis/my/backend/entities" + "github.com/nethesis/my/backend/helpers" + "github.com/nethesis/my/backend/logger" + "github.com/nethesis/my/backend/models" + "github.com/nethesis/my/backend/response" + "github.com/nethesis/my/backend/services/local" +) + +// favoriteUserID is the key system_favorites rows are stored under: the Logto +// ID, which every principal has (the bootstrap Owner has no local users row). +func favoriteUserID(user *models.User) string { + if user == nil { + return "" + } + if user.LogtoID != nil && *user.LogtoID != "" { + return *user.LogtoID + } + return user.ID +} + +// applySystemFavoriteFilters scopes the favorite flag, filter and sort of a +// systems list to the caller. With an impersonation token the caller is the +// target, so the impersonator sees the target's favorites. +func applySystemFavoriteFilters(c *gin.Context, filters *models.SystemListFilters) { + if value, exists := c.Get("user"); exists { + if user, ok := value.(*models.User); ok { + filters.FavoritesOf = favoriteUserID(user) + } + } + filters.FavoritesOnly = c.Query("favorite") == "true" +} + +// AddSystemFavorite handles PUT /api/systems/:id/favorite - stars a system for +// the caller. Starring is personal and changes nothing on the system, so it +// needs only read access to it. +func AddSystemFavorite(c *gin.Context) { + setSystemFavorite(c, true) +} + +// RemoveSystemFavorite handles DELETE /api/systems/:id/favorite - unstars a +// system for the caller. It skips the access check: it only deletes the +// caller's own row, and a system that left the caller's scope (or was +// archived) must still be removable from their favorites. +func RemoveSystemFavorite(c *gin.Context) { + setSystemFavorite(c, false) +} + +func setSystemFavorite(c *gin.Context, favorite bool) { + systemID := c.Param("id") + if systemID == "" { + c.JSON(http.StatusBadRequest, response.BadRequest("system ID required", nil)) + return + } + + user, ok := helpers.GetUserFromContext(c) + if !ok { + return + } + userKey := favoriteUserID(user) + + operation := "unfavorite" + if favorite { + operation = "favorite" + if _, err := local.NewSystemsService().GetSystem(systemID, user.OrgRole, user.OrganizationID); helpers.HandleAccessError(c, err, "system", systemID) { + return + } + } + + repo := entities.NewLocalSystemFavoriteRepository() + var err error + if favorite { + err = repo.Add(userKey, systemID) + } else { + err = repo.Remove(userKey, systemID) + } + if err != nil { + logger.LogBusinessOperation(c, "systems", operation, "system", systemID, false, err) + c.JSON(http.StatusInternalServerError, response.InternalServerError("failed to update favorite system", nil)) + return + } + + logger.LogBusinessOperation(c, "systems", operation, "system", systemID, true, nil) + + message := "system removed from favorites" + if favorite { + message = "system added to favorites" + } + c.JSON(http.StatusOK, response.OK(message, gin.H{ + "system_id": systemID, + "is_favorite": favorite, + })) +} diff --git a/backend/methods/system_favorites_unit_test.go b/backend/methods/system_favorites_unit_test.go new file mode 100644 index 000000000..171881cbe --- /dev/null +++ b/backend/methods/system_favorites_unit_test.go @@ -0,0 +1,69 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package methods + +import ( + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + + "github.com/nethesis/my/backend/models" +) + +func TestFavoriteUserID(t *testing.T) { + logtoID := "logto-1" + empty := "" + tests := []struct { + name string + user *models.User + expected string + }{ + {"logto id wins over the local id", &models.User{ID: "local-1", LogtoID: &logtoID}, "logto-1"}, + {"owner without local row", &models.User{ID: "logto-1"}, "logto-1"}, + {"empty logto id falls back to the local id", &models.User{ID: "local-1", LogtoID: &empty}, "local-1"}, + {"nil user", nil, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expected, favoriteUserID(tt.user)) + }) + } +} + +func TestApplySystemFavoriteFilters(t *testing.T) { + gin.SetMode(gin.TestMode) + logtoID := "logto-1" + + tests := []struct { + name string + url string + user *models.User + wantOf string + wantFilter bool + }{ + {"caller scopes the flag", "/api/systems", &models.User{ID: "local-1", LogtoID: &logtoID}, "logto-1", false}, + {"favorite=true filters", "/api/systems?favorite=true", &models.User{LogtoID: &logtoID}, "logto-1", true}, + {"any other value does not filter", "/api/systems?favorite=1", &models.User{LogtoID: &logtoID}, "logto-1", false}, + {"no user in context stars nothing", "/api/systems?favorite=true", nil, "", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("GET", tt.url, nil) + if tt.user != nil { + c.Set("user", tt.user) + } + + var f models.SystemListFilters + applySystemFavoriteFilters(c, &f) + + assert.Equal(t, tt.wantOf, f.FavoritesOf) + assert.Equal(t, tt.wantFilter, f.FavoritesOnly) + }) + } +} diff --git a/backend/methods/systems.go b/backend/methods/systems.go index 87aec091c..57e3bb57c 100644 --- a/backend/methods/systems.go +++ b/backend/methods/systems.go @@ -9,8 +9,11 @@ import ( "crypto/tls" "errors" "fmt" + "net" "net/http" + "net/url" "strings" + "syscall" "time" "github.com/gin-gonic/gin" @@ -161,7 +164,10 @@ func GetSystems(c *gin.Context) { filterVersions := c.QueryArray("version") // Version filter (multiple values) filterOrgIDs := c.QueryArray("organization_id") // Organization filter (multiple IDs) filterStatuses := c.QueryArray("status") // Status filter (multiple values) - filterAddons := c.QueryArray("addon") // Add-on filter (multiple catalog ids) + if rejectDeletedStatusOutsideOwnerOrg(c, userOrgRole, filterStatuses) { + return + } + filterAddons := c.QueryArray("addon") // Add-on filter (multiple catalog ids) // include_hierarchy expands each organization_id filter to the org plus its // whole subtree (resellers/customers); the systems RBAC scope still applies @@ -195,6 +201,7 @@ func GetSystems(c *gin.Context) { Statuses: filterStatuses, Addons: filterAddons, } + applySystemFavoriteFilters(c, &filters) systems, totalCount, err := systemsService.GetSystemsByOrganizationPaginated( c.Request.Context(), userID, userOrgID, userOrgRole, page, pageSize, search, sortBy, sortDirection, filters, ) @@ -212,6 +219,7 @@ func GetSystems(c *gin.Context) { Strs("filter_organization_ids", filterOrgIDs). Strs("filter_statuses", filterStatuses). Strs("filter_addons", filterAddons). + Bool("filter_favorite", filters.FavoritesOnly). Str("sort_by", sortBy). Str("sort_direction", sortDirection). Msg("Failed to retrieve systems") @@ -263,6 +271,7 @@ func GetSystems(c *gin.Context) { Strs("filter_organization_ids", filterOrgIDs). Strs("filter_statuses", filterStatuses). Strs("filter_addons", filterAddons). + Bool("filter_favorite", filters.FavoritesOnly). Str("sort_by", sortBy). Str("sort_direction", sortDirection). Msg("Systems list requested") @@ -303,6 +312,14 @@ func GetSystem(c *gin.Context) { system.RebrandingEnabled, system.RebrandingOrgID = resolveRebranding(system.Organization.LogtoID) } + isFavorite, err := entities.NewLocalSystemFavoriteRepository().IsFavorite(favoriteUserID(user), system.ID) + if err != nil { + logger.RequestLogger(c, "systems").Warn().Err(err). + Str("system_id", systemID). + Msg("Failed to resolve favorite flag") + } + system.IsFavorite = isFavorite + // Log the action logger.RequestLogger(c, "systems").Info(). Str("operation", "get_system"). @@ -360,6 +377,12 @@ func UpdateSystem(c *gin.Context) { })) return } + if errors.Is(err, models.ErrInvalidUIURL) { + c.JSON(http.StatusBadRequest, response.ValidationFailed("validation failed", []response.ValidationError{ + {Key: "ui_url", Message: "invalid", Value: *request.UIURL}, + })) + return + } if helpers.HandleAccessError(c, err, "system", systemID) { return } @@ -786,42 +809,59 @@ func CheckSystemReachability(c *gin.Context) { return } - if system.FQDN == "" { + // url is the address to open, reachable or not: the probe runs from this + // server, and a system it cannot reach may still open from the admin's own + // network. Empty when no address is known yet. + candidateURLs := models.UIURLCandidates(system.UIURL, system.Type, system.FQDN) + if len(candidateURLs) == 0 { c.JSON(http.StatusOK, response.OK("reachability check completed", gin.H{"reachable": false, "url": ""})) return } - // The FQDN is what the appliance reported about itself: a value pointing - // inside this backend's network would turn the probe into a port scanner - // of Render's private services. Such a system is simply "not reachable". - if err := rejectNonPublicHost(system.FQDN); err != nil { + openURL := candidateURLs[0] + notReachable := gin.H{"reachable": false, "url": openURL} + + // The host is what the appliance reported about itself, or what an admin + // typed: a value pointing inside this backend's network would turn the + // probe into a port scanner of Render's private services. Such a system is + // simply "not reachable", and the dialer below checks again at connect time. + parsedURL, err := url.Parse(openURL) + if err != nil || parsedURL.Hostname() == "" { + c.JSON(http.StatusOK, response.OK("reachability check completed", notReachable)) + return + } + if err := rejectNonPublicHost(parsedURL.Hostname()); err != nil { logger.RequestLogger(c, "systems").Warn(). Err(err). Str("system_id", systemID). - Str("fqdn", system.FQDN). + Str("host", parsedURL.Hostname()). Msg("Reachability probe refused: host is not publicly routable") - c.JSON(http.StatusOK, response.OK("reachability check completed", gin.H{"reachable": false, "url": ""})) - return - } - - // Build candidate URLs based on system type - var candidateURLs []string - switch { - case system.Type != nil && *system.Type == "ns8": - candidateURLs = []string{fmt.Sprintf("https://%s/cluster-admin", system.FQDN)} - case system.Type != nil && *system.Type == "nsec": - candidateURLs = []string{ - fmt.Sprintf("https://%s:443", system.FQDN), - fmt.Sprintf("https://%s:9090", system.FQDN), - } - default: - c.JSON(http.StatusOK, response.OK("reachability check completed", gin.H{"reachable": false, "url": ""})) + c.JSON(http.StatusOK, response.OK("reachability check completed", notReachable)) return } // HTTP client with short timeout and skip TLS verification (self-signed certs) + // The dialer refuses a non-public address at connect time too: a name can + // resolve to a public address for the check above and to a private one for + // the connection (DNS rebinding). + dialer := &net.Dialer{ + Timeout: 5 * time.Second, + Control: func(_, address string, _ syscall.RawConn) error { + host, _, err := net.SplitHostPort(address) + if err != nil { + return err + } + ip := net.ParseIP(host) + if ip == nil { + return fmt.Errorf("unparseable address %q", host) + } + return rejectNonPublicIP(ip) + }, + } client := &http.Client{ Timeout: 5 * time.Second, Transport: &http.Transport{ + DialContext: dialer.DialContext, + Proxy: nil, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec // systems use self-signed certificates }, CheckRedirect: func(req *http.Request, via []*http.Request) error { @@ -845,7 +885,7 @@ func CheckSystemReachability(c *gin.Context) { Str("system_id", systemID). Msg("System is not reachable on any candidate URL") - c.JSON(http.StatusOK, response.OK("reachability check completed", gin.H{"reachable": false, "url": ""})) + c.JSON(http.StatusOK, response.OK("reachability check completed", notReachable)) } // attachSystemAddons fills the Addons list of the given systems with one batch diff --git a/backend/methods/systems_export.go b/backend/methods/systems_export.go index 6bf040fbd..64c7973bb 100644 --- a/backend/methods/systems_export.go +++ b/backend/methods/systems_export.go @@ -77,6 +77,9 @@ func ExportSystems(c *gin.Context) { return } filterStatuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, filterStatuses) { + return + } filterAddons := c.QueryArray("addon") // For export, we don't use pagination - get all matching systems (with limit) @@ -87,20 +90,22 @@ func ExportSystems(c *gin.Context) { // Create systems service systemsService := local.NewSystemsService() + listFilters := models.SystemListFilters{ + Name: filterName, + SystemKeys: filterSystemKey, + Types: filterTypes, + CreatedBy: filterCreatedBy, + Versions: filterVersions, + OrganizationIDs: filterOrgIDs, + ParentOrganizationIDs: filterParentOrgIDs, + Statuses: filterStatuses, + Addons: filterAddons, + } + applySystemFavoriteFilters(c, &listFilters) + // Get systems without pagination limit (but with max export limit) systems, totalCount, err := systemsService.GetSystemsByOrganizationPaginated( - c.Request.Context(), userID, userOrgID, userOrgRole, 1, MaxExportLimit, search, sortBy, sortDirection, - models.SystemListFilters{ - Name: filterName, - SystemKeys: filterSystemKey, - Types: filterTypes, - CreatedBy: filterCreatedBy, - Versions: filterVersions, - OrganizationIDs: filterOrgIDs, - ParentOrganizationIDs: filterParentOrgIDs, - Statuses: filterStatuses, - Addons: filterAddons, - }, + c.Request.Context(), userID, userOrgID, userOrgRole, 1, MaxExportLimit, search, sortBy, sortDirection, listFilters, ) if err != nil { @@ -139,6 +144,9 @@ func ExportSystems(c *gin.Context) { if parents := c.QueryArray("parent_organization_id"); len(parents) > 0 { filters["parent_organization_id"] = strings.Join(parents, ", ") } + if listFilters.FavoritesOnly { + filters["favorite"] = true + } // Create export service exportService := export.NewSystemsExportService() diff --git a/backend/methods/users.go b/backend/methods/users.go index abd2e6d07..5042e5b43 100644 --- a/backend/methods/users.go +++ b/backend/methods/users.go @@ -263,6 +263,9 @@ func GetUsers(c *gin.Context) { // Parse filter parameters organizationFilter := c.QueryArray("organization_id") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } roleFilter := c.QueryArray("role") createdByFilter := c.QueryArray("created_by") @@ -286,31 +289,12 @@ func GetUsers(c *gin.Context) { // Check if current user has impersonate permission (from user roles or organization roles) canImpersonate := HasPermission(user.UserPermissions, user.OrgPermissions, "impersonate:users") - // Enrich users with impersonation consent status if user can impersonate + // For a caller who can impersonate, tell which users POST /impersonate + // would accept, so the frontend enables the action only for them enrichedUsers := make([]gin.H, 0) if canImpersonate { - impersonationService := local.NewImpersonationService() - - // Collect all user IDs for batch consent check (performance optimization) - userIDs := make([]string, len(accounts)) - for i, account := range accounts { - userIDs[i] = account.ID - } - - // Batch check impersonation consent for all users (single query instead of N queries) - consentMap, err := impersonationService.CanBeImpersonatedBatch(userIDs) - if err != nil { - logger.RequestLogger(c, "users").Warn(). - Err(err). - Int("user_count", len(userIDs)). - Msg("Failed to batch check impersonation consent, defaulting to false") - // Initialize empty map so all users default to false - consentMap = make(map[string]bool) - } - for _, account := range accounts { - // Get consent status from batch result (defaults to false if not found) - canBeImpersonated := consentMap[account.ID] + canBeImpersonated := isImpersonationTarget(user, account) // Convert account to gin.H and add impersonation field userMap := gin.H{ @@ -1139,3 +1123,19 @@ func ResetUserPassword(c *gin.Context) { // Return success response c.JSON(http.StatusOK, response.OK("password reset successfully", nil)) } + +// isImpersonationTarget mirrors the checks of ImpersonateUser: an active user +// other than the caller, without the Owner user role +func isImpersonationTarget(caller *models.User, account *models.LocalUser) bool { + if account.DeletedAt != nil || account.SuspendedAt != nil || account.ID == caller.ID { + return false + } + if caller.LogtoID != nil && account.LogtoID != nil && *caller.LogtoID == *account.LogtoID { + return false + } + roleNames := make([]string, 0, len(account.Roles)) + for _, role := range account.Roles { + roleNames = append(roleNames, role.Name) + } + return !models.HasOwnerUserRole(roleNames) +} diff --git a/backend/methods/users_export.go b/backend/methods/users_export.go index 721b6ba24..6721f3d9c 100644 --- a/backend/methods/users_export.go +++ b/backend/methods/users_export.go @@ -49,6 +49,9 @@ func ExportUsers(c *gin.Context) { // Parse filter parameters organizationFilter := c.QueryArray("organization_id") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } roleFilter := c.QueryArray("role") createdByFilter := c.QueryArray("created_by") diff --git a/backend/middleware/jwt.go b/backend/middleware/jwt.go index 6d420e3d3..133cd52f5 100644 --- a/backend/middleware/jwt.go +++ b/backend/middleware/jwt.go @@ -16,12 +16,10 @@ import ( "github.com/gin-gonic/gin" "github.com/nethesis/my/backend/cache" - "github.com/nethesis/my/backend/database" "github.com/nethesis/my/backend/jwt" "github.com/nethesis/my/backend/logger" "github.com/nethesis/my/backend/models" "github.com/nethesis/my/backend/response" - "github.com/nethesis/my/backend/services/local" ) // setUserContext sets user-related context values on the gin context @@ -137,39 +135,6 @@ func JWTAuthMiddleware() gin.HandlerFunc { impersonationClaims, impErr := jwt.ValidateImpersonationToken(tokenString) if impErr == nil { // This is a valid impersonation token - // Check if impersonation consent is still active (security: revoked consent should invalidate active tokens) - // Skip consent validation if database is not available (e.g., in test environments) - if database.DB != nil { - impersonationService := local.NewImpersonationService() - canBeImpersonated, consentErr := impersonationService.CanBeImpersonated(impersonationClaims.User.ID) - if consentErr != nil { - logger.RequestLogger(c, "auth").Error(). - Err(consentErr). - Str("operation", "impersonation_consent_check_failed"). - Str("impersonated_user_id", impersonationClaims.User.ID). - Str("impersonator_user_id", impersonationClaims.ImpersonatedBy.ID). - Str("client_ip", c.ClientIP()). - Msg("Failed to check impersonation consent - denying request") - c.JSON(http.StatusServiceUnavailable, response.ServiceUnavailable("security service temporarily unavailable", nil)) - c.Abort() - return - } - if !canBeImpersonated { - logger.RequestLogger(c, "auth").Warn(). - Str("operation", "impersonation_consent_revoked"). - Str("impersonated_user_id", impersonationClaims.User.ID). - Str("impersonator_user_id", impersonationClaims.ImpersonatedBy.ID). - Str("session_id", impersonationClaims.SessionID). - Str("client_ip", c.ClientIP()). - Msg("Impersonation consent has been revoked - invalidating token") - c.JSON(http.StatusUnauthorized, response.Unauthorized("impersonation consent has been revoked", gin.H{ - "message": "the user has revoked consent for impersonation. please exit impersonation mode.", - })) - c.Abort() - return - } - } - // User-level revocation of BOTH principals: a suspended (or logged // out) impersonator must not keep acting through the target, and a // suspended target must not be acted for. Keyed on the Logto ID diff --git a/backend/models/system_ui_url.go b/backend/models/system_ui_url.go new file mode 100644 index 000000000..16f9c4cf7 --- /dev/null +++ b/backend/models/system_ui_url.go @@ -0,0 +1,76 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package models + +import ( + "errors" + "fmt" + "net/url" + "strings" +) + +// MaxUIURLLength matches the systems.ui_url column. +const MaxUIURLLength = 2048 + +// ErrInvalidUIURL is returned for a web interface address that is not an +// absolute http(s) URL with a host. +var ErrInvalidUIURL = errors.New("invalid") + +// DefaultUIURL is the address the web interface of a system answers on when +// nobody set another one: it follows the FQDN of the latest inventory. Empty +// when the type or the FQDN is not known yet. The frontend derives the same +// address in getDefaultUiUrl, for the helper text of the edit drawer. +func DefaultUIURL(systemType *string, fqdn string) string { + if systemType == nil || fqdn == "" { + return "" + } + switch *systemType { + case "ns8": + return fmt.Sprintf("https://%s/cluster-admin", fqdn) + case "nsec": + return fmt.Sprintf("https://%s:9090", fqdn) + } + return "" +} + +// UIURLCandidates lists the addresses the reachability check tries, in order. +// A custom address is the only one: the admin set it because the default does +// not open the system. Without one, NethSecurity also tries the standard HTTPS +// port, where some installations serve their web interface. +func UIURLCandidates(customURL *string, systemType *string, fqdn string) []string { + if customURL != nil && *customURL != "" { + return []string{*customURL} + } + defaultURL := DefaultUIURL(systemType, fqdn) + if defaultURL == "" { + return nil + } + if *systemType == "nsec" { + return []string{defaultURL, fmt.Sprintf("https://%s:443", fqdn)} + } + return []string{defaultURL} +} + +// NormalizeUIURL validates the address an admin entered for the web interface +// and returns what to store: nil for an empty value or for the default +// address, so that the system keeps following its FQDN. +func NormalizeUIURL(raw string, systemType *string, fqdn string) (*string, error) { + value := strings.TrimSpace(raw) + if value == "" { + return nil, nil + } + if len(value) > MaxUIURLLength { + return nil, ErrInvalidUIURL + } + parsed, err := url.Parse(value) + if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.Hostname() == "" || parsed.User != nil { + return nil, ErrInvalidUIURL + } + if value == DefaultUIURL(systemType, fqdn) { + return nil, nil + } + return &value, nil +} diff --git a/backend/models/system_ui_url_test.go b/backend/models/system_ui_url_test.go new file mode 100644 index 000000000..9cadd34ca --- /dev/null +++ b/backend/models/system_ui_url_test.go @@ -0,0 +1,60 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package models + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDefaultUIURL(t *testing.T) { + assert.Equal(t, "https://ns.example.com/cluster-admin", DefaultUIURL(strPtr("ns8"), "ns.example.com")) + assert.Equal(t, "https://fw.example.com:9090", DefaultUIURL(strPtr("nsec"), "fw.example.com")) + assert.Equal(t, "", DefaultUIURL(nil, "fw.example.com")) + assert.Equal(t, "", DefaultUIURL(strPtr("nsec"), "")) + assert.Equal(t, "", DefaultUIURL(strPtr("other"), "x.example.com")) +} + +func TestUIURLCandidates(t *testing.T) { + assert.Equal(t, []string{"https://ns.example.com/cluster-admin"}, UIURLCandidates(nil, strPtr("ns8"), "ns.example.com")) + assert.Equal(t, []string{"https://fw.example.com:9090", "https://fw.example.com:443"}, UIURLCandidates(nil, strPtr("nsec"), "fw.example.com")) + assert.Equal(t, []string{"https://custom.example.org:8443"}, UIURLCandidates(strPtr("https://custom.example.org:8443"), strPtr("nsec"), "fw.example.com")) + assert.Equal(t, []string{"https://custom.example.org"}, UIURLCandidates(strPtr("https://custom.example.org"), nil, "")) + assert.Nil(t, UIURLCandidates(nil, nil, "")) +} + +func TestNormalizeUIURL(t *testing.T) { + ns8 := strPtr("ns8") + tests := []struct { + name string + raw string + want *string + wantErr bool + }{ + {"empty goes back to the default", " ", nil, false}, + {"the default is not stored", "https://ns.example.com/cluster-admin", nil, false}, + {"a custom https address", " https://ns.example.org:8443/cluster-admin ", strPtr("https://ns.example.org:8443/cluster-admin"), false}, + {"http is accepted", "http://192.0.2.10:9090", strPtr("http://192.0.2.10:9090"), false}, + {"no scheme", "ns.example.org/cluster-admin", nil, true}, + {"another scheme", "javascript:alert(1)", nil, true}, + {"no host", "https:///cluster-admin", nil, true}, + {"credentials", "https://user:pass@ns.example.org", nil, true}, + {"too long", "https://ns.example.org/" + strings.Repeat("a", MaxUIURLLength), nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := NormalizeUIURL(tt.raw, ns8, "ns.example.com") + if tt.wantErr { + assert.ErrorIs(t, err, ErrInvalidUIURL) + return + } + assert.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} diff --git a/backend/models/systems.go b/backend/models/systems.go index 13278548f..003b22dda 100644 --- a/backend/models/systems.go +++ b/backend/models/systems.go @@ -71,31 +71,34 @@ func (c *SystemCreator) SetCreatorOrgType(orgType string) { // System represents a managed system in the infrastructure type System struct { - ID string `json:"id" structs:"id"` - Name string `json:"name" structs:"name"` - Type *string `json:"type" structs:"type"` // ns8, nsec, etc. - nullable until first inventory - Status string `json:"status" structs:"status"` // Unified status: unknown, active, inactive, suspended, deleted - FQDN string `json:"fqdn" structs:"fqdn"` - IPv4Address string `json:"ipv4_address" structs:"ipv4_address"` - IPv6Address string `json:"ipv6_address" structs:"ipv6_address"` - Version string `json:"version" structs:"version"` - UpdateAvailable *bool `json:"update_available" structs:"update_available"` // From the latest inventory; nil = not reported - CustomData map[string]string `json:"custom_data" structs:"custom_data"` - Organization Organization `json:"organization" structs:"organization"` // Organization details with type - SystemKey string `json:"system_key" structs:"system_key"` - SystemSecret string `json:"system_secret,omitempty" structs:"system_secret"` // Returned during creation and regeneration - Notes string `json:"notes" structs:"notes"` - CreatedAt time.Time `json:"created_at" structs:"created_at"` - UpdatedAt time.Time `json:"updated_at" structs:"updated_at"` - DeletedAt *time.Time `json:"deleted_at" structs:"deleted_at"` // Soft delete timestamp - RegisteredAt *time.Time `json:"registered_at" structs:"registered_at"` // Registration timestamp - UnregisteredAt *time.Time `json:"unregistered_at" structs:"unregistered_at"` // Terminal: the system gave up its credentials - SuspendedAt *time.Time `json:"suspended_at" structs:"suspended_at"` // Suspension timestamp - SuspendedByOrgID *string `json:"suspended_by_org_id" structs:"suspended_by_org_id"` // Organization that caused cascade suspension - DeletedByOrgID *string `json:"deleted_by_org_id" structs:"deleted_by_org_id"` // Organization that caused cascade soft-deletion - CreatedBy SystemCreator `json:"created_by" structs:"created_by"` - LastHeartbeat *time.Time `json:"last_heartbeat,omitempty"` // Last heartbeat timestamp - LastInventory *time.Time `json:"last_inventory,omitempty"` // Last inventory timestamp (NULL = never received) + ID string `json:"id" structs:"id"` + Name string `json:"name" structs:"name"` + Type *string `json:"type" structs:"type"` // ns8, nsec, etc. - nullable until first inventory + Status string `json:"status" structs:"status"` // Unified status: unknown, active, inactive, suspended, deleted + FQDN string `json:"fqdn" structs:"fqdn"` + IPv4Address string `json:"ipv4_address" structs:"ipv4_address"` + IPv6Address string `json:"ipv6_address" structs:"ipv6_address"` + Version string `json:"version" structs:"version"` + UpdateAvailable *bool `json:"update_available" structs:"update_available"` // From the latest inventory; nil = not reported + CustomData map[string]string `json:"custom_data" structs:"custom_data"` + Organization Organization `json:"organization" structs:"organization"` // Organization details with type + SystemKey string `json:"system_key" structs:"system_key"` + SystemSecret string `json:"system_secret,omitempty" structs:"system_secret"` // Returned during creation and regeneration + Notes string `json:"notes" structs:"notes"` + // UIURL is the address of the web interface set by an admin; nil means the + // default one, which DefaultUIURL derives from FQDN and Type + UIURL *string `json:"ui_url" structs:"ui_url"` + CreatedAt time.Time `json:"created_at" structs:"created_at"` + UpdatedAt time.Time `json:"updated_at" structs:"updated_at"` + DeletedAt *time.Time `json:"deleted_at" structs:"deleted_at"` // Soft delete timestamp + RegisteredAt *time.Time `json:"registered_at" structs:"registered_at"` // Registration timestamp + UnregisteredAt *time.Time `json:"unregistered_at" structs:"unregistered_at"` // Terminal: the system gave up its credentials + SuspendedAt *time.Time `json:"suspended_at" structs:"suspended_at"` // Suspension timestamp + SuspendedByOrgID *string `json:"suspended_by_org_id" structs:"suspended_by_org_id"` // Organization that caused cascade suspension + DeletedByOrgID *string `json:"deleted_by_org_id" structs:"deleted_by_org_id"` // Organization that caused cascade soft-deletion + CreatedBy SystemCreator `json:"created_by" structs:"created_by"` + LastHeartbeat *time.Time `json:"last_heartbeat,omitempty"` // Last heartbeat timestamp + LastInventory *time.Time `json:"last_inventory,omitempty"` // Last inventory timestamp (NULL = never received) // First contact timestamps, populated by the single-system read only // (GetByID): they need per-system lookups that a list query cannot @@ -107,6 +110,10 @@ type System struct { RebrandingEnabled bool `json:"rebranding_enabled"` RebrandingOrgID *string `json:"rebranding_org_id,omitempty"` + // IsFavorite reports whether the caller starred the system. It is + // personal: two users reading the same system can get different values. + IsFavorite bool `json:"is_favorite"` + // Addons lists the catalog ids of the add-ons granted and still valid on // the system. The list endpoint fills it only when asked // (include_addons=true): it costs one extra query per page, which an @@ -128,6 +135,11 @@ type SystemListFilters struct { ParentOrganizationIDs []string // "Managed by": owning organization within these subtrees Statuses []string // unified status, including suspended/no_inventory Addons []string // catalog ids of add-ons the system must hold + + // FavoritesOf is the Logto ID of the caller: it fills IsFavorite and + // enables the favorite sort. Empty leaves every system unstarred. + FavoritesOf string + FavoritesOnly bool // only the systems FavoritesOf starred } // IsSuspended returns true if the system is suspended @@ -163,6 +175,8 @@ type UpdateSystemRequest struct { OrganizationID string `json:"organization_id" structs:"organization_id"` CustomData map[string]string `json:"custom_data" structs:"custom_data"` Notes string `json:"notes" structs:"notes"` + // UIURL: omitted keeps the current address, empty goes back to the default + UIURL *string `json:"ui_url,omitempty" structs:"ui_url"` } // RegisterSystemRequest represents the request payload for registering a system diff --git a/backend/models/user.go b/backend/models/user.go index 07677abd2..065b67a5a 100644 --- a/backend/models/user.go +++ b/backend/models/user.go @@ -95,21 +95,6 @@ type ChangeInfoRequest struct { Phone *string `json:"phone,omitempty"` } -// ImpersonationConsent represents a user's consent to be impersonated -type ImpersonationConsent struct { - ID string `json:"id" db:"id"` - UserID string `json:"user_id" db:"user_id"` - ExpiresAt time.Time `json:"expires_at" db:"expires_at"` - MaxDurationMinutes int `json:"max_duration_minutes" db:"max_duration_minutes"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - Active bool `json:"-" db:"active"` -} - -// EnableConsentRequest represents a request to enable impersonation consent -type EnableConsentRequest struct { - DurationHours int `json:"duration_hours" binding:"min=0,max=168"` // Max 1 week, defaults to 1 hour if 0 or not provided -} - // ImpersonationAuditEntry represents an action performed during impersonation type ImpersonationAuditEntry struct { ID string `json:"id" db:"id"` diff --git a/backend/openapi.yaml b/backend/openapi.yaml index a37b79bff..54519e6c7 100644 --- a/backend/openapi.yaml +++ b/backend/openapi.yaml @@ -30,7 +30,7 @@ tags: - name: Backend - Me description: Current user profile, password and avatar management - name: Backend - Impersonation - description: Consent-based user impersonation flow (start, exit, status, consent) + description: User impersonation flow (start, exit, status, sessions) - name: Backend - Impersonation Sessions description: Impersonation session history and audit logs @@ -1583,7 +1583,7 @@ components: - $ref: '#/components/schemas/OrgCreator' can_be_impersonated: type: boolean - description: Whether this user can currently be impersonated (only shown for users with impersonation permissions, based on active consent) + description: "Whether the caller can impersonate this user (only shown for users with impersonation permissions): an active user other than the caller, without the Owner user role" example: true has_avatar: type: boolean @@ -2224,6 +2224,25 @@ components: description: Cumulative count at this date example: 15 + SystemFavoriteResponse: + type: object + properties: + code: + type: integer + example: 200 + message: + type: string + example: "system added to favorites" + data: + type: object + properties: + system_id: + type: string + example: "sys_123456789" + is_favorite: + type: boolean + example: true + System: type: object properties: @@ -2292,6 +2311,14 @@ components: type: string description: Additional notes or description for the system example: "Production web server for EU region" + ui_url: + type: string + nullable: true + description: | + Address of the system web interface set by an admin. Null means the + default one, derived from fqdn and type: `https://{fqdn}/cluster-admin` + for NethServer, `https://{fqdn}:9090` for NethSecurity. + example: "https://firewall.example.com:8443" created_at: type: string format: date-time @@ -2369,6 +2396,10 @@ components: nullable: true description: Logto organization ID (logto_id) that provides the rebranding assets (the org itself or an ancestor). Use this value as the :org_id parameter in /api/rebranding/:org_id/* endpoints. example: "org_dist001" + is_favorite: + type: boolean + description: Whether the caller starred the system. Personal, so two users reading the same system can get different values. + example: false addons: type: array description: | @@ -2593,6 +2624,15 @@ components: type: string description: Additional notes or description for the system example: "Production web server for EU region" + ui_url: + type: string + maxLength: 2048 + description: | + Address of the system web interface, an absolute http or https URL. + Omitted keeps the current one; empty, or the default address, goes + back to the default derived from fqdn and type. An invalid value + returns 400 with the validation error `ui_url` / `invalid`. + example: "https://firewall.example.com:8443" # Entitlements schemas EntitlementCatalogItem: @@ -3908,32 +3948,6 @@ components: description: Custom notes for the application example: "Server di posta aziendale per il reparto marketing" - ImpersonationConsent: - type: object - properties: - id: - type: string - description: Consent ID - example: "consent_123" - user_id: - type: string - description: User ID who grants consent - example: "usr_456" - expires_at: - type: string - format: date-time - description: Consent expiration timestamp - example: "2025-09-04T14:30:00Z" - max_duration_minutes: - type: integer - description: Maximum duration for each impersonation session in minutes - example: 60 - created_at: - type: string - format: date-time - description: Consent creation timestamp - example: "2025-09-03T14:30:00Z" - ImpersonationSession: type: object properties: @@ -4028,7 +4042,7 @@ components: example: "Jane Smith" action_type: type: string - enum: [session_start, session_end, api_call] + enum: [session_start, session_extended, session_end, api_call] description: Type of action performed example: "api_call" api_endpoint: @@ -4720,6 +4734,8 @@ components: - deleted: soft-deleted When "deleted" is combined with other statuses, both deleted and non-deleted matching records are returned. + + Only the Owner organization may ask for "deleted": any other caller gets 403. required: false schema: type: array @@ -4743,11 +4759,13 @@ components: SystemSortByParam: name: sort_by in: query - description: Field to sort systems by + description: >- + Field to sort systems by. `favorite` lists the caller's favorites first + in ascending order, last in descending order. required: false schema: type: string - enum: ["name", "type", "status", "fqdn", "version", "system_key", "created_at", "updated_at", "creator_name", "organization_name", "managed_by"] + enum: ["name", "type", "status", "fqdn", "version", "system_key", "created_at", "updated_at", "creator_name", "organization_name", "managed_by", "favorite"] example: "name" TrendPeriodParam: @@ -4948,6 +4966,7 @@ components: Special value "deleted" shows soft-deleted systems (where deleted_at IS NOT NULL). When "deleted" is combined with other statuses, both deleted and non-deleted systems matching the other statuses are returned. + Only the Owner organization may ask for "deleted": any other caller gets 403. "no_inventory" is additive rather than exclusive: such a system is also active or inactive, so it matches both filters. Selecting it alone yields @@ -4983,6 +5002,18 @@ components: style: form explode: true + SystemFavoriteFilterParam: + name: favorite + in: query + description: | + Only the systems the caller starred (see PUT /api/systems/{id}/favorite). + Favorites are personal: with an impersonation token they are the + target's. + required: false + schema: + type: boolean + example: true + IncludeAddonsParam: name: include_addons in: query @@ -5395,7 +5426,8 @@ paths: - enabled: not suspended and not deleted - suspended: suspended but not deleted - - deleted: soft-deleted + - deleted: soft-deleted, for the Owner organization only (any other + caller gets 403) - no_login: virtual status matching accounts that never signed in (latest_login_at IS NULL) @@ -5898,7 +5930,7 @@ paths: tags: - Backend - Users summary: /users/{id}/restore - Restore soft-deleted user - description: Restore a soft-deleted user (requires manage:users permission and hierarchical validation) + description: Restore a soft-deleted user (Owner organization only; requires manage:users permission and hierarchical validation) parameters: - name: id in: path @@ -6096,7 +6128,8 @@ paths: - enabled: not suspended and not deleted - suspended: suspended but not deleted - - deleted: soft-deleted + - deleted: soft-deleted, for the Owner organization only (any other + caller gets 403) - no_login: virtual status matching accounts that never signed in (latest_login_at IS NULL) @@ -7446,144 +7479,12 @@ paths: $ref: '#/components/responses/Unauthorized' # =========================================================================== - # CONSENT-BASED IMPERSONATION SYSTEM + # IMPERSONATION # =========================================================================== - /impersonate/consent: - post: - operationId: enableImpersonationConsent - servers: - - url: https://my.nethesis.it/backend/api - description: Backend API server - tags: - - Backend - Impersonation - summary: /impersonate/consent - Enable impersonation consent - description: | - Allows a user to enable consent for being impersonated by authorized users (Owner organization users holding the Staff or Owner role). - This is a **privacy-friendly** approach where users explicitly control - if and for how long they can be impersonated. - - **Key Features:** - - User controls their own impersonation consent - - Custom duration (1-168 hours) - - Only active while consent is valid - - Complete audit trail of all impersonation activities - requestBody: - required: true - content: - application/json: - schema: - type: object - properties: - duration_hours: - type: integer - minimum: 1 - maximum: 168 - default: 1 - description: How many hours the consent should be active (max 1 week, defaults to 1 hour) - example: 24 - responses: - '200': - description: Impersonation consent enabled successfully - content: - application/json: - schema: - type: object - properties: - code: - type: integer - example: 200 - message: - type: string - example: "impersonation consent enabled successfully" - data: - type: object - properties: - consent: - $ref: '#/components/schemas/ImpersonationConsent' - '400': - description: Bad request (invalid duration) - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - example: - code: 400 - message: "Duration must be between 1 and 168 hours" - '401': - $ref: '#/components/responses/Unauthorized' - - get: - operationId: getImpersonationConsentStatus - servers: - - url: https://my.nethesis.it/backend/api - description: Backend API server - tags: - - Backend - Impersonation - summary: /impersonate/consent - Get impersonation consent status - description: | - Retrieves the current impersonation consent status for the authenticated user. - Shows if consent is active, when it expires, and other consent details. - responses: - '200': - description: Consent status retrieved successfully - content: - application/json: - schema: - type: object - properties: - code: - type: integer - example: 200 - message: - type: string - example: "consent status retrieved successfully" - data: - type: object - properties: - consent: - allOf: - - $ref: '#/components/schemas/ImpersonationConsent' - type: object - nullable: true - description: Consent details (null if no active consent) - '401': - $ref: '#/components/responses/Unauthorized' - - delete: - operationId: disableImpersonationConsent - servers: - - url: https://my.nethesis.it/backend/api - description: Backend API server - tags: - - Backend - Impersonation - summary: /impersonate/consent - Disable impersonation consent - description: | - Disables all active impersonation consent for the authenticated user. - This prevents any future impersonation until consent is re-enabled. - responses: - '200': - description: Impersonation consent disabled successfully - content: - application/json: - schema: - type: object - properties: - code: - type: integer - example: 200 - message: - type: string - example: "impersonation consent disabled successfully" - data: - type: object - nullable: true - '401': - $ref: '#/components/responses/Unauthorized' - /impersonate: post: - operationId: impersonateUserWithConsent + operationId: impersonateUser servers: - url: https://my.nethesis.it/backend/api description: Backend API server @@ -7592,8 +7493,9 @@ paths: summary: /impersonate - Start impersonation (permission-based access) description: | Allows users with the `impersonate:users` permission (Staff and Owner roles, Owner organization only) - to impersonate another user, but only if that user has active consent enabled. - The impersonation token duration will match the user's consent settings. + to impersonate another active user, without the target's consent. An Owner-role account is never a + target. The token expires after the `IMPERSONATION_SESSION_DURATION` of the backend (default 1 hour), + and every session is audited. requestBody: required: true content: @@ -7630,8 +7532,13 @@ paths: example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." expires_in: type: integer - description: Token expiration time in seconds (matches user consent) - example: 86400 + description: Token expiration time in seconds (IMPERSONATION_SESSION_DURATION) + example: 3600 + expires_at: + type: string + format: date-time + description: When the impersonation token expires + example: "2025-09-04T14:30:00Z" session_id: type: string description: Unique session ID for audit tracking @@ -7661,11 +7568,6 @@ paths: value: code: 400 message: "Target user not found or inaccessible" - no_consent: - summary: User has no active consent - value: - code: 400 - message: "Target user has not provided consent for impersonation or consent has expired" '403': description: Forbidden (insufficient permissions for impersonation, or already impersonating) content: @@ -7739,6 +7641,77 @@ paths: '401': $ref: '#/components/responses/Unauthorized' + /impersonate/extend: + post: + operationId: extendImpersonation + servers: + - url: https://my.nethesis.it/backend/api + description: Backend API server + tags: + - Backend - Impersonation + summary: /impersonate/extend - Extend the impersonation session + description: | + Restarts the current impersonation session for a full `IMPERSONATION_SESSION_DURATION` (default 1 hour) + from now, with no limit on the number of extensions. Called with the impersonation token: the response + carries a new token for the same session, and the presented one is revoked. The impersonator must still + hold `impersonate:users` and the target must still be an active user without the Owner role. API keys + are refused. The extension is recorded in the session audit as `session_extended`. + responses: + '200': + description: Impersonation extended successfully + content: + application/json: + schema: + type: object + properties: + code: + type: integer + example: 200 + message: + type: string + example: "impersonation extended successfully" + data: + type: object + properties: + token: + type: string + description: New impersonation JWT token for the same session + example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." + expires_in: + type: integer + description: Token expiration time in seconds (IMPERSONATION_SESSION_DURATION) + example: 3600 + expires_at: + type: string + format: date-time + description: When the new impersonation token expires + example: "2025-09-04T14:30:00Z" + session_id: + type: string + description: The session being extended + example: "session-uuid-here" + is_impersonating: + type: boolean + example: true + impersonated_user: + $ref: '#/components/schemas/User' + impersonator: + $ref: '#/components/schemas/User' + '400': + description: Not impersonating, the session expired or ended, or the target is no longer active + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + description: The impersonator lost impersonate:users, the target now has the Owner role, or the caller used an API key + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /impersonate/status: get: operationId: getImpersonationStatus @@ -8575,7 +8548,7 @@ paths: tags: - Backend - Customers summary: /customers/{id}/restore - Restore soft-deleted customer - description: Restore a soft-deleted customer (requires manage:customers permission and hierarchical validation) + description: Restore a soft-deleted customer (Owner organization only; requires manage:customers permission and hierarchical validation) parameters: - name: id in: path @@ -9210,7 +9183,7 @@ paths: tags: - Backend - Distributors summary: /distributors/{id}/restore - Restore soft-deleted distributor - description: Restore a soft-deleted distributor (requires manage:distributors permission and hierarchical validation) + description: Restore a soft-deleted distributor (Owner organization only; requires manage:distributors permission and hierarchical validation) parameters: - name: id in: path @@ -10912,7 +10885,7 @@ paths: tags: - Backend - Resellers summary: /resellers/{id}/restore - Restore soft-deleted reseller - description: Restore a soft-deleted reseller (requires manage:resellers permission and hierarchical validation) + description: Restore a soft-deleted reseller (Owner organization only; requires manage:resellers permission and hierarchical validation) parameters: - name: id in: path @@ -11227,6 +11200,7 @@ paths: - $ref: '#/components/parameters/ParentOrganizationFilterParam' - $ref: '#/components/parameters/SystemStatusFilterParam' - $ref: '#/components/parameters/SystemAddonFilterParam' + - $ref: '#/components/parameters/SystemFavoriteFilterParam' - $ref: '#/components/parameters/IncludeAddonsParam' responses: '200': @@ -11496,7 +11470,7 @@ paths: tags: - Backend - Systems summary: /systems/{id}/restore - Restore soft-deleted system - description: Restore a soft-deleted system. Users can restore systems they have permission to delete based on hierarchical permissions. + description: Restore a soft-deleted system (Owner organization only; requires manage:systems permission and hierarchical validation). parameters: - name: id in: path @@ -11545,6 +11519,89 @@ paths: '404': $ref: '#/components/responses/NotFound' + /systems/{id}/favorite: + put: + operationId: addSystemFavorite + servers: + - url: https://my.nethesis.it/backend/api + description: Backend API server + tags: + - Backend - Systems + summary: /systems/{id}/favorite - Star a system + description: | + Add the system to the caller's favorites. Favorites are personal and + change nothing on the system, so read:systems is enough. Starring a + system already starred succeeds without changes. The system must be + visible to the caller and not archived. + + Refused with an API key and with an impersonation token. + parameters: + - name: id + in: path + required: true + description: System ID + schema: + type: string + example: "sys_123456789" + responses: + '200': + description: System added to favorites + content: + application/json: + schema: + $ref: '#/components/schemas/SystemFavoriteResponse' + example: + code: 200 + message: "system added to favorites" + data: + system_id: "sys_123456789" + is_favorite: true + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + delete: + operationId: removeSystemFavorite + servers: + - url: https://my.nethesis.it/backend/api + description: Backend API server + tags: + - Backend - Systems + summary: /systems/{id}/favorite - Unstar a system + description: | + Remove the system from the caller's favorites. It succeeds when the + system was not starred, and also for a system the caller can no longer + see or that was archived, so a stale favorite can always be removed. + + Refused with an API key and with an impersonation token. + parameters: + - name: id + in: path + required: true + description: System ID + schema: + type: string + example: "sys_123456789" + responses: + '200': + description: System removed from favorites + content: + application/json: + schema: + $ref: '#/components/schemas/SystemFavoriteResponse' + example: + code: 200 + message: "system removed from favorites" + data: + system_id: "sys_123456789" + is_favorite: false + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + /systems/{id}/destroy: delete: operationId: destroySystem @@ -11727,11 +11784,18 @@ paths: summary: /systems/{id}/reachability - Check if system web UI is reachable description: | Checks if the system's web UI is reachable from the backend server. - The target URL is constructed from the system's FQDN and type: + When an admin set `ui_url`, only that address is tried. Otherwise the + target URL is constructed from the system's FQDN and type: - NS8: `https://{fqdn}/cluster-admin` - - NethSecurity: tries `https://{fqdn}:443` first, then `https://{fqdn}:9090` + - NethSecurity: tries `https://{fqdn}:9090` first, then `https://{fqdn}:443` + + Hosts that are not publicly routable are never probed, and read as not reachable. - Returns `reachable: true` with the responding `url` on success, or `reachable: false` if unreachable. + Returns `reachable: true` with the responding `url` on success. When + nothing responds, `reachable: false` comes with the `url` to open + anyway, since the check runs from the server and the system may still + open from the user's network; `url` is empty only when no address is + known yet. parameters: - name: id in: path @@ -11762,7 +11826,7 @@ paths: example: true url: type: string - description: The URL that responded successfully (empty if not reachable) + description: The URL that responded, or the one to open when none did (empty when no address is known yet) example: "https://firewall.example.com:9090" '400': $ref: '#/components/responses/BadRequest' @@ -12011,6 +12075,7 @@ paths: - $ref: '#/components/parameters/ParentOrganizationFilterParam' - $ref: '#/components/parameters/SystemStatusFilterParam' - $ref: '#/components/parameters/SystemAddonFilterParam' + - $ref: '#/components/parameters/SystemFavoriteFilterParam' responses: '200': description: Export file generated successfully diff --git a/backend/services/local/impersonation.go b/backend/services/local/impersonation.go index 16b341d5e..ed416864e 100644 --- a/backend/services/local/impersonation.go +++ b/backend/services/local/impersonation.go @@ -11,18 +11,15 @@ package local import ( "database/sql" - "fmt" - "strings" "time" "github.com/google/uuid" - "github.com/nethesis/my/backend/cache" "github.com/nethesis/my/backend/database" "github.com/nethesis/my/backend/logger" "github.com/nethesis/my/backend/models" ) -// ImpersonationService provides database operations for impersonation consent and audit +// ImpersonationService provides database operations for the impersonation audit type ImpersonationService struct { db *sql.DB } @@ -34,186 +31,6 @@ func NewImpersonationService() *ImpersonationService { } } -// ============================================================================= -// CONSENT MANAGEMENT -// ============================================================================= - -// EnableConsent creates or updates impersonation consent for a user -func (s *ImpersonationService) EnableConsent(userID string, durationHours int) (*models.ImpersonationConsent, error) { - // First, disable any existing consent - if err := s.DisableConsent(userID); err != nil { - logger.ComponentLogger("impersonation").Warn(). - Err(err). - Str("user_id", userID). - Msg("Failed to disable existing consent before enabling new one") - } - - consent := &models.ImpersonationConsent{ - ID: uuid.New().String(), - UserID: userID, - ExpiresAt: time.Now().Add(time.Duration(durationHours) * time.Hour), - MaxDurationMinutes: durationHours * 60, - CreatedAt: time.Now(), - Active: true, - } - - query := ` - INSERT INTO impersonation_consents (id, user_id, expires_at, max_duration_minutes, created_at, active) - VALUES ($1, $2, $3, $4, $5, $6) - ` - - _, err := s.db.Exec(query, consent.ID, consent.UserID, consent.ExpiresAt, consent.MaxDurationMinutes, consent.CreatedAt, consent.Active) - if err != nil { - logger.ComponentLogger("impersonation").Error(). - Err(err). - Str("user_id", userID). - Int("duration_hours", durationHours). - Msg("Failed to enable impersonation consent") - return nil, err - } - - logger.ComponentLogger("impersonation").Info(). - Str("consent_id", consent.ID). - Str("user_id", userID). - Int("duration_hours", durationHours). - Time("expires_at", consent.ExpiresAt). - Msg("Impersonation consent enabled successfully") - - return consent, nil -} - -// DisableConsent disables all active consent for a user -func (s *ImpersonationService) DisableConsent(userID string) error { - // First, clear all active impersonation sessions for this user - if err := s.InvalidateActiveSessionsForUser(userID); err != nil { - logger.ComponentLogger("impersonation").Warn(). - Err(err). - Str("user_id", userID). - Msg("Failed to invalidate active sessions when disabling consent") - // Continue with consent disabling even if session cleanup fails - } - - query := `UPDATE impersonation_consents SET active = FALSE WHERE user_id = $1 AND active = TRUE` - - result, err := s.db.Exec(query, userID) - if err != nil { - logger.ComponentLogger("impersonation").Error(). - Err(err). - Str("user_id", userID). - Msg("Failed to disable impersonation consent") - return err - } - - rowsAffected, _ := result.RowsAffected() - logger.ComponentLogger("impersonation").Info(). - Str("user_id", userID). - Int64("rows_affected", rowsAffected). - Msg("Impersonation consent disabled") - - return nil -} - -// GetConsentStatus retrieves the current consent status for a user -func (s *ImpersonationService) GetConsentStatus(userID string) (*models.ImpersonationConsent, error) { - query := ` - SELECT id, user_id, expires_at, max_duration_minutes, created_at, active - FROM impersonation_consents - WHERE user_id = $1 AND active = TRUE AND expires_at > NOW() - ORDER BY created_at DESC - LIMIT 1 - ` - - var consent models.ImpersonationConsent - err := s.db.QueryRow(query, userID).Scan( - &consent.ID, - &consent.UserID, - &consent.ExpiresAt, - &consent.MaxDurationMinutes, - &consent.CreatedAt, - &consent.Active, - ) - - if err == sql.ErrNoRows { - return nil, nil // No active consent - } - if err != nil { - logger.ComponentLogger("impersonation").Error(). - Err(err). - Str("user_id", userID). - Msg("Failed to get consent status") - return nil, err - } - - return &consent, nil -} - -// CanBeImpersonated checks if a user can currently be impersonated -func (s *ImpersonationService) CanBeImpersonated(userID string) (bool, error) { - consent, err := s.GetConsentStatus(userID) - if err != nil { - return false, err - } - return consent != nil, nil -} - -// CanBeImpersonatedBatch checks multiple users at once for impersonation consent -// Returns a map[userID]bool for efficient lookup. Much faster than N individual queries. -func (s *ImpersonationService) CanBeImpersonatedBatch(userIDs []string) (map[string]bool, error) { - if len(userIDs) == 0 { - return make(map[string]bool), nil - } - - result := make(map[string]bool) - - // Initialize all users to false - for _, userID := range userIDs { - result[userID] = false - } - - // Build placeholders for IN query ($1, $2, $3, ...) - placeholders := make([]string, len(userIDs)) - params := make([]interface{}, len(userIDs)) - for i, userID := range userIDs { - placeholders[i] = fmt.Sprintf("$%d", i+1) - params[i] = userID - } - - query := fmt.Sprintf(` - SELECT DISTINCT user_id - FROM impersonation_consents - WHERE user_id IN (%s) AND active = TRUE AND expires_at > NOW() - `, strings.Join(placeholders, ",")) - - rows, err := s.db.Query(query, params...) - if err != nil { - logger.ComponentLogger("impersonation").Error(). - Err(err). - Int("user_count", len(userIDs)). - Msg("Failed to batch check impersonation consent") - return result, err - } - defer func() { _ = rows.Close() }() - - // Mark users with active consent as true - for rows.Next() { - var userID string - if err := rows.Scan(&userID); err != nil { - logger.ComponentLogger("impersonation").Error(). - Err(err). - Msg("Failed to scan user ID from batch consent check") - continue - } - result[userID] = true - } - - logger.ComponentLogger("impersonation").Debug(). - Int("user_count", len(userIDs)). - Int("consents_found", len(result)). - Msg("Batch impersonation consent check completed") - - return result, nil -} - // ============================================================================= // AUDIT MANAGEMENT // ============================================================================= @@ -468,121 +285,3 @@ func (s *ImpersonationService) GetUserSessions(userID string, page, pageSize int return sessions, total, nil } - -// InvalidateActiveSessionsForUser invalidates all active impersonation sessions where the specified user is being impersonated -// This is called when a user revokes consent to ensure all active sessions are terminated -func (s *ImpersonationService) InvalidateActiveSessionsForUser(impersonatedUserID string) error { - sessionManager := cache.NewImpersonationSessionManager() - - // Query the audit database to find all unique impersonators who have active sessions with this user - query := ` - SELECT DISTINCT impersonator_user_id - FROM impersonation_audit a1 - WHERE a1.impersonated_user_id = $1 - AND a1.action_type = 'session_start' - AND NOT EXISTS ( - SELECT 1 - FROM impersonation_audit a2 - WHERE a2.session_id = a1.session_id - AND a2.action_type = 'session_end' - ) - AND a1.timestamp > NOW() - INTERVAL '24 hours' - ` - - // The audit table keys the target on its local id, the Redis session on - // its Logto ID (what the token and the status endpoint use): resolve the - // latter so the comparison below matches the record that was written. - var impersonatedLogtoID string - if err := s.db.QueryRow(`SELECT COALESCE(logto_id, '') FROM users WHERE id = $1`, impersonatedUserID).Scan(&impersonatedLogtoID); err != nil && err != sql.ErrNoRows { - return fmt.Errorf("failed to resolve impersonated user: %w", err) - } - - rows, err := s.db.Query(query, impersonatedUserID) - if err != nil { - logger.ComponentLogger("impersonation").Error(). - Err(err). - Str("impersonated_user_id", impersonatedUserID). - Msg("Failed to query for active session impersonators") - return fmt.Errorf("failed to query active sessions: %w", err) - } - defer func() { - if err := rows.Close(); err != nil { - logger.ComponentLogger("impersonation").Warn(). - Err(err). - Str("impersonated_user_id", impersonatedUserID). - Msg("Failed to close database rows") - } - }() - - var impersonators []string - for rows.Next() { - var impersonatorUserID string - if err := rows.Scan(&impersonatorUserID); err != nil { - logger.ComponentLogger("impersonation").Warn(). - Err(err). - Str("impersonated_user_id", impersonatedUserID). - Msg("Failed to scan impersonator user ID") - continue - } - impersonators = append(impersonators, impersonatorUserID) - } - - if err := rows.Err(); err != nil { - logger.ComponentLogger("impersonation").Error(). - Err(err). - Str("impersonated_user_id", impersonatedUserID). - Msg("Error iterating through impersonator results") - return fmt.Errorf("error reading query results: %w", err) - } - - // For each impersonator, check if they have an active session and clear it if it targets this user - clearedCount := 0 - for _, impersonatorUserID := range impersonators { - // Handle special case where impersonator_user_id is "owner" but actual Redis key uses empty string - redisKeyUserID := impersonatorUserID - if impersonatorUserID == "owner" { - redisKeyUserID = "" // Owner uses empty string as Redis key - } - - activeSession, err := sessionManager.GetActiveSession(redisKeyUserID) - if err != nil { - logger.ComponentLogger("impersonation").Warn(). - Err(err). - Str("impersonator_user_id", impersonatorUserID). - Str("redis_key_user_id", redisKeyUserID). - Str("impersonated_user_id", impersonatedUserID). - Msg("Failed to check active session for impersonator") - continue - } - - // If there's an active session and it targets our user, clear it - if activeSession != nil && (activeSession.ImpersonatedUserID == impersonatedUserID || (impersonatedLogtoID != "" && activeSession.ImpersonatedUserID == impersonatedLogtoID)) { - if err := sessionManager.ClearSession(redisKeyUserID); err != nil { - logger.ComponentLogger("impersonation").Warn(). - Err(err). - Str("impersonator_user_id", impersonatorUserID). - Str("redis_key_user_id", redisKeyUserID). - Str("impersonated_user_id", impersonatedUserID). - Str("session_id", activeSession.SessionID). - Msg("Failed to clear active impersonation session") - continue - } - - clearedCount++ - logger.ComponentLogger("impersonation").Info(). - Str("impersonator_user_id", impersonatorUserID). - Str("redis_key_user_id", redisKeyUserID). - Str("impersonated_user_id", impersonatedUserID). - Str("session_id", activeSession.SessionID). - Msg("Cleared active impersonation session due to consent revocation") - } - } - - logger.ComponentLogger("impersonation").Info(). - Str("impersonated_user_id", impersonatedUserID). - Int("sessions_cleared", clearedCount). - Int("impersonators_checked", len(impersonators)). - Msg("Completed invalidation of active sessions for user") - - return nil -} diff --git a/backend/services/local/systems.go b/backend/services/local/systems.go index 1cc982d4a..dd6802ca1 100644 --- a/backend/services/local/systems.go +++ b/backend/services/local/systems.go @@ -415,6 +415,13 @@ func (s *LocalSystemsService) UpdateSystem(systemID string, request *models.Upda if request.Notes != "" || request.Notes == "" { system.Notes = request.Notes } + if request.UIURL != nil { + uiURL, err := models.NormalizeUIURL(*request.UIURL, system.Type, system.FQDN) + if err != nil { + return nil, err + } + system.UIURL = uiURL + } system.UpdatedAt = now @@ -467,11 +474,11 @@ func (s *LocalSystemsService) UpdateSystem(systemID string, request *models.Upda // Note: type and system_key are not modifiable query := ` UPDATE systems - SET name = $2, organization_id = $3, custom_data = $4, notes = $5, updated_at = $6 + SET name = $2, organization_id = $3, custom_data = $4, notes = $5, updated_at = $6, ui_url = $7 WHERE id = $1 AND deleted_at IS NULL ` - _, err = database.DB.Exec(query, systemID, system.Name, system.Organization.LogtoID, customDataJSON, system.Notes, now) + _, err = database.DB.Exec(query, systemID, system.Name, system.Organization.LogtoID, customDataJSON, system.Notes, now, system.UIURL) if err != nil { return nil, fmt.Errorf("failed to update system: %w", err) } diff --git a/docs/docs/features/applications.md b/docs/docs/features/applications.md index 82ad25fc3..a8930075e 100644 --- a/docs/docs/features/applications.md +++ b/docs/docs/features/applications.md @@ -76,6 +76,8 @@ You can add notes to applications to record additional context or operational in 3. Add or edit your notes 4. Save changes +In the applications list, an icon next to the name of an application with notes shows them on hover (up to 10 lines). + ## Totals and Trends The [Dashboard](./dashboard.md) displays the total count of applications visible to your account, with a badge linking to the unassigned ones. Growth over time is available from the API through `/backend/api/applications/trend`. diff --git a/docs/docs/getting-started/account.md b/docs/docs/getting-started/account.md index 812feaae7..9a7a0e17e 100644 --- a/docs/docs/getting-started/account.md +++ b/docs/docs/getting-started/account.md @@ -4,7 +4,7 @@ sidebar_position: 2 # Account Settings -Manage your language, profile, avatar, password, API keys and impersonation consent. +Manage your language, profile, avatar, password and API keys, and review your impersonation sessions. ## Overview @@ -15,7 +15,7 @@ The Account page is reached from the user menu in the top-right corner. It is ma - **Avatar** -- your profile picture - **Change password** -- credential update - **API keys** -- credentials for programmatic access -- **Impersonation consent** -- whether administrators may act as you +- **Impersonation** -- the sessions in which Nethesis staff acted as you ## General Settings @@ -93,12 +93,14 @@ The new password must satisfy the platform policy: at least **12 characters**, w The Account page includes an **API Keys** section where you can create and revoke personal keys for programmatic access from external applications and scripts. For full details, see [API Keys](./api-keys.md). -## Impersonation Consent +## Impersonation -The **Impersonation** section controls whether Owner-organization administrators can temporarily use the platform as you. For how impersonation works, see [Impersonation](../platform/impersonation.md). +Nethesis staff (users of the Owner organization with the Staff role, or the `owner` account) can temporarily use the platform as you, to resolve technical issues or provide support. Your consent is not asked, and every session has a limited duration. + +The **Impersonation** section lists, under **Sessions**, every session in which you were impersonated: start, end, duration, impersonator and status. Click **Show audit log** on a session to see every action performed during it. For how impersonation works, see [Impersonation](../platform/impersonation.md). :::note -Consent is optional and always yours to revoke. With consent revoked, nobody can start a session as you. +The **Sessions** table is not available while you are impersonating another user. ::: ## Troubleshooting diff --git a/docs/docs/platform/impersonation.md b/docs/docs/platform/impersonation.md index 49e363359..64bcfb7f7 100644 --- a/docs/docs/platform/impersonation.md +++ b/docs/docs/platform/impersonation.md @@ -4,11 +4,11 @@ sidebar_position: 3 # User Impersonation -Learn how to use the impersonation feature to troubleshoot user issues while respecting privacy and consent. +Learn how Nethesis staff use impersonation to troubleshoot user issues, and how every session is audited. ## What is User Impersonation? -User impersonation allows authorized administrators to temporarily access My platform as another user. This feature is useful for: +User impersonation allows Nethesis staff to temporarily access My platform as another user. This feature is useful for: - **Troubleshooting**: Reproduce issues users are experiencing - **Support**: Help users with complex operations @@ -17,19 +17,21 @@ User impersonation allows authorized administrators to temporarily access My pla ## Key Features -### Privacy-Focused Design +### Transparency for Users -- **User Consent Required**: Users must explicitly enable impersonation -- **Time-Limited**: Users control how long impersonation is allowed (1-168 hours) -- **Complete Transparency**: All actions logged and visible to the user -- **Easy Revocation**: Users can disable consent at any time +- **Complete Transparency**: All actions are logged and visible to the impersonated user +- **Session History**: Users see every session in which they were impersonated, with its audit log +- **Time-Limited**: Every session lasts a fixed duration, then ends on its own ### Security Controls -- **Permission-Based**: Only Nethesis staff (Owner organization users) can impersonate +- **Permission-Based**: Only Nethesis staff (Owner organization users with the Staff role, or the `owner` account) can impersonate - **No Self-Impersonation**: Cannot impersonate your own account +- **Owner Account Protected**: The `owner` account can never be impersonated +- **Active Users Only**: Suspended or deleted users cannot be impersonated - **No Chaining**: Cannot impersonate while already impersonating another user -- **Automatic Expiration**: Consent automatically expires after user-defined duration +- **No API Keys**: Impersonation is not available to API keys +- **Automatic Expiration**: The session ends automatically after a fixed duration - **Session Tracking**: Each impersonation session has unique ID for audit ### Complete Audit Trail @@ -45,59 +47,43 @@ User impersonation allows authorized administrators to temporarily access My pla **Nethesis Staff (Owner Organization):** - Users of the Owner organization — Staff role or the `owner` account — hold the `impersonate:users` permission -- Can impersonate any user across the whole hierarchy (with their consent) +- Can impersonate any active user of the platform, in any distributor, reseller or customer +- The target user's consent is not required - No additional role assignment needed **Everyone Else:** - Cannot see impersonation features - Cannot impersonate any user -## Impersonation Workflow - -### Step 1: User Enables Consent - -Before impersonation can occur, the target user must enable consent. +## Session Duration -**For Users:** +Every impersonation session lasts a fixed duration, set by the platform administrator with the `IMPERSONATION_SESSION_DURATION` backend setting. The default is **1 hour**, and the maximum is **168 hours** (one week). -1. Log in to your account -2. Navigate to **Account Settings** > **Impersonation** -3. Find **Consent to Impersonation** section -4. Click **Enable Impersonation** -5. Set duration (1-168 hours) -6. Click **Save** +While impersonating, hover over the impersonation badge in the top bar to see how much time is left. When the time runs out, the session ends and you are logged in as yourself again. -**What happens:** -- Consent is recorded with timestamp -- Administrator is notified consent is available -- Expires automatically after duration -- Can be revoked at any time +To keep working, click **Extend session** in the same tooltip: the session restarts for its full duration from that moment, with no confirmation and no limit on the number of extensions. A notification confirms the new remaining time, and the extension appears in the session's audit log as **Session extended**. -**Duration Options:** -- **1-24 hours**: Short-term troubleshooting -- **24-72 hours**: Multi-day support -- **72-168 hours**: Extended access (max 1 week) +## Impersonation Workflow -### Step 2: Administrator Impersonates User +### Step 1: Administrator Impersonates User **For Administrators (Nethesis staff):** 1. Navigate to **Users** 2. Find the target user -3. Check if **Impersonate user** is available (using kebab menu) -4. Click **Impersonate User** -5. Confirm the action -6. You are now acting as that user +3. Click **Impersonate user** (using kebab menu) +4. Confirm the action +5. You are now acting as that user **During Impersonation:** You will see: -- **Banner at top**: "You are impersonating [User Name]" -- **Exit button**: Click to return to your account +- **Badge in the top bar**: "You are impersonating [User Name]" +- **Close icon**: Click it to return to your account - **All features**: Exactly as the user sees them - **User's permissions**: Filtered by their actual permissions -### Step 3: Perform Support Actions +### Step 2: Perform Support Actions While impersonating: @@ -111,73 +97,21 @@ While impersonating: All actions are logged and visible to the impersonated user. Treat user data with respect and exit impersonation when done. ::: -### Step 4: Exit Impersonation +### Step 3: Exit Impersonation **To exit impersonation:** -1. Click **Exit Impersonation** button in banner +1. Click the close icon on the impersonation badge in the top bar 2. You return to your original account -3. Impersonation session is closed +3. Impersonation session is closed and its token is revoked **Automatic Exit:** -- Session expires after user's consent duration -- If user revokes consent during impersonation -- If token expires (follows consent duration) - -## For Users: Managing Consent +- The session duration expires +- The impersonated user is suspended or deleted -### Enabling Impersonation Consent +## For Users: Viewing Your Impersonation Sessions -**When to enable:** -- When you have an issue and need support -- When requesting help from administrator -- Before training session -- When administrator asks for consent - -**How to enable:** - -1. Go to **Account Settings** > **Impersonation** -2. Click **Consent to Impersonation** -3. Choose duration: - ``` - 1 hour - Quick support - 24 hours - Same day support - 72 hours - Multi-day issue - Custom - Specify hours (max 168) - ``` -4. Click **Enable** - -**Confirmation:** -``` -Impersonation consent enabled - Expires: [Date and time] - Duration: [X] hours -``` - -### Checking Consent Status - -**To check if consent is active:** - -1. Go to **Account Settings** > **Impersonation** -2. View **Impersonation Consent** section: - ``` - Status: Active - Expires: 2025-11-07 10:30:00 UTC - ``` - -### Revoking Consent - -**To disable consent:** - -1. Go to **Account Settings** > **Impersonation** -2. Click **Revoke Consent** -3. Confirm the action - -**Effects:** -- Consent immediately disabled -- Active impersonation sessions terminated -- Administrator can no longer impersonate -- Can be re-enabled anytime +You are not asked for permission before a session starts. Instead, every session is recorded, and you can review it at any time. ### Viewing Impersonation Audit @@ -187,17 +121,18 @@ Impersonation consent enabled 2. Under **Sessions** 3. See complete history: ``` - Started: 2025-11-06 10:00:00 UTC - Ended: 2025-11-06 11:30:00 UTC - Duration: 1.5 hours + Start: 2025-11-06 10:00:00 UTC + End: 2025-11-06 11:00:00 UTC + Duration: 1 hour Impersonator: John Admin (john@example.com) - Status: Ongoing + Status: Completed ``` 4. Click **Show audit log** to see all actions **Audit Information:** - Date and time of each action +- Start, extensions and end of the session - API endpoint called - Sensitive data automatically redacted - Result (success/failure) @@ -208,21 +143,21 @@ Impersonation consent enabled **In user list:** -Users with active consent show: -- **Impersonate user** status enabled -- Consent expiration time -- Click to impersonate +The **Impersonate user** action is enabled for every user you can impersonate. -**Users without consent:** -- **Impersonate user** status disabled +It is disabled for: +- Your own account +- The `owner` account +- Suspended or deleted users ### Starting Impersonation **Requirements:** -- User has active consent - You belong to the Owner organization (Staff role or the `owner` account) - User is not deleted or suspended +- User is not you, and is not the `owner` account - You are not already impersonating someone +- You are signed in with your account, not with an API key **Steps:** @@ -230,13 +165,8 @@ Users with active consent show: - Navigate to **Users** - Search for target user -2. **Verify Consent**: - - Check **Impersonate user** status enabled - - Check consent expiration time - - Ensure sufficient time for your needs - -3. **Initiate Impersonation**: - - Click **Impersonate User** (using kebab menu) +2. **Initiate Impersonation**: + - Click **Impersonate user** (using kebab menu) - Confirm dialog: ``` You will temporarily act as user [Name] and have their permissions. @@ -247,10 +177,10 @@ Users with active consent show: [Cancel] [Impersonate user] ``` -4. **Confirmation**: +3. **Confirmation**: - You are now impersonating the user - - Banner appears at top - - Session starts + - Badge appears in the top bar + - Session starts, with the duration set by the platform ### During Impersonation Session @@ -283,15 +213,13 @@ Users with active consent show: **Normal Exit:** -- Click **X** button in banner +- Click the close icon on the impersonation badge in the top bar - Return to your account **Automatic Exit:** Impersonation automatically ends when: -- Consent duration expires -- User revokes consent -- Session token expires +- The session duration expires - You log out - User is suspended/deleted @@ -336,22 +264,20 @@ In the log, `endpoint` is the path as the backend sees it, after the proxy rewri ### Data Protection -**User Control:** -- Users choose when to enable consent -- Users control duration -- Users can revoke at any time -- Users see complete audit trail +**User Visibility:** +- Users see every session in which they were impersonated +- Users see the complete audit trail of each session **Platform Protection:** -- No access without consent -- Automatic expiration +- Impersonation reserved to Nethesis staff +- `owner` account, suspended and deleted users never impersonated +- Fixed session duration and automatic expiration - Complete logging - Sensitive data redaction **Compliance:** - Audit trail for regulatory requirements -- Consent-based access model -- User visibility and control +- User visibility on every session - Data privacy respected ## Common Use Cases @@ -361,40 +287,37 @@ In the log, `endpoint` is the path as the backend sees it, after the proxy rewri **Scenario:** User reports they cannot see a feature **Workflow:** -1. User enables impersonation consent (1 hour) -2. Administrator impersonates user -3. Administrator navigates to reported area -4. Reproduces issue -5. Identifies permission/configuration problem -6. Exits impersonation -7. Fixes issue in user's settings -8. User confirms fix +1. Administrator impersonates user +2. Administrator navigates to reported area +3. Reproduces issue +4. Identifies permission/configuration problem +5. Exits impersonation +6. Fixes issue in user's settings +7. User confirms fix ### Training New Users **Scenario:** Training user on complex workflow **Workflow:** -1. User enables impersonation (24 hours) -2. Administrator impersonates -3. Performs workflow steps -4. Documents each action -5. Exits impersonation -6. Shares audit with user -7. User reviews actions performed -8. User practices independently +1. Administrator impersonates user +2. Performs workflow steps +3. Documents each action +4. Exits impersonation +5. Shares audit with user +6. User reviews actions performed +7. User practices independently ### Permission Verification **Scenario:** Verify user has correct permissions **Workflow:** -1. User enables impersonation (1 hour) -2. Administrator impersonates -3. Tests access to various features -4. Documents what is visible/accessible -5. Exits impersonation -6. Adjusts permissions if needed +1. Administrator impersonates user +2. Tests access to various features +3. Documents what is visible/accessible +4. Exits impersonation +5. Adjusts permissions if needed ## Troubleshooting @@ -403,44 +326,30 @@ In the log, `endpoint` is the path as the backend sees it, after the proxy rewri **Problem:** Impersonate button is disabled **Solutions:** -1. Check user has enabled consent: - - Ask the user to enable it in **Account** > **Impersonation** - - Verify consent hasn't expired -2. Verify you have permissions: +1. Verify you have permissions: - You belong to the Owner organization (Staff role or the `owner` account) -3. Check user status: +2. Check user status: - User is not suspended - User is not deleted +3. Check the target: + - It is not your own account + - It is not the `owner` account 4. Verify not already impersonating: - Exit current impersonation first -### Consent Not Showing - -**Problem:** User enabled consent but administrator doesn't see it - -**Solutions:** -1. Refresh the page (Ctrl+F5) -2. Wait 30 seconds (cache propagation) -3. Check consent expiration time -4. Verify user saved the consent -5. Check user didn't accidentally revoke - ### Impersonation Session Ends Unexpectedly **Problem:** Kicked out of impersonation session **Possible Causes:** -- User revoked consent -- Consent duration expired -- Token expired -- User was suspended +- Session duration expired +- User was suspended or deleted - Network interruption **Solutions:** -1. Check if consent is still active -2. Ask user to re-enable consent -3. Check consent expiration time -4. Verify your network connection +1. Start a new impersonation session if you need more time +2. Check the user's status in **Users** +3. Verify your network connection ### Cannot See User's Data @@ -462,23 +371,16 @@ In the log, `endpoint` is the path as the backend sees it, after the proxy rewri ### For Users -**Enabling Consent:** -- Only enable when requested or needed -- Set minimum necessary duration -- Revoke when support is complete -- Review audit trail after impersonation - **Privacy:** -- Trust your administrators -- Consent is entirely voluntary -- You control when and how long -- You can see everything they did +- Review your impersonation sessions in **Account Settings** > **Impersonation** +- You can see everything that was done on your behalf +- Contact Nethesis if you find a session you do not expect ### For Administrators **Before Impersonating:** - Have clear purpose for impersonation -- Request user enable consent +- Inform the user, when possible - Plan what you need to do - Estimate time needed diff --git a/docs/docs/platform/organizations.md b/docs/docs/platform/organizations.md index 2848faed3..61ffd3582 100644 --- a/docs/docs/platform/organizations.md +++ b/docs/docs/platform/organizations.md @@ -153,7 +153,7 @@ Each organization type has its own list view: 1. Navigate to **[Type]** (Distributors/Resellers/Customers) 2. View the list with the following information: - - Organization name + - Organization name, with an icon that shows its notes on hover (up to 10 lines) when it has any - Description - Number of users - Number of systems @@ -189,13 +189,13 @@ Click on an organization to view detailed information: ### Deleting Organizations -**Delete archives, it does not erase.** The organization is soft-deleted and +**Delete keeps the data.** The organization is soft-deleted and disappears from the lists, and the same operation cascades down the hierarchy: -- Every **user** of the organization is archived -- Every **system** of the organization is archived +- Every **user** of the organization is deleted +- Every **system** of the organization is deleted - For a distributor or a reseller, every **child organization** in its - hierarchy is archived too, together with their users and systems + hierarchy is deleted too, together with their users and systems To delete an organization: @@ -205,7 +205,9 @@ To delete an organization: :::tip Reversible A deleted organization can be brought back with **Restore**, which -cascade-restores the users and systems archived along with it. +cascade-restores the users and systems deleted along with it. Only the Owner +organization sees deleted organizations and can restore them: for everyone +else, deletion is final. ::: :::danger Permanent deletion diff --git a/docs/docs/platform/users.md b/docs/docs/platform/users.md index 8c32fcc93..556c1a7e6 100644 --- a/docs/docs/platform/users.md +++ b/docs/docs/platform/users.md @@ -14,7 +14,7 @@ My uses a dual-role system combining business hierarchy with technical capabilit Automatically inherited from user's organization: -- **Owner**: Complete platform access (Nethesis only). Every member of the Owner organization has global visibility on all companies, systems and users, including archiving and destroying distributors, resellers and customers +- **Owner**: Complete platform access (Nethesis only). Every member of the Owner organization has global visibility on all companies, systems and users, including deleting, restoring and destroying distributors, resellers and customers - **Distributor**: Manages resellers and customers - **Reseller**: Manages customers - **Customer**: Views own organization data @@ -48,7 +48,7 @@ Manually assigned to users based on their job function: - **Staff** (Owner organization only): Nethesis cross-cutting staff - Manage systems, users, applications, alerts (including alert template configuration), add-ons, rebranding across all companies - - User impersonation (with the user's consent) and remote connection to systems + - User impersonation (any active user except the `owner` account, with every session audited) and remote connection to systems - Cannot permanently destroy systems or users :::note Role assignment rules @@ -138,7 +138,7 @@ Use filters to find specific users: - **Search by name or email**: Type in the search box - **Search by organization**: Select one or more organizations - **Search by role**: Admin, Backoffice, Support, Reader, Staff -- **Filter by status**: Enabled, Suspended, Archived, No login. "No login" selects +- **Filter by status**: Enabled, Suspended, Deleted (Owner organization only), No login. "No login" selects the accounts that never signed in since the invitation, the same ones flagged with the badge next to the name; it adds to the other statuses rather than narrowing them @@ -237,9 +237,9 @@ Re-enable a suspended account: ### Deleting a User -**Delete archives, it does not erase.** The user is soft-deleted: it disappears -from the lists and can no longer sign in, but the record is kept and can be -brought back with **Restore**. +**Delete keeps the record.** The user is soft-deleted: it disappears from the +lists and can no longer sign in, but the record is kept and the Owner +organization can bring it back with **Restore**. To delete a user: @@ -249,7 +249,8 @@ To delete a user: **Effects of deletion:** - The user can no longer sign in -- The account is archived, not erased -- **Restore** brings it back +- The account is kept, not erased -- the Owner organization can bring it back + with **Restore** - All audit logs are preserved - Systems created by this user remain @@ -258,7 +259,7 @@ To delete a user: - You need `manage:users` (Admin, Backoffice or Staff) :::danger Permanent deletion -Erasing a user for good is a separate operation and requires `destroy:users`, +**Destroy**, which erases a user for good, is a separate operation and requires `destroy:users`, which no assignable role holds -- only the bootstrap `owner` account. That one cannot be undone. ::: @@ -302,7 +303,7 @@ hierarchy. | Create and edit users | `manage:users` | Yes | Yes | Yes | No | No | | Reset a user's password | `manage:users` | Yes | Yes | Yes | No | No | | Suspend / reactivate a user | `manage:users` | Yes | Yes | Yes | No | No | -| Delete a user (archive) | `manage:users` | Yes | Yes | Yes | No | No | +| Delete a user (soft delete) | `manage:users` | Yes | Yes | Yes | No | No | | View systems | `read:systems` | Yes | Yes | Yes | Yes | Yes | | Create, edit and delete systems | `manage:systems` | Yes | Yes | No | Yes | No | | Silence alerts | `manage:systems` | Yes | Yes | No | Yes | No | diff --git a/docs/docs/systems/management.md b/docs/docs/systems/management.md index 9cd043043..367bb98b8 100644 --- a/docs/docs/systems/management.md +++ b/docs/docs/systems/management.md @@ -88,7 +88,7 @@ The `system_secret` is shown **only once** during creation. Copy and save it imm Navigate to **Systems** to see: -- System name +- System name, with a star to add it to your [favorites](#favorite-systems) and, when it has notes, an icon that shows them on hover (up to 10 lines) - Type (ns8, nsec, etc.) - Version, with an update icon when an update is available - FQDN and IP addresses @@ -108,16 +108,57 @@ Use filters to find specific systems: - **Created By**: Filter by user who created the system - **Add-on**: Filter by purchased add-on (see [Add-ons](../features/entitlements.md)) - **Status**: unknown, active, inactive, suspended, deleted -- **Sort By**: Name, version, FQDN/IP address, Organization, Created By, Status +- **Favorites**: all systems, or only the ones you starred (see [Favorite Systems](#favorite-systems)) +- **Sort By**: Name, version, FQDN/IP address, Organization, Created By, Status, Favorite The **Add-on** menu lists the add-ons held by at least one of your systems, so an option never comes back empty. Selecting more than one widens the search: a system matches when it holds any of them. Only add-ons that are valid at that moment count, so an expired or cancelled one leaves the system out. +### Favorite Systems + +Star the systems you work on most to find them quickly. Click the star next to +the system name, in the systems list or in the header of the system page; click +it again to remove the system from your favorites. In the systems list, the +star of a system that is not a favorite shows when you point at its row; the +**Add to favorites** and **Remove from favorites** options of the row's menu +do the same. + +- Favorites are personal: each user has their own, and starring a system + changes nothing for anyone else +- Every user who can see a system can star it, read-only roles included +- Your favorites follow you on every browser and device +- A deleted system leaves your favorites list and comes back when it is + restored; a destroyed one is removed for good +- While impersonating another user, their favorites are shown but cannot be + changed + +Use the **Favorites** filter to list only your favorites, or sort by +**Favorite** to bring them to the top. + ### System Details -Click on a system to view comprehensive information: +Click on a system to view comprehensive information. + +#### Opening the System + +The button at the top of the page opens the web interface of the system in a +new tab: **Open NethServer**, **Open NethSecurity**, or **Open system** while +the product is not known yet. The default address comes from the FQDN of the +latest inventory: + +- NethServer: `https:///cluster-admin` +- NethSecurity: `https://:9090` (the check also tries port 443) + +My checks whether the address answers. The check runs from the My server, not +from your browser: when it fails, a warning icon appears next to the button, +but the button still works, because the system may open from your network, for +example over a VPN. The button is disabled only while the address is unknown, +before the first inventory. + +If the web interface answers at another address, set it in **Web interface +URL** when editing the system. #### Overview Tab @@ -174,6 +215,9 @@ See [Inventory and Heartbeat](./inventory-heartbeat.md) for details. - Name - Organization - Notes + - Web interface URL, once the first inventory has told the product: the + address the **Open** button uses. Leave it empty to use the default one, + which follows the FQDN of later inventories 4. Click **Save system** :::tip @@ -227,27 +271,27 @@ Soft delete marks a system as deleted without removing data: - Cannot send inventory or heartbeat - Hidden from normal views - Its applications are hidden from lists, totals and organization counters until the system is restored (they are kept, not deleted) -- Can be restored if needed +- Can be restored by the Owner organization - All historical data is preserved -**To view deleted systems:** -1. Apply filter: Status = "deleted" +**To view deleted systems** (Owner organization only): +1. Apply filter: Status = Deleted 2. Select the deleted system 3. Click **Restore** to undelete -### Permanent Delete +### Destroy :::danger This operation is irreversible! ::: -To permanently delete: +To destroy a system: 1. Soft delete the system first 2. Navigate to deleted systems view 3. Select the system -4. Click **Permanent Delete** +4. Click **Destroy** 5. Type system name to confirm -6. Click **Delete** +6. Click **Destroy** **This will remove:** - System record diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/features/applications.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/features/applications.md index 1d6a54d0d..0bbdc9646 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/features/applications.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/features/applications.md @@ -73,6 +73,8 @@ Un'applicazione senza assegnazione non sparisce: torna a essere conteggiata sull 3. Aggiungi o modifica le note 4. Salva le modifiche +Nell'elenco delle applicazioni, un'icona accanto al nome di un'applicazione con note le mostra al passaggio del mouse (fino a 10 righe). + ## Totali e Trend La [Dashboard](./dashboard.md) mostra il totale delle applicazioni visibili al tuo account, con un badge che porta a quelle non assegnate. I dati di crescita nel tempo sono disponibili da API tramite `/backend/api/applications/trend`. diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/getting-started/account.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/getting-started/account.md index d7ceb2b69..7b4aa3114 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/getting-started/account.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/getting-started/account.md @@ -4,7 +4,7 @@ sidebar_position: 2 # Impostazioni Account -Gestione di lingua, profilo, avatar, password, API key e consenso all'impersonificazione. +Gestione di lingua, profilo, avatar, password e API key, e consultazione delle sessioni di impersonificazione. ## Panoramica @@ -15,7 +15,7 @@ La pagina Account è accessibile dal menu utente in alto a destra e si compone d - **Avatar** -- immagine del profilo - **Cambio password** -- aggiornamento credenziali - **API key** -- credenziali per l'accesso programmatico -- **Consenso impersonificazione** -- se gli amministratori possono agire al posto tuo +- **Impersonificazione** -- le sessioni in cui il personale Nethesis ha agito al posto tuo ## Impostazioni Generali @@ -93,12 +93,14 @@ La nuova password deve rispettare la policy della piattaforma: almeno **12 carat La pagina Account include una sezione **API key** dove puoi creare e revocare key personali per l'accesso programmatico da applicazioni e script esterni. Per i dettagli completi consulta [API Key](./api-keys.md). -## Consenso Impersonificazione +## Impersonificazione -La sezione **Impersonificazione** controlla se gli amministratori dell'organizzazione Owner possono usare temporaneamente la piattaforma al posto tuo. Per capire come funziona, vedi [Impersonificazione](../platform/impersonation.md). +Il personale Nethesis (utenti dell'organizzazione Owner con ruolo Staff, o l'account `owner`) può usare temporaneamente la piattaforma al posto tuo, per risolvere problemi tecnici o fornire supporto. Il tuo consenso non viene richiesto, e ogni sessione ha una durata limitata. + +La sezione **Impersonificazione** elenca, sotto **Sessioni**, ogni sessione in cui sei stato impersonificato: inizio, fine, durata, impersonatore e stato. Clicca su **Mostra audit log** in una sessione per vedere tutte le azioni compiute durante la sessione. Per capire come funziona, vedi [Impersonificazione](../platform/impersonation.md). :::note -Il consenso è facoltativo e sempre revocabile da te. Con il consenso revocato, nessuno può aprire una sessione a tuo nome. +La tabella **Sessioni** non è disponibile mentre stai impersonificando un altro utente. ::: ## Risoluzione Problemi diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/impersonation.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/impersonation.md index c5e41da3d..575904ffd 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/impersonation.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/impersonation.md @@ -4,11 +4,11 @@ sidebar_position: 3 # Impersonificazione Utente -Accesso temporaneo alla piattaforma come un altro utente, con il suo consenso e sotto audit completo. +Accesso temporaneo alla piattaforma come un altro utente, riservato al personale Nethesis e sotto audit completo. ## Cos'è l'Impersonificazione -L'impersonificazione permette agli amministratori autorizzati di accedere temporaneamente a My come un altro utente. È utile per: +L'impersonificazione permette al personale Nethesis di accedere temporaneamente a My come un altro utente. È utile per: - **Diagnosi**: riprodurre i problemi segnalati dagli utenti - **Supporto**: assistere gli utenti in operazioni complesse @@ -17,19 +17,21 @@ L'impersonificazione permette agli amministratori autorizzati di accedere tempor ## Caratteristiche Principali -### Progettata attorno alla Privacy +### Trasparenza verso l'Utente -- **Consenso obbligatorio**: l'utente deve abilitare esplicitamente l'impersonificazione -- **A tempo**: è l'utente a decidere per quanto resta permessa (1-168 ore) -- **Trasparenza totale**: tutte le azioni sono registrate e visibili all'utente -- **Revoca immediata**: l'utente può disattivare il consenso in qualsiasi momento +- **Trasparenza totale**: tutte le azioni sono registrate e visibili all'utente impersonificato +- **Storico delle sessioni**: l'utente vede ogni sessione in cui è stato impersonificato, con il relativo log di audit +- **A tempo**: ogni sessione ha una durata fissa e poi termina da sola ### Controlli di Sicurezza -- **Basata sui permessi**: solo il personale Nethesis (utenti dell'organizzazione Owner) può impersonificare +- **Basata sui permessi**: solo il personale Nethesis (utenti dell'organizzazione Owner con ruolo Staff, o l'account `owner`) può impersonificare - **Nessuna auto-impersonificazione**: non si può impersonificare il proprio account +- **Account owner protetto**: l'account `owner` non può mai essere impersonificato +- **Solo utenti attivi**: gli utenti sospesi o eliminati non possono essere impersonificati - **Nessun concatenamento**: non si può impersonificare mentre si sta già impersonificando qualcun altro -- **Scadenza automatica**: il consenso scade da solo alla durata scelta dall'utente +- **Nessuna API key**: l'impersonificazione non è disponibile alle API key +- **Scadenza automatica**: la sessione termina da sola dopo una durata fissa - **Tracciamento di sessione**: ogni sessione ha un identificativo univoco per l'audit ### Tracciabilità Completa @@ -45,57 +47,41 @@ L'impersonificazione permette agli amministratori autorizzati di accedere tempor **Personale Nethesis (organizzazione Owner):** - Gli utenti dell'organizzazione Owner — ruolo Staff o account `owner` — hanno il permesso `impersonate:users` -- Possono impersonificare qualsiasi utente dell'intera gerarchia (con il suo consenso) +- Possono impersonificare qualsiasi utente attivo della piattaforma, in qualsiasi distributore, rivenditore o cliente +- Il consenso dell'utente bersaglio non è richiesto - Non serve assegnare altri ruoli **Tutti gli altri:** - Non vedono le funzionalità di impersonificazione - Non possono impersonificare nessun utente -## Flusso di Lavoro - -### Passo 1: L'Utente Abilita il Consenso - -Prima che l'impersonificazione possa avvenire, l'utente bersaglio deve abilitare il consenso. +## Durata della Sessione -**Per gli utenti:** +Ogni sessione di impersonificazione ha una durata fissa, stabilita dall'amministratore della piattaforma con l'impostazione del backend `IMPERSONATION_SESSION_DURATION`. Il valore predefinito è **1 ora**, il massimo è **168 ore** (una settimana). -1. Accedi al tuo account -2. Vai su **Account** > **Impersonificazione** -3. Individua la sezione **Consenso all'impersonificazione** -4. Clicca su **Abilita impersonificazione** -5. Imposta la durata (1-168 ore) -6. Clicca su **Salva** +Durante l'impersonificazione, passa il mouse sul badge di impersonificazione nella barra superiore per vedere il tempo rimanente. Allo scadere del tempo la sessione termina e torni a usare il tuo account. -**Cosa succede:** -- Il consenso viene registrato con data e ora -- L'amministratore vede che il consenso è disponibile -- Scade automaticamente alla fine della durata -- Può essere revocato in qualsiasi momento +Per continuare a lavorare, clicca su **Estendi sessione** nello stesso tooltip: la sessione riparte per la sua durata completa da quel momento, senza conferma e senza un limite al numero di estensioni. Una notifica conferma il nuovo tempo rimanente, e l'estensione compare nell'audit log della sessione come **Sessione estesa**. -**Durate tipiche:** -- **1-24 ore**: diagnosi rapida -- **24-72 ore**: supporto su più giorni -- **72-168 ore**: accesso prolungato (massimo una settimana) +## Flusso di Lavoro -### Passo 2: L'Amministratore Impersonifica l'Utente +### Passo 1: L'Amministratore Impersonifica l'Utente **Per gli amministratori (personale Nethesis):** 1. Vai su **Utenti** 2. Trova l'utente bersaglio -3. Controlla che **Impersonifica utente** sia disponibile (dal menu contestuale) -4. Clicca su **Impersonifica utente** -5. Conferma l'operazione -6. Da quel momento stai agendo come quell'utente +3. Clicca su **Impersona utente** (dal menu contestuale) +4. Conferma l'operazione +5. Da quel momento stai agendo come quell'utente **Durante l'impersonificazione vedrai:** -- **Banner in alto**: "Stai impersonificando [Nome Utente]" -- **Pulsante di uscita**: per tornare al tuo account +- **Badge nella barra superiore**: "Stai impersonando [Nome Utente]" +- **Icona di chiusura**: per tornare al tuo account - **Tutte le funzionalità**: esattamente come le vede l'utente - **I permessi dell'utente**: filtrati sui suoi permessi reali -### Passo 3: Svolgere le Azioni di Supporto +### Passo 2: Svolgere le Azioni di Supporto Mentre impersonifichi: @@ -109,73 +95,21 @@ Mentre impersonifichi: Tutte le azioni vengono registrate e sono visibili all'utente impersonificato. Tratta i suoi dati con rispetto ed esci dall'impersonificazione appena hai finito. ::: -### Passo 4: Uscire dall'Impersonificazione +### Passo 3: Uscire dall'Impersonificazione **Per uscire:** -1. Clicca sul pulsante **Esci dall'impersonificazione** nel banner +1. Clicca sull'icona di chiusura del badge di impersonificazione nella barra superiore 2. Torni al tuo account originale -3. La sessione di impersonificazione viene chiusa +3. La sessione di impersonificazione viene chiusa e il suo token revocato **Uscita automatica:** -- La sessione scade alla fine della durata del consenso -- L'utente revoca il consenso durante la sessione -- Il token scade (segue la durata del consenso) - -## Per gli Utenti: Gestione del Consenso +- La durata della sessione scade +- L'utente impersonificato viene sospeso o eliminato -### Attivazione del Consenso +## Per gli Utenti: Le Tue Sessioni di Impersonificazione -**Quando attivarlo:** -- Quando hai un problema e ti serve assistenza -- Quando chiedi aiuto a un amministratore -- Prima di una sessione di formazione -- Quando l'amministratore te lo chiede - -**Come attivarlo:** - -1. Vai su **Account** > **Impersonificazione** -2. Clicca su **Consenso all'impersonificazione** -3. Scegli la durata: - ``` - 1 ora - Supporto rapido - 24 ore - Supporto in giornata - 72 ore - Problema su più giorni - Custom - Specifica le ore (massimo 168) - ``` -4. Clicca su **Abilita** - -**Conferma:** -``` -Consenso all'impersonificazione abilitato - Scade: [data e ora] - Durata: [X] ore -``` - -### Verifica dello Stato del Consenso - -**Per controllare se il consenso è attivo:** - -1. Vai su **Account** > **Impersonificazione** -2. Guarda la sezione **Consenso all'impersonificazione**: - ``` - Stato: Attivo - Scade: 2025-11-07 10:30:00 UTC - ``` - -### Revoca del Consenso - -**Per disattivare il consenso:** - -1. Vai su **Account** > **Impersonificazione** -2. Clicca su **Revoca consenso** -3. Conferma l'operazione - -**Effetti:** -- Il consenso viene disabilitato immediatamente -- Le sessioni di impersonificazione attive vengono terminate -- L'amministratore non può più impersonificarti -- Puoi riabilitarlo quando vuoi +Prima che una sessione inizi non ti viene chiesto alcun permesso. In compenso ogni sessione viene registrata, e puoi rivederla quando vuoi. ### Visualizzazione dell'Audit @@ -186,16 +120,17 @@ Consenso all'impersonificazione abilitato 3. Trovi lo storico completo: ``` Inizio: 2025-11-06 10:00:00 UTC - Fine: 2025-11-06 11:30:00 UTC - Durata: 1,5 ore - Impersonificatore: John Admin (john@example.com) - Stato: In corso + Fine: 2025-11-06 11:00:00 UTC + Durata: 1 ora + Impersonatore: John Admin (john@example.com) + Stato: Completata ``` -4. Clicca su **Mostra log di audit** per vedere tutte le azioni +4. Clicca su **Mostra audit log** per vedere tutte le azioni **Informazioni registrate:** - Data e ora di ogni azione +- Inizio, estensioni e fine della sessione - Endpoint API chiamato - Dati sensibili oscurati automaticamente - Esito (successo/errore) @@ -206,21 +141,21 @@ Consenso all'impersonificazione abilitato **Nell'elenco utenti:** -Gli utenti con consenso attivo mostrano: -- La voce **Impersonifica utente** abilitata -- La data di scadenza del consenso -- Il click avvia l'impersonificazione +La voce **Impersona utente** è abilitata per ogni utente che puoi impersonificare. -**Gli utenti senza consenso:** -- Hanno la voce **Impersonifica utente** disabilitata +È disabilitata per: +- Il tuo account +- L'account `owner` +- Gli utenti sospesi o eliminati ### Avvio dell'Impersonificazione **Requisiti:** -- L'utente ha un consenso attivo - Appartieni all'organizzazione Owner (ruolo Staff o account `owner`) - L'utente non è eliminato né sospeso +- L'utente non sei tu e non è l'account `owner` - Non stai già impersonificando qualcun altro +- Hai effettuato l'accesso con il tuo account, non con una API key **Procedura:** @@ -228,27 +163,22 @@ Gli utenti con consenso attivo mostrano: - Vai su **Utenti** - Cerca l'utente bersaglio -2. **Verifica il consenso**: - - Controlla che **Impersonifica utente** sia abilitato - - Controlla la scadenza del consenso - - Assicurati che il tempo residuo ti basti - -3. **Avvia l'impersonificazione**: - - Clicca su **Impersonifica utente** (dal menu contestuale) +2. **Avvia l'impersonificazione**: + - Clicca su **Impersona utente** (dal menu contestuale) - Conferma nel dialogo: ``` Agirai temporaneamente come l'utente [Nome] e avrai i suoi permessi. - Per tornare al tuo account, clicca sull'icona di chiusura sul badge - di impersonificazione nella barra in alto. + Per tornare al tuo account, clicca sull'icona di chiusura nel badge + di impersonificazione nella barra superiore. - [Annulla] [Impersonifica utente] + [Annulla] [Impersona utente] ``` -4. **Conferma**: +3. **Conferma**: - Stai impersonificando l'utente - - Compare il banner in alto - - La sessione è iniziata + - Compare il badge nella barra superiore + - La sessione è iniziata, con la durata stabilita dalla piattaforma ### Durante la Sessione @@ -281,15 +211,13 @@ Gli utenti con consenso attivo mostrano: **Uscita normale:** -- Clicca sulla **X** nel banner +- Clicca sull'icona di chiusura del badge di impersonificazione nella barra superiore - Torni al tuo account **Uscita automatica:** L'impersonificazione termina da sola quando: -- La durata del consenso scade -- L'utente revoca il consenso -- Il token di sessione scade +- La durata della sessione scade - Effettui il logout - L'utente viene sospeso o eliminato @@ -334,22 +262,20 @@ Nel log l'`endpoint` è il percorso come lo vede il backend, dopo il rewrite del ### Protezione dei Dati -**Controllo dell'utente:** -- È l'utente a scegliere quando abilitare il consenso -- È l'utente a decidere la durata -- L'utente può revocare in qualsiasi momento -- L'utente vede la tracciabilità completa +**Visibilità per l'utente:** +- L'utente vede ogni sessione in cui è stato impersonificato +- L'utente vede la tracciabilità completa di ogni sessione **Protezione della piattaforma:** -- Nessun accesso senza consenso -- Scadenza automatica +- Impersonificazione riservata al personale Nethesis +- L'account `owner` e gli utenti sospesi o eliminati non sono mai impersonificabili +- Durata fissa della sessione e scadenza automatica - Registrazione completa - Oscuramento dei dati sensibili **Conformità:** - Tracciabilità per i requisiti normativi -- Modello di accesso basato sul consenso -- Visibilità e controllo in capo all'utente +- Visibilità dell'utente su ogni sessione - Privacy dei dati rispettata ## Casi d'Uso Comuni @@ -359,40 +285,37 @@ Nel log l'`endpoint` è il percorso come lo vede il backend, dopo il rewrite del **Scenario:** un utente segnala di non vedere una funzionalità **Flusso:** -1. L'utente abilita il consenso (1 ora) -2. L'amministratore lo impersonifica -3. L'amministratore va nella sezione segnalata -4. Riproduce il problema -5. Individua il problema di permessi o configurazione -6. Esce dall'impersonificazione -7. Corregge le impostazioni dell'utente -8. L'utente conferma la risoluzione +1. L'amministratore impersonifica l'utente +2. L'amministratore va nella sezione segnalata +3. Riproduce il problema +4. Individua il problema di permessi o configurazione +5. Esce dall'impersonificazione +6. Corregge le impostazioni dell'utente +7. L'utente conferma la risoluzione ### Formazione di Nuovi Utenti **Scenario:** formazione su un flusso di lavoro complesso **Flusso:** -1. L'utente abilita il consenso (24 ore) -2. L'amministratore lo impersonifica -3. Esegue i passaggi del flusso -4. Documenta ogni azione -5. Esce dall'impersonificazione -6. Condivide l'audit con l'utente -7. L'utente rivede le azioni compiute -8. L'utente si esercita in autonomia +1. L'amministratore impersonifica l'utente +2. Esegue i passaggi del flusso +3. Documenta ogni azione +4. Esce dall'impersonificazione +5. Condivide l'audit con l'utente +6. L'utente rivede le azioni compiute +7. L'utente si esercita in autonomia ### Verifica dei Permessi **Scenario:** verificare che un utente abbia i permessi corretti **Flusso:** -1. L'utente abilita il consenso (1 ora) -2. L'amministratore lo impersonifica -3. Prova l'accesso alle varie funzionalità -4. Documenta cosa è visibile e accessibile -5. Esce dall'impersonificazione -6. Corregge i permessi se necessario +1. L'amministratore impersonifica l'utente +2. Prova l'accesso alle varie funzionalità +3. Documenta cosa è visibile e accessibile +4. Esce dall'impersonificazione +5. Corregge i permessi se necessario ## Risoluzione Problemi @@ -401,44 +324,30 @@ Nel log l'`endpoint` è il percorso come lo vede il backend, dopo il rewrite del **Problema:** il pulsante di impersonificazione è disabilitato **Soluzioni:** -1. Controlla che l'utente abbia abilitato il consenso: - - Chiedigli di abilitarlo in **Account** > **Impersonificazione** - - Verifica che il consenso non sia scaduto -2. Verifica di avere i permessi: +1. Verifica di avere i permessi: - Devi appartenere all'organizzazione Owner (ruolo Staff o account `owner`) -3. Controlla lo stato dell'utente: +2. Controlla lo stato dell'utente: - L'utente non deve essere sospeso - L'utente non deve essere eliminato +3. Controlla l'utente bersaglio: + - Non deve essere il tuo account + - Non deve essere l'account `owner` 4. Verifica di non stare già impersonificando: - Esci prima dall'impersonificazione in corso -### Consenso Non Mostrato - -**Problema:** l'utente ha abilitato il consenso ma l'amministratore non lo vede - -**Soluzioni:** -1. Ricarica la pagina (Ctrl+F5) -2. Aspetta 30 secondi (propagazione della cache) -3. Controlla la scadenza del consenso -4. Verifica che l'utente abbia salvato il consenso -5. Controlla che non l'abbia revocato per errore - ### La Sessione Termina Inaspettatamente **Problema:** vieni espulso dalla sessione di impersonificazione **Cause possibili:** -- L'utente ha revocato il consenso -- La durata del consenso è scaduta -- Il token è scaduto -- L'utente è stato sospeso +- La durata della sessione è scaduta +- L'utente è stato sospeso o eliminato - Interruzione di rete **Soluzioni:** -1. Controlla se il consenso è ancora attivo -2. Chiedi all'utente di riabilitarlo -3. Controlla la scadenza del consenso -4. Verifica la tua connessione di rete +1. Avvia una nuova sessione di impersonificazione se ti serve altro tempo +2. Controlla lo stato dell'utente in **Utenti** +3. Verifica la tua connessione di rete ### Non Vedi i Dati dell'Utente @@ -460,22 +369,16 @@ Nel log l'`endpoint` è il percorso come lo vede il backend, dopo il rewrite del ### Per gli Utenti -**Abilitare il consenso:** -- Abilitalo solo quando serve o ti viene chiesto -- Imposta la durata minima necessaria -- Revocalo quando il supporto è concluso -- Rivedi l'audit dopo l'impersonificazione - **Privacy:** -- Il consenso è del tutto volontario -- Sei tu a decidere quando e per quanto -- Puoi vedere tutto quello che è stato fatto +- Rivedi le tue sessioni di impersonificazione in **Account** > **Impersonificazione** +- Puoi vedere tutto quello che è stato fatto a tuo nome +- Contatta Nethesis se trovi una sessione che non ti aspetti ### Per gli Amministratori **Prima di impersonificare:** - Abbi uno scopo chiaro -- Chiedi all'utente di abilitare il consenso +- Avvisa l'utente, quando possibile - Pianifica cosa devi fare - Stima il tempo necessario diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md index 5fba6f38d..5f19d8676 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md @@ -153,7 +153,7 @@ Ogni tipo di organizzazione ha il proprio elenco: 1. Vai su **[Tipo]** (Distributori/Rivenditori/Clienti) 2. L'elenco mostra: - - Nome dell'organizzazione + - Nome dell'organizzazione, con un'icona che ne mostra le note al passaggio del mouse (fino a 10 righe), se ne ha - Descrizione - Numero di utenti - Numero di sistemi @@ -189,13 +189,13 @@ Cliccando su un'organizzazione si accede alle informazioni di dettaglio: ### Eliminazione -**L'eliminazione archivia, non cancella.** L'organizzazione viene eliminata in +**L'eliminazione conserva i dati.** L'organizzazione viene eliminata in modo soft e sparisce dagli elenchi, e la stessa operazione si propaga lungo la gerarchia: -- Ogni **utente** dell'organizzazione viene archiviato -- Ogni **sistema** dell'organizzazione viene archiviato -- Per un distributore o un rivenditore, viene archiviata anche ogni +- Ogni **utente** dell'organizzazione viene eliminato +- Ogni **sistema** dell'organizzazione viene eliminato +- Per un distributore o un rivenditore, viene eliminata anche ogni **organizzazione figlia** della sua gerarchia, con i relativi utenti e sistemi Per eliminare un'organizzazione: @@ -207,11 +207,13 @@ Per eliminare un'organizzazione: :::tip Reversibile Un'organizzazione eliminata può essere recuperata con **Ripristina**, che -ripristina a cascata anche gli utenti e i sistemi archiviati insieme a lei. +ripristina a cascata anche gli utenti e i sistemi eliminati insieme a lei. Solo +l'organizzazione Owner vede le organizzazioni eliminate e può ripristinarle: per +tutti gli altri l'eliminazione è definitiva. ::: -:::danger Eliminazione definitiva -**Elimina definitivamente** è l'operazione irreversibile: cancella +:::danger Distruzione +**Distruggi** è l'operazione irreversibile: cancella l'organizzazione per sempre e non si può annullare. Richiede il permesso `destroy:` su quella risorsa, che ha solo l'organizzazione Owner. ::: diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/users.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/users.md index 8757d73c2..454ad54f2 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/users.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/users.md @@ -14,7 +14,7 @@ My usa un sistema a doppio ruolo che combina la gerarchia commerciale con le cap Ereditati automaticamente dall'organizzazione dell'utente: -- **Owner**: accesso completo alla piattaforma (solo Nethesis). Ogni membro dell'organizzazione Owner ha visibilità globale su tutte le aziende, i sistemi e gli utenti, inclusa l'archiviazione e l'eliminazione definitiva di distributori, rivenditori e clienti +- **Owner**: accesso completo alla piattaforma (solo Nethesis). Ogni membro dell'organizzazione Owner ha visibilità globale su tutte le aziende, i sistemi e gli utenti, inclusi l'eliminazione, il ripristino e la distruzione di distributori, rivenditori e clienti - **Distributore**: gestisce rivenditori e clienti - **Rivenditore**: gestisce i clienti - **Cliente**: vede i dati della propria organizzazione @@ -48,7 +48,7 @@ Assegnati manualmente in base alla funzione lavorativa: - **Staff** (solo organizzazione Owner): personale trasversale Nethesis - Gestione di sistemi, utenti, applicazioni, allarmi (inclusa la configurazione dei template), add-on e rebranding su tutte le aziende - - Impersonificazione degli utenti (con il loro consenso) e connessione remota ai sistemi + - Impersonificazione degli utenti (qualsiasi utente attivo tranne l'account `owner`, con ogni sessione sotto audit) e connessione remota ai sistemi - Non può eliminare definitivamente sistemi o utenti :::note Regole di assegnazione @@ -138,7 +138,7 @@ Usa i filtri per trovare utenti specifici: - **Ricerca per nome o email**: digita nella casella di ricerca - **Ricerca per organizzazione**: seleziona una o più organizzazioni - **Ricerca per ruolo**: Admin, Backoffice, Support, Reader, Staff -- **Filtro per stato**: Abilitato, Sospeso, Archiviato, Nessun accesso. "Nessun +- **Filtro per stato**: Abilitato, Sospeso, Eliminato (solo organizzazione Owner), Nessun accesso. "Nessun accesso" seleziona gli account che non hanno mai effettuato l'accesso dall'invito, gli stessi segnalati dal badge accanto al nome; si somma agli altri stati invece di restringerli @@ -237,7 +237,7 @@ Riabilita un account sospeso: ### Eliminazione -**L'eliminazione archivia, non cancella.** L'utente viene eliminato in modo +**L'eliminazione conserva il record.** L'utente viene eliminato in modo soft: sparisce dagli elenchi e non può più accedere, ma il record resta e può essere recuperato con **Ripristina**. @@ -249,7 +249,8 @@ Per eliminare un utente: **Effetti dell'eliminazione:** - L'utente non può più accedere -- L'account viene archiviato, non cancellato -- **Ripristina** lo riporta indietro +- L'account viene conservato, non cancellato -- l'organizzazione Owner può + riportarlo indietro con **Ripristina** - I log di audit vengono conservati - I sistemi creati da quell'utente restano @@ -257,8 +258,8 @@ Per eliminare un utente: - Non è possibile eliminare il proprio account - Serve `manage:users` (Admin, Backoffice o Staff) -:::danger Eliminazione definitiva -Cancellare un utente per sempre è un'operazione separata e richiede +:::danger Distruzione +**Distruggi**, che cancella un utente per sempre, è un'operazione separata e richiede `destroy:users`, che non appartiene a nessun ruolo assegnabile: solo l'account `owner` creato all'installazione. Quella non è reversibile. ::: @@ -302,7 +303,7 @@ ruolo utente -- con una sola eccezione: al Reader vengono tolti i permessi | Crea e modifica utenti | `manage:users` | Sì | Sì | Sì | No | No | | Reset password di un utente | `manage:users` | Sì | Sì | Sì | No | No | | Sospendi / riattiva un utente | `manage:users` | Sì | Sì | Sì | No | No | -| Elimina un utente (archiviazione) | `manage:users` | Sì | Sì | Sì | No | No | +| Elimina un utente (eliminazione soft) | `manage:users` | Sì | Sì | Sì | No | No | | Visualizza sistemi | `read:systems` | Sì | Sì | Sì | Sì | Sì | | Crea, modifica ed elimina sistemi | `manage:systems` | Sì | Sì | No | Sì | No | | Silenzia allarmi | `manage:systems` | Sì | Sì | No | Sì | No | @@ -325,7 +326,7 @@ Per esportare un elenco basta il permesso `read:` di quella risorsa, quindi ogni ruolo può esportare ciò che vede -- Support compreso, tranne gli utenti, che non può leggere. -:::note Eliminazione definitiva +:::note Distruzione `destroy:systems` e `destroy:users` non appartengono a nessun ruolo assegnabile, Staff incluso. Sono solo dell'account `owner` creato all'installazione, che è anche l'unico a poter creare e gestire gli utenti dell'organizzazione Owner. diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md index 9f5b50c93..0d33d656b 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md @@ -83,7 +83,7 @@ Il `system_secret` viene mostrato **una sola volta**, alla creazione. Copialo e La pagina **Sistemi** mostra tutti i sistemi visibili con: -- Nome del sistema +- Nome del sistema, con una stella per aggiungerlo ai [preferiti](#sistemi-preferiti) e, se ha delle note, un'icona che le mostra al passaggio del mouse (fino a 10 righe) - Tipo (NethServer o NethSecurity) - Versione, con un'icona di aggiornamento quando è disponibile un aggiornamento - Organizzazione @@ -101,7 +101,8 @@ Usa i filtri per trovare sistemi specifici: - **Creato da**: filtra per utente che ha creato il sistema - **Add-on**: filtra per add-on acquistato (vedi [Add-on](../features/entitlements.md)) - **Stato**: unknown, active, inactive, suspended, deleted -- **Ordinamento**: nome, versione, FQDN/indirizzo IP, organizzazione, creato da, stato +- **Preferiti**: tutti i sistemi, o solo quelli che hai aggiunto ai preferiti (vedi [Sistemi preferiti](#sistemi-preferiti)) +- **Ordinamento**: nome, versione, FQDN/indirizzo IP, organizzazione, creato da, stato, preferito Il menu **Add-on** elenca gli add-on posseduti da almeno uno dei tuoi sistemi, quindi un'opzione non restituisce mai un elenco vuoto. Selezionandone più di uno @@ -109,9 +110,50 @@ la ricerca si allarga: un sistema corrisponde se ne possiede almeno uno. Contano solo gli add-on validi in quel momento, quindi uno scaduto o annullato esclude il sistema. +### Sistemi Preferiti + +Aggiungi ai preferiti i sistemi su cui lavori più spesso per trovarli subito. +Fai clic sulla stella accanto al nome del sistema, nell'elenco dei sistemi o +nell'intestazione della pagina del sistema; fai clic di nuovo per rimuoverlo dai +preferiti. Nell'elenco dei sistemi, la stella di un sistema che non è tra i +preferiti appare quando passi il mouse sulla sua riga; le opzioni **Aggiungi ai +preferiti** e **Rimuovi dai preferiti** del menu della riga fanno lo stesso. + +- I preferiti sono personali: ogni utente ha i suoi, e aggiungere un sistema ai + preferiti non cambia nulla per gli altri +- Ogni utente che vede un sistema può aggiungerlo ai preferiti, anche con un + ruolo di sola lettura +- I preferiti ti seguono su ogni browser e dispositivo +- Un sistema eliminato esce dall'elenco dei preferiti e ci torna quando viene + ripristinato; uno distrutto viene rimosso per sempre +- Mentre impersoni un altro utente vedi i suoi preferiti, ma non puoi + modificarli + +Usa il filtro **Preferiti** per elencare solo i tuoi preferiti, oppure ordina per +**Preferito** per portarli in cima. + ### Dettagli Sistema -Cliccando su un sistema si accede alle informazioni complete: +Cliccando su un sistema si accede alle informazioni complete. + +#### Apertura del Sistema + +Il pulsante in alto nella pagina apre l'interfaccia web del sistema in una +nuova scheda: **Apri NethServer**, **Apri NethSecurity**, oppure **Apri +sistema** finché il prodotto non è noto. L'indirizzo predefinito deriva +dall'FQDN dell'ultimo inventario: + +- NethServer: `https:///cluster-admin` +- NethSecurity: `https://:9090` (la verifica prova anche la porta 443) + +My verifica se l'indirizzo risponde. La verifica parte dal server di My, non +dal tuo browser: se fallisce, accanto al pulsante compare un'icona di +avviso, ma il pulsante funziona comunque, perché il sistema potrebbe aprirsi +dalla tua rete, ad esempio tramite VPN. Il pulsante è disabilitato solo +finché l'indirizzo non è noto, prima del primo inventario. + +Se l'interfaccia web risponde a un altro indirizzo, impostalo in **URL +dell'interfaccia web** modificando il sistema. #### Tab Panoramica @@ -168,6 +210,9 @@ Vedi [Inventario e Heartbeat](./inventory-heartbeat.md) per i dettagli. - Nome - Organizzazione - Note + - URL dell'interfaccia web, quando il primo inventario ha indicato il + prodotto: l'indirizzo usato dal pulsante **Apri**. Lascialo vuoto per + usare quello predefinito, che segue l'FQDN degli inventari successivi 4. Clicca su **Salva** :::note @@ -217,27 +262,27 @@ L'eliminazione soft marca il sistema come eliminato senza rimuovere i dati: - Non può più inviare inventario o heartbeat - Sparisce dalle viste normali - Le sue applicazioni spariscono da elenchi, totali e contatori delle organizzazioni finché il sistema non viene ripristinato (vengono conservate, non cancellate) -- Può essere ripristinato in qualsiasi momento +- Può essere ripristinato dall'organizzazione Owner - Tutti i dati storici vengono conservati -**Per vedere i sistemi eliminati:** -1. Applica il filtro Stato = "deleted" +**Per vedere i sistemi eliminati** (solo organizzazione Owner): +1. Applica il filtro Stato = Eliminato 2. Seleziona il sistema eliminato 3. Clicca su **Ripristina** -### Eliminazione Permanente +### Distruzione :::danger Questa operazione è irreversibile! ::: -Per eliminare definitivamente: +Per distruggere un sistema: 1. Elimina prima il sistema in modo soft 2. Vai alla vista dei sistemi eliminati 3. Seleziona il sistema -4. Clicca su **Elimina definitivamente** +4. Clicca su **Distruggi** 5. Digita il nome del sistema per confermare -6. Clicca su **Elimina** +6. Clicca su **Distruggi** **Viene rimosso:** - Il record del sistema diff --git a/frontend/e2e/fixtures/users.ts b/frontend/e2e/fixtures/users.ts index 911d77745..362de1bd4 100644 --- a/frontend/e2e/fixtures/users.ts +++ b/frontend/e2e/fixtures/users.ts @@ -83,12 +83,12 @@ export async function roleIdByName(name: string): Promise { * load-bearing for teardown: `/users` adds `AND u.deleted_at IS NULL` unless * `status=deleted` is among the query parameters * (`entities/local_users.go`, `deletedClause`). A default listing therefore - * cannot see an archived user, so the sweep would walk straight past one and - * leave it in the tenant for ever — which is exactly what the archive spec + * cannot see an deleted user, so the sweep would walk straight past one and + * leave it in the tenant for ever — which is exactly what the delete spec * creates. * * Pass a narrower list to ask a question instead of to clean up, e.g. - * `listE2eUsers(['deleted'])` for "did the archive really happen". + * `listE2eUsers(['deleted'])` for "did the deletion really happen". */ export async function listE2eUsers( statuses: string[] = ['enabled', 'suspended', 'deleted'], diff --git a/frontend/e2e/fullstack/controls.spec.ts b/frontend/e2e/fullstack/controls.spec.ts index e17ed0a73..30a9fd87b 100644 --- a/frontend/e2e/fullstack/controls.spec.ts +++ b/frontend/e2e/fullstack/controls.spec.ts @@ -24,8 +24,8 @@ * Read-only: the controls are located, never clicked, so nothing is created and * there is nothing to tear down. Two gates are deliberately left out and * tracked as later work, both because they need a fixture this spec would have - * to build: impersonation (`impersonate:users`, which also depends on the - * target's consent) and the add-on catalog, including the compound + * to build: impersonation (`impersonate:users`, which needs an active target + * user) and the add-on catalog, including the compound * `canBuyAddons` — `manage:entitlements` AND NOT owner-level, the one gate in * the codebase where holding more authority has to hide a control. */ diff --git a/frontend/e2e/fullstack/users.spec.ts b/frontend/e2e/fullstack/users.spec.ts index 579e03e20..fccea5214 100644 --- a/frontend/e2e/fullstack/users.spec.ts +++ b/frontend/e2e/fullstack/users.spec.ts @@ -2,13 +2,13 @@ // SPDX-License-Identifier: GPL-3.0-or-later /** - * Creating, editing and archiving a user, and assigning technical roles. + * Creating, editing and deleting a user, and assigning technical roles. * * The lifecycle runs as one serial sequence rather than as independent tests, * for a reason that is not tidiness: creating a user makes the backend send a * welcome email with a temporary password * (`services/local/users.go:351`). Sharing one user across create, edit and - * archive keeps that to a single message per run instead of one per test. + * delete keeps that to a single message per run instead of one per test. * * Everything created is plus sub-addressed with the reserved tag and destroyed * afterwards; teardown refuses any address without it. See @@ -104,7 +104,7 @@ async function filterTo(page: Page, email: string): Promise { test.describe('user lifecycle', () => { // Serial for the reason in the file docstring: one account covers create, - // edit and archive, so each step depends on the one before. Scoped to this + // edit and delete, so each step depends on the one before. Scoped to this // describe rather than the file, so a failure here does not skip the // independent validation test below. // @@ -163,44 +163,44 @@ test.describe('user lifecycle', () => { ]) }) - test('archives the user', async ({ page }) => { + test('deletes the user', async ({ page }) => { await openUsers(page) const row = await filterTo(page, email) await row.getByRole('button', { name: /menu/i }).click() - await page.getByRole('menuitem', { name: t('common.archive') }).click() + await page.getByRole('menuitem', { name: t('common.delete') }).click() // The confirmation is type-to-confirm, and that is load-bearing: // `DeleteObjectModal.vue` only emits primary-click when the typed text - // matches the name exactly, so clicking Archive without it shows a - // validation error and archives nothing. + // matches the name exactly, so clicking Delete without it shows a + // validation error and deletes nothing. // // Asserted on the heading rather than on the dialog itself: the element // carrying role="dialog" is a zero-size wrapper around fixed-position // children, which Playwright reports as hidden however open the modal is. const confirm = page.getByRole('dialog') - const title = confirm.getByRole('heading', { name: t('users.archive_user') }) + const title = confirm.getByRole('heading', { name: t('users.delete_user') }) await expect(title).toBeVisible() await confirm.getByRole('textbox').fill(name) - await confirm.getByRole('button', { name: t('common.archive') }).click() + await confirm.getByRole('button', { name: t('common.delete') }).click() // Wait for the modal to go before looking at the table, and not only for // tidiness: while it is open the rest of the page is aria-hidden, so // `getByRole('row')` matches nothing and the assertion below would pass - // against an archive that never happened. + // against a deletion that never happened. await expect(title).toBeHidden({ timeout: 30_000 }) - // Archived users drop out of the listing, which asks for enabled and + // Deleted users drop out of the listing, which asks for enabled and // suspended only. await expect(rowOf(page, email)).toHaveCount(0, { timeout: 30_000 }) - // The row leaving the page is not the same as the account being archived. - // Ask the backend for the archived ones and it is there. - const archived = await listE2eUsers(['deleted']) + // The row leaving the page is not the same as the account being deleted. + // Ask the backend for the deleted ones and it is there. + const deleted = await listE2eUsers(['deleted']) expect( - archived.map((u) => u.email), - `${email} should be listed once the archived are asked for`, + deleted.map((u) => u.email), + `${email} should be listed once the deleted are asked for`, ).toContain(email) }) }) diff --git a/frontend/src/assets/main.css b/frontend/src/assets/main.css index d4f47bbd3..bd1957848 100644 --- a/frontend/src/assets/main.css +++ b/frontend/src/assets/main.css @@ -51,11 +51,21 @@ --duration-small: 200ms; --duration-large-enter: 300ms; --duration-large-leave: 200ms; + /* how long a reload runs before its indicator shows: a quicker one ends + before anyone needs to be told, and a flashing bar distracts more than it + informs */ + --duration-loading-delay: 500ms; /* animations */ --animate-spin-relaxed: spin 1.5s linear infinite; --animate-fade-in: fade-in 0.3s ease-in; --animate-fade-in-relaxed: fade-in 0.6s ease-in; + /* one-shot feedback when a system is starred, so it follows the duration scale */ + --animate-favorite-pop: favorite-pop var(--duration-large-enter) ease-out; + /* a loading indicator that stays transparent while the load is quick, then + fades in; removed before the delay ends, it never shows */ + --animate-delayed-fade-in: fade-in var(--duration-small) ease-in var(--duration-loading-delay) + both; @keyframes fade-in { from { @@ -65,6 +75,21 @@ opacity: 1; } } + + @keyframes favorite-pop { + 0% { + transform: scale(1) rotate(0deg); + } + 40% { + transform: scale(1.35) rotate(-12deg); + } + 70% { + transform: scale(0.95) rotate(4deg); + } + 100% { + transform: scale(1) rotate(0deg); + } + } } /* inline, so the utility carries the value itself and each element resolves its own delay: a diff --git a/frontend/src/components/account/apiKeys/ApiKeysPanel.vue b/frontend/src/components/account/apiKeys/ApiKeysPanel.vue index b68c4ef5e..e4dd24586 100644 --- a/frontend/src/components/account/apiKeys/ApiKeysPanel.vue +++ b/frontend/src/components/account/apiKeys/ApiKeysPanel.vue @@ -4,6 +4,7 @@ --> - - diff --git a/frontend/src/components/account/impersonation/ImpersonationPanel.vue b/frontend/src/components/account/impersonation/ImpersonationPanel.vue index be5670984..899ca182d 100644 --- a/frontend/src/components/account/impersonation/ImpersonationPanel.vue +++ b/frontend/src/components/account/impersonation/ImpersonationPanel.vue @@ -5,178 +5,18 @@ diff --git a/frontend/src/components/account/impersonation/SessionModal.vue b/frontend/src/components/account/impersonation/SessionModal.vue index 239302ef4..5560f18a2 100644 --- a/frontend/src/components/account/impersonation/SessionModal.vue +++ b/frontend/src/components/account/impersonation/SessionModal.vue @@ -4,6 +4,7 @@ --> + + diff --git a/frontend/src/components/common/UpdatingSpinner.test.ts b/frontend/src/components/common/UpdatingSpinner.test.ts new file mode 100644 index 000000000..230f22745 --- /dev/null +++ b/frontend/src/components/common/UpdatingSpinner.test.ts @@ -0,0 +1,100 @@ +// Copyright (C) 2026 Nethesis S.r.l. +// SPDX-License-Identifier: GPL-3.0-or-later + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mount } from '@vue/test-utils' +import { createI18n } from 'vue-i18n' +import UpdatingSpinner from './UpdatingSpinner.vue' + +const i18n = createI18n({ legacy: false, locale: 'en', missingWarn: false, fallbackWarn: false }) + +const mountSpinner = (updating = false) => + mount(UpdatingSpinner, { props: { updating }, global: { plugins: [i18n] } }) + +const isShown = (wrapper: ReturnType) => + wrapper.text().includes('common.updating') + +beforeEach(() => { + vi.useFakeTimers() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('UpdatingSpinner', () => { + it('shows nothing for a refresh quicker than the delay', async () => { + const wrapper = mountSpinner() + + await wrapper.setProps({ updating: true }) + await vi.advanceTimersByTimeAsync(400) + await wrapper.setProps({ updating: false }) + await vi.advanceTimersByTimeAsync(1000) + + expect(isShown(wrapper)).toBe(false) + }) + + it('shows after the delay while the refresh goes on', async () => { + const wrapper = mountSpinner() + + await wrapper.setProps({ updating: true }) + await vi.advanceTimersByTimeAsync(499) + expect(isShown(wrapper)).toBe(false) + await vi.advanceTimersByTimeAsync(1) + + expect(isShown(wrapper)).toBe(true) + }) + + it('stays at least as long as the delay once shown', async () => { + const wrapper = mountSpinner() + + await wrapper.setProps({ updating: true }) + await vi.advanceTimersByTimeAsync(600) + await wrapper.setProps({ updating: false }) + await vi.advanceTimersByTimeAsync(300) + expect(isShown(wrapper)).toBe(true) + await vi.advanceTimersByTimeAsync(100) + + expect(isShown(wrapper)).toBe(false) + }) + + it('hides at once after a long refresh', async () => { + const wrapper = mountSpinner() + + await wrapper.setProps({ updating: true }) + await vi.advanceTimersByTimeAsync(2000) + await wrapper.setProps({ updating: false }) + await vi.advanceTimersByTimeAsync(0) + + expect(isShown(wrapper)).toBe(false) + }) + + it('stays shown when a new refresh starts before it hides', async () => { + const wrapper = mountSpinner() + + await wrapper.setProps({ updating: true }) + await vi.advanceTimersByTimeAsync(600) + await wrapper.setProps({ updating: false }) + await vi.advanceTimersByTimeAsync(100) + await wrapper.setProps({ updating: true }) + await vi.advanceTimersByTimeAsync(1000) + + expect(isShown(wrapper)).toBe(true) + }) + + it('starts the delay when mounted during a refresh', async () => { + const wrapper = mountSpinner(true) + + await vi.advanceTimersByTimeAsync(500) + + expect(isShown(wrapper)).toBe(true) + }) + + it('leaves no timer running once unmounted', async () => { + const wrapper = mountSpinner(true) + + wrapper.unmount() + + expect(vi.getTimerCount()).toBe(0) + }) +}) diff --git a/frontend/src/components/common/UpdatingSpinner.vue b/frontend/src/components/common/UpdatingSpinner.vue index d378c0b53..190e87d49 100644 --- a/frontend/src/components/common/UpdatingSpinner.vue +++ b/frontend/src/components/common/UpdatingSpinner.vue @@ -1,14 +1,64 @@