Compare commits

..
Author SHA1 Message Date
ngqileandClaude Opus 5.5 b6b05f12df docs(openspec): archive fix-company-scope-fail-closed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 09:32:21 +08:00
ngqile a1aa906a66 Merge pull request 'fix: fail closed for admins outside the company model' (#27) from fix-company-scope-fail-closed into main
CI / build-and-publish (push) Failing after 0s
2026-12-01 01:32:09 +00:00
ngqileandClaude Opus 5.5 998e04b844 fix(mobile-api): fail closed for admins outside the company model
An admin with no company who is not a super admin now gets 403
COMPANY_REQUIRED on every company-scoped request instead of seeing all
companies. The module check and the email detail treat only a real super
admin (no company and role 1) as super; a company user still holding
role 1 gets only what their other roles grant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 09:31:55 +08:00
ngqile 7d29d89b3f Merge pull request 'docs(openspec): archive add-company-scoping' (#26) from archive-add-company-scoping into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 13:38:36 +00:00
ngqileandClaude Opus 5.5 3c30e0d629 docs(openspec): archive add-company-scoping
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 21:38:27 +08:00
ngqile 66904869cf Merge pull request 'feat: company scoping (INS and CV, super admins see all)' (#25) from add-company-scoping into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 13:38:08 +00:00
32 changed files with 352 additions and 51 deletions

No files matched your search

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-01
@@ -0,0 +1,23 @@
## Why
The whole-branch review of add-company-scoping (PR #25) found that the code trusts the "every non-super admin belongs to a company" rule instead of enforcing it. An admin user with no company who is not a super admin (left over from before companies, or created by a direct DB edit) is scoped to all companies. A company user who still holds role 1 skips every module check and is treated as a super admin when reading super admins' emails.
## What Changes
- Company scope fails closed: an admin with no company who is not a super admin gets 403 `COMPANY_REQUIRED` on every company-scoped admin endpoint instead of seeing all companies.
- The admin module check grants all modules only to a super admin (no company and role 1), not to any holder of role 1.
- The email detail hides super admins' emails from every caller who is not a super admin, using the same super-admin test.
## Capabilities
### New Capabilities
### Modified Capabilities
- `company-scoping`: adds the "Invalid admins fail closed" requirement for the two invalid states.
## Impact
- `solvway-mobile-api`: `AdminCompanyScope`, `AppAccessAspect`, `AdminEmailService`.
- No API shape, schema or portal change. Valid users (super admins, and staff with a company) see no difference.
- Deferred: the capture event list still loads only the first 100 enabled events (marked `ponytail:` in `AdminEventLeadService`).
@@ -0,0 +1,18 @@
## ADDED Requirements
### Requirement: Invalid admins fail closed
The system SHALL refuse every company-scoped request from an admin with no company who is not a super admin, and SHALL grant a company user who holds the super admin role only the modules and records their company and other roles allow.
#### Scenario: Admin without a company who is not a super admin
- **GIVEN** an admin user with no company and no super admin role
- **WHEN** they open Leads, Events, Users or any other company-scoped list or record
- **THEN** the request is refused with 403
- **AND** no company's records are returned
#### Scenario: Company user still holding the super admin role
- **GIVEN** a user of INS who holds the super admin role and a role granting only Leads
- **WHEN** they open Users or another super admin's email
- **THEN** the request is refused with 403
@@ -0,0 +1,10 @@
## 1. Fail closed
- [x] 1.1 `AdminCompanyScope.scope` and `requireCompanyForCreate` refuse (403 `COMPANY_REQUIRED`) an admin with no company who is not a super admin
- Depends on: none
- Scope: `solvway-mobile-api/src/**/useraccess/AdminCompanyScope*.java`
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
- [x] 1.2 `AppAccessAspect` skips the module check only for `AdminCompanyScope.isSuper`; `AdminEmailService` uses the same test
- Depends on: 1.1
- Scope: `solvway-mobile-api/src/**/useraccess/AppAccessAspect*.java`, `solvway-mobile-api/src/**/service/AdminEmailService*.java`
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
+14 -8
View File
@@ -8,20 +8,26 @@ Staff log in to the Co-Lite admin portal, and every admin page and `/api/admin/*
### Requirement: Staff login
The system SHALL let an active admin user log in with username and password through the admin portal, and SHALL return the user's name, roles, menu and whether a password change is required.
The system SHALL let an active admin user log in through the admin portal with company code, username and password, or with username and password and no company for a super admin, and SHALL return the user's name, roles, company, menu and whether a password change is required.
#### Scenario: Correct credentials
- **GIVEN** an active admin user `admin` with password `colite-dev-admin`
- **WHEN** they submit those credentials on the login page
- **GIVEN** an active admin user `sales1` of active company `ins`
- **WHEN** they submit company `ins`, username `sales1` and their password on the login page
- **THEN** they are signed in and land on the portal home
- **AND** the sidebar shows only the menu entries their roles grant
#### Scenario: Super admin
- **GIVEN** the super admin `admin`, who belongs to no company
- **WHEN** they submit username `admin` and their password with the company left empty
- **THEN** they are signed in
#### Scenario: Wrong password
- **WHEN** a user submits a wrong password
- **THEN** `/api/admin/auth/login` responds 401
- **AND** the login page shows an invalid-credentials message without saying whether the username exists
- **AND** the login page shows an invalid-credentials message without saying whether the company or username exists
#### Scenario: Deactivated user
@@ -53,19 +59,19 @@ The system SHALL require a user whose password is temporary (new user or reset)
### Requirement: Forgot password
The system SHALL let a user request a temporary password by entering their username and email on a public forgot-password page. The response SHALL be the same whether or not the username and email match an active admin user.
The system SHALL let a user request a temporary password by entering their company code, username and email on a public forgot-password page; a super admin leaves the company empty. The response SHALL be the same whether or not the details match an active admin user.
#### Scenario: Matching username and email
- **GIVEN** an active admin user with username `sales1` and email `sales1@example.com`
- **WHEN** someone submits `sales1` and `sales1@example.com`
- **GIVEN** an active admin user `sales1` of company `ins` with email `sales1@example.com`
- **WHEN** someone submits company `ins`, username `sales1` and `sales1@example.com`
- **THEN** a temporary password is emailed to `sales1@example.com`
- **AND** the user must change it at next login
- **AND** the page shows "If the details match an account, we have emailed a temporary password."
#### Scenario: Non-matching details
- **WHEN** someone submits a username and email that do not match an active admin user
- **WHEN** someone submits a company, username and email that do not match an active admin user
- **THEN** no password changes and no email is sent
- **AND** the page shows the same message as for a match
+19 -8
View File
@@ -89,16 +89,22 @@ The system SHALL refuse sign-in for a locked username before checking the passwo
### Requirement: Unlock
The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked.
The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames of their own company that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one of them. A super admin SHALL see and unlock locked usernames of every company, including attempts that match no company. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked.
#### Scenario: Unlock a locked username
- **GIVEN** `sales1` is locked
- **WHEN** an admin with `BO_LOGIN_SECURITY` unlocks `sales1`
- **GIVEN** INS user `sales1` is locked
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` unlocks `sales1`
- **THEN** `sales1` no longer appears in the locked list
- **AND** `sales1` can sign in with the right password
- **AND** an `UNLOCK_RESET` record for `sales1` names the admin
#### Scenario: Another company's locked user
- **GIVEN** CV user `sales2` is locked
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` lists locked users or unlocks `sales2` of CV
- **THEN** `sales2` is not listed and the unlock answers 404
### Requirement: Login history screen
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the login history, newest first and paged, filtered by username, event and date range.
@@ -115,19 +121,24 @@ The system SHALL let an admin with `BO_LOGIN_SECURITY` read the login history, n
### Requirement: Lockout and password-rule settings
The system SHALL let an admin with `BO_LOGIN_SECURITY` read and change the lockout settings (on/off, maximum attempts, period, time unit) and the admin password rules (each rule's on/off status and value). The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the lockout settings and the admin password rules, and SHALL let only a super admin change them, because they apply to every company. The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
#### Scenario: Change the lockout settings
- **WHEN** an admin sets the maximum to 3 and the period to 30 minutes
- **THEN** the next lock decision uses 3 attempts in 30 minutes
- **WHEN** a super admin sets the maximum to 3 and the period to 30 minutes
- **THEN** the next lock decision in every company uses 3 attempts in 30 minutes
#### Scenario: Invalid setting
- **WHEN** an admin sets the maximum to 0
- **WHEN** a super admin sets the maximum to 0
- **THEN** the change is refused with a validation error and the settings stay as they were
#### Scenario: Change a password rule
- **WHEN** an admin sets the minimum length rule to 10
- **WHEN** a super admin sets the minimum length rule to 10
- **THEN** a new password of 9 characters is refused by every admin password check
#### Scenario: Company user changes settings
- **WHEN** an INS user with `BO_LOGIN_SECURITY` changes a lockout setting or a password rule
- **THEN** the change is refused with 403 and the settings stay as they were
+15 -10
View File
@@ -8,35 +8,40 @@ Admins with the Roles module define roles and choose which back-office modules e
### Requirement: Role list and edit
The system SHALL let an admin with `BO_ROLES` list, create and rename admin roles. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules).
The system SHALL let any admin with `BO_ROLES` list admin roles, and SHALL let only a super admin create and rename them, because roles are shared by every company. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules).
#### Scenario: Create role
- **WHEN** an admin with `BO_ROLES` creates role `ROLE_SALES`
- **THEN** it appears in the role list and can be assigned to users
- **WHEN** a super admin creates role `ROLE_SALES`
- **THEN** it appears in the role list and can be assigned to users of any company
#### Scenario: Duplicate name
- **GIVEN** role `ROLE_SALES` exists
- **WHEN** an admin creates another role named `ROLE_SALES`
- **WHEN** a super admin creates another role named `ROLE_SALES`
- **THEN** the save is refused with a message
#### Scenario: Company user edits a role
- **WHEN** an INS user with `BO_ROLES` creates or renames a role
- **THEN** the request is refused with 403 and nothing changes
### Requirement: Role permissions
The system SHALL let an admin with `BO_ROLES` choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. An admin who is not super admin SHALL NOT change the grants of a role they hold.
The system SHALL let only a super admin choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. Admins with `BO_ROLES` who are not super admins SHALL see the grants read-only.
#### Scenario: Grant Users module
- **GIVEN** role `ROLE_SALES` without `BO_USERS`
- **WHEN** an admin grants `BO_USERS` to `ROLE_SALES` and saves
- **THEN** users with `ROLE_SALES` see Users in the sidebar after their next login or session refresh
- **WHEN** a super admin grants `BO_USERS` to `ROLE_SALES` and saves
- **THEN** users with `ROLE_SALES` in every company see Users in the sidebar after their next login or session refresh
- **AND** `GET /api/admin/users` responds 200 for them
#### Scenario: Own role
- **GIVEN** an admin who is not super admin and holds `ROLE_SALES`
- **WHEN** they change the module grants of `ROLE_SALES` and save
- **THEN** the save is refused with a message, so no admin can widen their own access or lock themselves out of role management
- **GIVEN** an INS user who is not super admin and holds `ROLE_SALES` and `BO_ROLES`
- **WHEN** they change the module grants of `ROLE_SALES`, or of any other role
- **THEN** the save is refused with 403 and the grants stay as they were
### Requirement: Back-office module set
+20 -10
View File
@@ -18,22 +18,27 @@ The system SHALL list admin users only (never members), paginated on the server,
### Requirement: Create user
The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email, one or more roles, and an initial password with its confirmation. Username and email SHALL be unique. The password SHALL match its confirmation and pass the admin password rules. The new user SHALL be saved with a pending password change, SHALL belong to the creating admin's company, and SHALL NOT be sent an email.
The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email, one or more roles, and an initial password with its confirmation. Username and email SHALL be unique within the user's company, so the same username or email may exist in another company. A username SHALL NOT contain `@`. The password SHALL match its confirmation and pass the admin password rules. The new user SHALL be saved with a pending password change and SHALL NOT be sent an email.
#### Scenario: New user
- **WHEN** an admin creates user `sales1` with email `sales1@example.com`, role Sales and a valid initial password
- **THEN** the user is saved as active with a pending password change
- **AND** `sales1` can sign in with that password and must choose a new password before anything else
- **WHEN** an INS admin creates user `sales1` with email `sales1@example.com`, role Sales and a valid initial password
- **THEN** the user is saved as active in INS with a pending password change
- **AND** `sales1` can sign in with company `ins` and that password and must choose a new password before anything else
- **AND** no email is sent
- **AND** the user's company is the creating admin's company
#### Scenario: Duplicate username
- **GIVEN** a user `sales1` exists
- **WHEN** an admin creates another user with username `sales1`
- **GIVEN** a user `sales1` exists in INS
- **WHEN** an admin creates another INS user with username `sales1`
- **THEN** the save is refused and the form shows that the username is taken
#### Scenario: Same username in another company
- **GIVEN** a user `sales1` exists in INS
- **WHEN** a CV admin creates user `sales1` in CV
- **THEN** the user is created
#### Scenario: Weak or mismatched initial password
- **WHEN** an admin creates a user with a password that fails the admin password rules, or that does not match its confirmation
@@ -97,12 +102,17 @@ The system SHALL let an admin with `BO_USERS` give an active admin user a new pa
### Requirement: Company membership
Every admin user SHALL belong to exactly one company. The company SHALL be set by the system from the creating admin, never from the request.
Every admin user other than a super admin SHALL belong to exactly one company. A company user's new user SHALL belong to the creating user's company, whatever the request says. A super admin SHALL choose the company of a new user, or no company to create another super admin.
#### Scenario: Company in the request is ignored
- **WHEN** a create-user request carries a company id different from the admin's own
- **THEN** the new user gets the admin's company
- **WHEN** an INS user's create-user request carries the CV company id
- **THEN** the new user belongs to INS
#### Scenario: Super admin chooses the company
- **WHEN** a super admin creates a user and chooses CV
- **THEN** the new user belongs to CV
### Requirement: Temporary password refusals
+151
View File
@@ -0,0 +1,151 @@
# company-scoping Specification
## Purpose
Separate the data of each company using Co-Lite (INS and CV at go-live): staff sign in with their company code and see only their own company's records, while company-less super admins manage companies and see every company.
## Requirements
### Requirement: Companies
The system SHALL let a super admin list, create and edit companies, each with a name, a unique code and an active or inactive status. A code SHALL be 2 to 20 characters of lowercase letters, digits and hyphens, compared ignoring case. Companies SHALL NOT be deletable. The Companies screen and its endpoints SHALL be available to super admins only.
#### Scenario: Create a company
- **WHEN** a super admin creates company `CV` with code `cv`
- **THEN** it is listed as active
- **AND** staff can be created in it
#### Scenario: Duplicate code
- **GIVEN** a company with code `ins`
- **WHEN** a super admin creates or renames another company to code `INS`
- **THEN** the save is refused and the code is reported as taken
#### Scenario: Not a super admin
- **WHEN** company staff open the Companies page or call a companies endpoint
- **THEN** the page shows not-authorised and the endpoint responds 403
### Requirement: Company sign-in
The system SHALL sign company staff in with company code, username and password, and SHALL sign super admins in with username and password and no company. The answer SHALL be the same for a wrong or unknown company, an inactive company, an unknown user and a wrong password. A user's sessions SHALL end when their company is deactivated or its code is changed.
#### Scenario: Staff sign-in
- **GIVEN** an active user `john` in active company `ins`
- **WHEN** they sign in with company `ins`, username `john` and the right password
- **THEN** they are signed in as `john` of INS
#### Scenario: Same username in two companies
- **GIVEN** a user `john` in INS and a different user `john` in CV
- **WHEN** someone signs in with company `cv`, username `john` and CV John's password
- **THEN** they are signed in as CV's John and see only CV data
#### Scenario: Wrong company
- **WHEN** INS's `john` signs in with company `cv` or a code that does not exist
- **THEN** login is refused with the same invalid-credentials answer as a wrong password
#### Scenario: Inactive company
- **GIVEN** company CV is deactivated
- **WHEN** a CV user signs in with the right password, or uses an existing session
- **THEN** the sign-in is refused with the invalid-credentials answer and the session ends
#### Scenario: Code changed
- **GIVEN** a signed-in user of the company with code `ins`
- **WHEN** a super admin changes that code to `ins-my`
- **THEN** the user's session ends
- **AND** they sign in again with company `ins-my`
### Requirement: Super admins
A super admin SHALL be an admin user who belongs to no company and holds the super admin role. Only a super admin SHALL create another super admin. The super admin role SHALL NOT be granted to a user who belongs to a company, and every admin user who is not a super admin SHALL belong to a company.
#### Scenario: Create a second super admin
- **WHEN** a super admin creates a user with no company
- **THEN** the user is created as a super admin and signs in without a company
#### Scenario: Super admin role for company staff
- **WHEN** anyone assigns the super admin role to a user of INS
- **THEN** the save is refused with a message
### Requirement: Company data is separated
The system SHALL limit every admin list, search, export, detail, create, edit and action to the caller's company for: users, events, event teams, event leads, leads, emails, login history, locked users and audit events. A record of another company SHALL answer 404, as if it did not exist.
#### Scenario: Lists show own company only
- **GIVEN** leads, events and users in INS and in CV
- **WHEN** an INS user with the matching modules opens Leads, Events or Users
- **THEN** only INS records are listed
- **AND** an export contains only INS leads
#### Scenario: Another company's record by id
- **GIVEN** a CV lead, event, user or email
- **WHEN** an INS user requests it, edits it or acts on it by its id
- **THEN** the answer is 404 and nothing changes
#### Scenario: Same phone in two companies
- **GIVEN** INS has a lead with mobile `+60123456789`
- **WHEN** a CV user captures a lead with the same mobile at a CV event
- **THEN** a new CV lead is created and flagged New
- **AND** the INS lead is unchanged
### Requirement: Super admin sees all companies
The system SHALL show super admins every company's records by default, SHALL let them narrow any scoped list to one company, and SHALL show each record's company in mixed lists. Creating a company-owned record (user, event, event lead) SHALL require a super admin to choose the company.
#### Scenario: Mixed list
- **WHEN** a super admin opens Leads with all companies selected
- **THEN** INS and CV leads are listed together with a Company column
#### Scenario: Pick a company
- **WHEN** a super admin picks CV in the company picker
- **THEN** scoped lists show CV records only
#### Scenario: Create without a company
- **WHEN** a super admin creates an event without choosing a company
- **THEN** the save is refused and the form asks for a company
### Requirement: Company of login and audit records
An audit event and a login-history record SHALL belong to the company of the user who acted, or of the user who tried to sign in when the given company and username match a user. Records with no company SHALL be visible to super admins only.
#### Scenario: Super admin edits a company record
- **WHEN** a super admin edits an INS lead
- **THEN** the audit event has no company
- **AND** INS staff with Audit log do not see it, and super admins do
#### Scenario: Failed sign-in with an unknown company
- **WHEN** someone fails to sign in with a company code that does not exist
- **THEN** the login-history record has no company and only super admins see it
### Requirement: Invalid admins fail closed
The system SHALL refuse every company-scoped request from an admin with no company who is not a super admin, and SHALL grant a company user who holds the super admin role only the modules and records their company and other roles allow.
#### Scenario: Admin without a company who is not a super admin
- **GIVEN** an admin user with no company and no super admin role
- **WHEN** they open Leads, Events, Users or any other company-scoped list or record
- **THEN** the request is refused with 403
- **AND** no company's records are returned
#### Scenario: Company user still holding the super admin role
- **GIVEN** a user of INS who holds the super admin role and a role granting only Leads
- **WHEN** they open Users or another super admin's email
- **THEN** the request is refused with 403
+11 -5
View File
@@ -8,25 +8,31 @@ Admins with the Interests module maintain the list of products and services that
### Requirement: Interest list
The system SHALL let an admin with `BO_INTERESTS` list, add, rename, reorder, deactivate and reactivate interests for their company. An interest name SHALL be required, at most 100 characters, and unique within the company ignoring case. Interests SHALL NOT be deletable.
The system SHALL keep one interest list shared by all companies. Admins with `BO_INTERESTS` SHALL see the list, and only a super admin SHALL add, rename, reorder, deactivate and reactivate interests. An interest name SHALL be required, at most 100 characters, and unique ignoring case. Interests SHALL NOT be deletable.
#### Scenario: Add interest
- **WHEN** an admin with `BO_INTERESTS` adds `Kitchen appliances`
- **WHEN** a super admin adds `Kitchen appliances`
- **THEN** it is listed as active
- **AND** staff of every company can tag leads with it
#### Scenario: Duplicate name
- **GIVEN** an interest `Kitchen appliances`
- **WHEN** an admin adds `kitchen APPLIANCES`
- **WHEN** a super admin adds `kitchen APPLIANCES`
- **THEN** the save is refused and the name is reported as a duplicate
#### Scenario: Deactivate
- **GIVEN** an active interest `Cookware`
- **WHEN** an admin deactivates it
- **WHEN** a super admin deactivates it
- **THEN** it is still listed, marked inactive
- **AND** it is no longer offered when capturing a lead
- **AND** it is no longer offered when capturing a lead in any company
#### Scenario: Company user edits
- **WHEN** an INS user with `BO_INTERESTS` adds, renames or deactivates an interest
- **THEN** the request is refused with 403 and the list is unchanged
#### Scenario: No module
@@ -87,7 +87,7 @@ public class AdminEmailService {
}
}
}
if (!isSuper(caller) && recipients.stream().anyMatch(r -> isSuperAdminAddress((String) r.get("recipient")))) {
if (!AdminCompanyScope.isSuper(caller) && recipients.stream().anyMatch(r -> isSuperAdminAddress((String) r.get("recipient")))) {
throw new CodedResponseStatusException(HttpStatus.FORBIDDEN, "Only a super admin can read this email", "SUPER_ADMIN_REQUIRED");
}
Map<String, Object> out = new LinkedHashMap<>();
@@ -125,10 +125,6 @@ public class AdminEmailService {
&& roles.stream().anyMatch(r -> Long.valueOf(SUPER_ADMIN_ROLE_ID).equals(AdminRoleService.idOf(r)));
}
private static boolean isSuper(User caller) {
return caller.getRoles() != null && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID);
}
private static String upstreamDate(String isoDate) {
try {
return LocalDate.parse(isoDate.trim()).format(UPSTREAM_DATE);
@@ -16,9 +16,12 @@ public class AdminCompanyScope {
&& caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID);
}
/** Staff: their own company, whatever was requested. Super: the requested company, null = all companies. */
/** Staff: their own company, whatever was requested. Super: the requested company, null = all companies.
* An admin with no company who is not a super admin breaks the model and sees nothing (403). */
public Long scope(User caller, Long requestedCompanyId) {
return isSuper(caller) ? requestedCompanyId : caller.getCompanyId();
if (isSuper(caller)) return requestedCompanyId;
if (caller.getCompanyId() == null) throw coded(HttpStatus.FORBIDDEN, "No company assigned", "COMPANY_REQUIRED");
return caller.getCompanyId();
}
/** Writes need a concrete company: staff get their own, a super admin must choose one. */
@@ -351,7 +351,6 @@ public class AppAccessAspect {
return jwt;
}
private static final long SUPER_ADMIN_ROLE_ID = 1L;
private static final long INJECTED_ROLE_ADMIN_ID = 2L;
/** Admin paths: admin token, live and enabled session, and a granted BO module. Fails closed. */
@@ -376,7 +375,7 @@ public class AppAccessAspect {
// services-auth findUserByToken adds ROLE_ADMIN to every admin, so it never grants a module.
.filter(id -> id != INJECTED_ROLE_ADMIN_ID)
.collect(Collectors.toSet());
if (roleIds.contains(SUPER_ADMIN_ROLE_ID)) {
if (AdminCompanyScope.isSuper(admin)) {
return;
}
boolean granted = false;
@@ -46,7 +46,7 @@ class AdminAuditLogServiceTest {
service = new AdminAuditLogService(rest, auth, new AdminCompanyScope());
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
when(auth.loadUserByToken("tok")).thenReturn(new User());
when(auth.loadUserByToken("tok")).thenReturn(superAdmin()); // all companies: these tests are about filter forwarding
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
}
@@ -102,4 +102,12 @@ class AdminAuditLogServiceTest {
assertThat(e.getReason()).isEqualTo("Audit event not found");
});
}
private static User superAdmin() {
User u = new User();
com.solvway.core.model.Role r = new com.solvway.core.model.Role();
r.setId(1L);
u.setRoles(java.util.List.of(r));
return u;
}
}
@@ -67,12 +67,14 @@ class AdminEmailServiceTest {
Role r = new Role();
r.setId(roleId);
caller.setRoles(List.of(r));
if (roleId != 1L) caller.setCompanyId(5L); // staff always belong to a company; only a super admin has none
when(auth.loadUserByToken("tok")).thenReturn(caller);
}
private static Map<String, Object> emailRow(long id, String to) {
Map<String, Object> m = new HashMap<>();
m.put("id", id);
m.put("companyId", 5L); // the staff caller's company
m.put("sender", "noreply@example.com");
m.put("subject", "Reset Admin Password");
m.put("body", BODY);
@@ -100,6 +102,7 @@ class AdminEmailServiceTest {
@Test
void list_sendsOnlyGivenFiltersNewestFirstAndConvertsDates() {
callerWithRole(1L); // a super admin with no company picked: no company filter
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(), "totalElements", 0)));
@@ -161,6 +164,23 @@ class AdminEmailServiceTest {
});
}
@Test
void detail_companyCallerHoldingRole1_isNotSuper() {
when(auth.loadUserByToken("tok")).thenAnswer(i -> {
User u = new User();
u.setId(1L);
Role r = new Role();
r.setId(1L);
u.setRoles(List.of(r));
u.setCompanyId(5L);
return u;
});
stubFind(7, emailRow(7, "root@example.com"));
stubUserByEmail("root@example.com", adminUser(1));
assertThatThrownBy(() -> service.detail(7L)).isInstanceOfSatisfying(CodedResponseStatusException.class,
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN));
}
@Test
void detail_superAdminRoleSentAsBareId_isStillProtected() {
stubFind(7, emailRow(7, "root@example.com"));
@@ -66,4 +66,20 @@ class AdminCompanyScopeTest {
assertStatus(() -> scope.requireSuper(user(5L, 1)), HttpStatus.FORBIDDEN);
assertStatus(() -> scope.requireSuper(user(null, 4)), HttpStatus.FORBIDDEN);
}
@Test
void companyLessNonSuper_isRefusedEverywhere() {
User orphan = user(null, 4);
for (Runnable call : List.<Runnable>of(
() -> scope.scope(orphan, null),
() -> scope.scope(orphan, 9L),
() -> scope.requireCompanyForCreate(orphan, 9L))) {
assertThatThrownBy(call::run).isInstanceOf(ResponseStatusException.class)
.satisfies(ex -> {
ResponseStatusException e = (ResponseStatusException) ex;
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(e.getBody().getProperties()).containsEntry("code", "COMPANY_REQUIRED");
});
}
}
}
@@ -278,6 +278,18 @@ class AppAccessAspectAdminTest {
}
}
@Test
void companyUserHoldingRole1_getsOnlyTheirOtherRolesModules() throws Throwable {
target(Target.class, "methodWins");
User staff = admin(1L, 5L); // role 5 holds BO_LEADS, not BO_USERS
staff.setCompanyId(5L);
when(guard.check(TOK, false)).thenReturn(staff);
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
http(h, TOK, "A");
expect(HttpStatus.FORBIDDEN);
}
}
@Test
void undeclaredHandler_isForbiddenForNonSuperAdmin() throws Throwable {
target(Undeclared.class, "handler");
@@ -140,6 +140,11 @@ class AppAccessAspectAuditTest {
u.getRoles().add(r);
}
when(guard.check(eq(TOK), any(Boolean.class))).thenReturn(u);
// A company user is never a super admin, so role 1 here is an ordinary role granted both test modules.
when(rest.getForEntity(any(), any(org.springframework.core.ParameterizedTypeReference.class), eq("BO")))
.thenReturn(org.springframework.http.ResponseEntity.ok(List.of(
Map.of("name", "BO_USERS", "roles", List.of(Map.of("id", 1))),
Map.of("name", "BO_ROLES", "roles", List.of(Map.of("id", 1))))));
return u;
}