Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"phpcs": "./vendor/bin/phpcs --standard=phpcs.xml",
"phpcs:fix": "./vendor/bin/phpcbf --standard=phpcs.xml",
"phpcs:output": "./vendor/bin/phpcs --standard=phpcs.xml --report=json lib/ 2>/dev/null | tail -1 > phpcs-output.json",
"phpmd": "./vendor/bin/phpmd lib text phpmd.xml --exclude '*/Resources/template/*' --baseline-file phpmd.baseline.xml",
"phpmd": "E=0; ./vendor/bin/phpmd lib text phpmd.xml --exclude '*/Resources/template/*' --baseline-file phpmd.baseline.xml || E=$?; ./vendor/bin/phpmd lib text phpmd-unusedparams.xml --exclude '*/Resources/template/*' --baseline-file phpmd.baseline.xml || E=$?; exit $E",
"phpmetrics": "./vendor/bin/phpmetrics --report-html=phpmetrics lib/",
"psalm": "./vendor/bin/psalm --threads=1 --no-cache",
"phpstan": "./vendor/bin/phpstan analyse --memory-limit=1G",
Expand Down
42 changes: 31 additions & 11 deletions lib/Controller/AppOverrideController.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,17 +132,7 @@ public function get(string $appId): JSONResponse
$rawAdmin = ((string) $this->request->getParam('scope', '') === 'admin');

try {
if ($rawAdmin === true) {
$record = $this->appOverrideService->findByAppId(appId: $appId);
} else {
$user = $this->userSession->getUser();
$uid = null;
if ($user !== null) {
$uid = (string) $user->getUID();
}

$record = $this->appOverrideService->resolveLayeredDelta(appId: $appId, uid: $uid);
}
$record = $this->loadDelta(appId: $appId, rawAdmin: $rawAdmin);
} catch (Throwable $e) {
$this->logger->error(
'OpenBuild: AppOverride get failed for appId '.$appId.': '.$e->getMessage(),
Expand All @@ -166,6 +156,36 @@ public function get(string $appId): JSONResponse

}//end get()

/**
* Load the delta a `get()` call asked for.
*
* Extracted from {@see self::get()} so the raw-admin and layered paths read
* as an early return rather than an else branch. `?scope=admin` yields the
* RAW shared admin delta; the default yields the layered resolution
* (admin ⊕ the caller's own delta), which for an anonymous caller is
* exactly the admin delta.
*
* @param string $appId The fleet app id.
* @param bool $rawAdmin True for `?scope=admin`.
*
* @return array<string, mixed>|null The record, or null when no override exists.
*/
private function loadDelta(string $appId, bool $rawAdmin): ?array
{
if ($rawAdmin === true) {
return $this->appOverrideService->findByAppId(appId: $appId);
}

$user = $this->userSession->getUser();
$uid = null;
if ($user !== null) {
$uid = (string) $user->getUID();
}

return $this->appOverrideService->resolveLayeredDelta(appId: $appId, uid: $uid);

}//end loadDelta()

/**
* Return the calling user's OWN user-scoped delta for a fleet app (for editing).
*
Expand Down
16 changes: 8 additions & 8 deletions lib/Controller/ShopController.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,12 @@ class ShopController extends Controller
/**
* Constructor.
*
* @param IRequest $request The current HTTP request.
* @param LoggerInterface $logger PSR logger.
* @param IUserSession $userSession Current NC user session.
* @param GitHubCatalogService $catalogService Fixed-host GitHub source.
* @param AppRepoParser $repoParser Strict repo-file-map parser (change 1).
* @param ApplicationsController $applicationsController Shared clone/install seam.
* @param IRequest $request The current HTTP request.
* @param LoggerInterface $logger PSR logger.
* @param IUserSession $userSession Current NC user session.
* @param GitHubCatalogService $catalogService Fixed-host GitHub source.
* @param AppRepoParser $repoParser Strict repo-file-map parser (change 1).
* @param ApplicationsController $appsController Shared clone/install seam.
*
* @return void
*/
Expand All @@ -92,7 +92,7 @@ public function __construct(
private readonly IUserSession $userSession,
private readonly GitHubCatalogService $catalogService,
private readonly AppRepoParser $repoParser,
private readonly ApplicationsController $applicationsController,
private readonly ApplicationsController $appsController,
) {
parent::__construct(appName: Application::APP_ID, request: $request);
}//end __construct()
Expand Down Expand Up @@ -219,7 +219,7 @@ public function githubInstall(): JSONResponse
return new JSONResponse(data: $e->toArray(), statusCode: Http::STATUS_UNPROCESSABLE_ENTITY);
}

$result = $this->applicationsController->installFromTemplateArray(
$result = $this->appsController->installFromTemplateArray(
template: $template,
name: $name,
newSlug: $newSlug,
Expand Down
14 changes: 7 additions & 7 deletions lib/Controller/StoreController.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,11 @@ class StoreController extends Controller
/**
* Constructor.
*
* @param IRequest $request The current HTTP request.
* @param LoggerInterface $logger PSR logger.
* @param IUserSession $userSession Current NC user session.
* @param GenericStoreService $storeService Engine-owned store client.
* @param ApplicationsController $applicationsController Shared clone/install seam.
* @param IRequest $request The current HTTP request.
* @param LoggerInterface $logger PSR logger.
* @param IUserSession $userSession Current NC user session.
* @param GenericStoreService $storeService Engine-owned store client.
* @param ApplicationsController $appsController Shared clone/install seam.
*
* @return void
*/
Expand All @@ -103,7 +103,7 @@ public function __construct(
private readonly LoggerInterface $logger,
private readonly IUserSession $userSession,
private readonly GenericStoreService $storeService,
private readonly ApplicationsController $applicationsController,
private readonly ApplicationsController $appsController,
) {
parent::__construct(appName: Application::APP_ID, request: $request);
}//end __construct()
Expand Down Expand Up @@ -267,7 +267,7 @@ public function install(string $slug): JSONResponse
// Reuse the exact local clone path (companion namespacing, manifest
// rewrite, per-app register, owner-tagged persist). The seam returns a
// {status, data} result; this thin action owns the JSONResponse.
$result = $this->applicationsController->installFromTemplateArray(
$result = $this->appsController->installFromTemplateArray(
template: $template,
name: $name,
newSlug: $newSlug,
Expand Down
48 changes: 34 additions & 14 deletions lib/Mcp/Handler/AbstractToolHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -290,20 +290,7 @@ protected function requireAnyRoleOnApp(array $app): ?array
$permissions = [];
}

if ($this->permissionResolver !== null) {
$userGroups = $this->permissionResolver->resolveUserGroups($caller);
$hasRole = $this->permissionResolver->matchesCaller(
permissions: $permissions,
caller: $caller,
userGroups: $userGroups,
allowAdminBypass: true,
roles: ['owners', 'editors', 'viewers']
);
} else {
$hasRole = $this->callerHasWriteRole(app: $app, uid: $uid, allowAdminBypass: true);
}

if ($hasRole === true) {
if ($this->hasAnyRole(app: $app, permissions: $permissions, caller: $caller, uid: $uid) === true) {
return null;
}

Expand All @@ -314,6 +301,39 @@ protected function requireAnyRoleOnApp(array $app): ?array

}//end requireAnyRoleOnApp()

/**
* Whether the caller holds ANY role on the Application.
*
* Extracted from {@see self::requireAnyRoleOnApp()}: the resolver-backed
* and legacy paths both yield a bool, so an early return expresses the
* choice without an else branch. Deny-by-default is preserved — every path
* still returns an explicit bool from a real check.
*
* @param array<string, mixed> $app Application data array.
* @param array<string, mixed> $permissions The Application's permissions block.
* @param IUser $caller The authenticated caller.
* @param string $uid The caller's UID.
*
* @return bool True when the caller holds owner, editor or viewer.
*/
private function hasAnyRole(array $app, array $permissions, IUser $caller, string $uid): bool
{
if ($this->permissionResolver === null) {
return $this->callerHasWriteRole(app: $app, uid: $uid, allowAdminBypass: true);
}

$userGroups = $this->permissionResolver->resolveUserGroups($caller);

return $this->permissionResolver->matchesCaller(
permissions: $permissions,
caller: $caller,
userGroups: $userGroups,
allowAdminBypass: true,
roles: ['owners', 'editors', 'viewers']
);

}//end hasAnyRole()

/**
* Check whether the session caller holds any WRITE_ROLES entry on the Application.
*
Expand Down
22 changes: 12 additions & 10 deletions lib/Repair/MigrateAppOverridesToHybrid.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,10 @@ public function run(IOutput $output): void
foreach ($rows as $row) {
if ($this->migrateOne(row: $row, output: $output) === true) {
$migrated++;
} else {
$failed++;
continue;
}

$failed++;
}

$output->info('Migrate-app-overrides-to-hybrid: migrated '.$migrated.' override(s) to hybrid apps.');
Expand All @@ -130,16 +131,17 @@ public function run(IOutput $output): void
// retry; otherwise un-migrated overrides would be silently destroyed.
if ($failed === 0) {
$this->dropLegacySchema(schemaId: $schemaId, output: $output);
} else {
$output->warning(
'Migrate-app-overrides-to-hybrid: '.$failed.' override(s) failed to migrate; '
.'retaining the app-override schema and its rows for retry (schema NOT dropped).'
);
$this->logger->warning(
'OpenBuild: MigrateAppOverridesToHybrid: schema retained — '.$failed.' override(s) un-migrated'
);
return;
}

$output->warning(
'Migrate-app-overrides-to-hybrid: '.$failed.' override(s) failed to migrate; '
.'retaining the app-override schema and its rows for retry (schema NOT dropped).'
);
$this->logger->warning(
'OpenBuild: MigrateAppOverridesToHybrid: schema retained — '.$failed.' override(s) un-migrated'
);

}//end run()

/**
Expand Down
67 changes: 45 additions & 22 deletions lib/Repair/MigrateToVersionedModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@

namespace OCA\OpenBuild\Repair;

use Closure;
use OCA\OpenBuild\AppInfo\Application;
use OCA\OpenBuild\Service\ApplicationVersionService;
use OCA\OpenRegister\Db\RegisterMapper;
Expand Down Expand Up @@ -230,13 +231,18 @@ public function run(IOutput $output): void
}
}

// Precedence unchanged: failed beats blocked beats done. Initialising to
// the default and keeping the if/else-if chain drops the bare `else`
// without adding a path — two independent ifs would have doubled run()'s
// already-flagged NPath complexity.
$state = self::STATE_DONE;
if ($sawFailed === true) {
$this->appConfig->setValueString(Application::APP_ID, self::STATE_KEY, self::STATE_FAILED);
$state = self::STATE_FAILED;
} else if ($sawBlocked === true) {
$this->appConfig->setValueString(Application::APP_ID, self::STATE_KEY, self::STATE_BLOCKED);
} else {
$this->appConfig->setValueString(Application::APP_ID, self::STATE_KEY, self::STATE_DONE);
$state = self::STATE_BLOCKED;
}

$this->appConfig->setValueString(Application::APP_ID, self::STATE_KEY, $state);
}//end run()

/**
Expand Down Expand Up @@ -391,15 +397,11 @@ private function migrateOne(array $application, IOutput $output, bool $hasSystem

if ($register !== null) {
try {
if ($hasSystemContext === true) {
$this->objectService->runAsSystem(
function () use ($register): void {
$this->registerService->delete(register: $register);
}
);
} else {
$this->registerService->delete(register: $register);
}
$this->runElevated(
work: function () use ($register): void {
$this->registerService->delete(register: $register);
}
);
} catch (Throwable $e) {
if ($hasSystemContext === false) {
// Expected/precondition-absent: no elevation available on
Expand Down Expand Up @@ -453,15 +455,11 @@ function () use ($register): void {
}

try {
if ($hasSystemContext === true) {
$this->objectService->runAsSystem(
function () use ($applicationUuid): void {
$this->objectService->deleteObject(uuid: $applicationUuid);
}
);
} else {
$this->objectService->deleteObject(uuid: $applicationUuid);
}
$this->runElevated(
work: function () use ($applicationUuid): void {
$this->objectService->deleteObject(uuid: $applicationUuid);
}
);
} catch (Throwable $e) {
if ($hasSystemContext === false) {
$this->logger->debug(
Expand Down Expand Up @@ -500,6 +498,31 @@ function () use ($applicationUuid): void {
return self::ROW_OK;
}//end migrateOne()

/**
* Run a unit of work under OpenRegister's system context when the installed
* release offers one, and plainly when it does not.
*
* Extracted from {@see self::migrateOne()}, which carried the same
* elevate-or-not if/else twice. Folding both into one guarded helper removes
* the else branches AND lowers migrateOne()'s NPath complexity, rather than
* trading one rule for another. The probe is the same `method_exists()` test
* `run()` uses to derive `$hasSystemContext`, so the choice is unchanged.
*
* @param Closure $work The work to run.
*
* @return void
*/
private function runElevated(Closure $work): void
{
if (method_exists($this->objectService, 'runAsSystem') === true) {
$this->objectService->runAsSystem($work);
return;
}

$work();

}//end runElevated()

/**
* Coerce an OR result entry to a plain associative array.
*
Expand Down
35 changes: 26 additions & 9 deletions lib/Repair/PopulateApplicationPermissions.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,7 @@ public function run(IOutput $output): void
$output->info('Populating permissions on pre-existing Applications...');

try {
$hasSystemContext = method_exists($this->objectService, 'runAsSystem') === true;

if ($hasSystemContext === true) {
$patched = $this->objectService->runAsSystem(
fn (): ?int => $this->patchApplicationsMissingPermissions(output: $output)
);
} else {
$patched = $this->patchApplicationsMissingPermissions(output: $output);
}
$patched = $this->patchAllApplications(output: $output);

if ($patched === null) {
$output->info('No Applications found; nothing to migrate.');
Expand All @@ -127,6 +119,31 @@ public function run(IOutput $output): void
}//end try
}//end run()

/**
* Patch every Application, elevating to a system context when the installed
* ObjectService offers one.
*
* Extracted from {@see self::run()}: the elevated and plain paths call the
* same worker, so an early return expresses the choice without an else
* branch. Older ObjectService builds have no `runAsSystem()`, hence the
* duck-typed probe.
*
* @param IOutput $output Repair output channel.
*
* @return int|null The number patched, or null when no Applications exist.
*/
private function patchAllApplications(IOutput $output): ?int
{
if (method_exists($this->objectService, 'runAsSystem') === true) {
return $this->objectService->runAsSystem(
fn (): ?int => $this->patchApplicationsMissingPermissions(output: $output)
);
}

return $this->patchApplicationsMissingPermissions(output: $output);

}//end patchAllApplications()

/**
* Find every Application row and patch the ones missing `permissions`.
*
Expand Down
Loading
Loading