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
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-01 09:31:55 +08:00
1 parent 7d29d89b3f
commit 998e04b844
12 files changed
+122 -10

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`
@@ -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;
}