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
16 changes: 8 additions & 8 deletions RELEASE.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
> v2.0.4 ~ "Sandbox migrations for extensions outside core's vendor"
> v2.0.5 ~ "App Review types that share a model"

# v2.0.4 — Sandbox migrations for extensions outside core's vendor
# v2.0.5 — App Review types that share a model

## Fixed

- **`sandbox:migrate` runs the migrations of extensions installed outside core's `vendor` directory.** It made each extension's migration path relative by cutting it at the first `vendor` segment. Two layouts broke:
- **Extensions project** (`api/extensions/vendor/...`, fleetbase/fleetbase#754): the path pointed at core's `vendor` instead, so those sandbox migrations never ran.
- **Path-linked package in development** (`packages/<name>`): the absolute path was passed as `--path`, which Laravel resolves against the base path.

Paths inside the app are now made relative by stripping the base path, and paths outside it are migrated with `--realpath`.
- **A second App Review type on the same model is read and changed as itself.** `AppReview::typeOf()` returns the first registered type whose model matches. Fleet-Ops registers an organization's Navigator app on `Company`, so any other type on `Company` (such as Fleet-Ops' customer apps) was always read, changed and checked as Navigator's.
- `accessFor()`, `isEnabledFor()`, `acceptsCode()`, `update()` and `status()` take an optional `?string $type` as their last argument. Left out, it is `typeOf($subject)`, so existing callers behave as before.
- A type registered for a different model never applies: `acceptsCode()` and `isEnabledFor()` answer false, `status()` reports no type, and `update()` throws.
- New `AppReview::resolveType($subject, $type)` gives the type a subject is checked as.
- The Console endpoint (`/int/v1/review-access/{type}/{id}`) and the OAuth endpoint (`/oauth/v1/review-access/{type}/{id}`) pass the route's `{type}` through, so each type keeps its own number, code and access row.

## Upgrade Steps

- Run `php artisan sandbox:migrate` to apply any extension sandbox migrations that were skipped before.
- No migration. Extensions that register more than one type on the same model must pass the type to the calls above.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "fleetbase/core-api",
"version": "2.0.4",
"version": "2.0.5",
"description": "Core Framework and Resources for Fleetbase API",
"keywords": [
"fleetbase",
Expand Down
6 changes: 3 additions & 3 deletions src/Http/Controllers/Internal/v1/ReviewAccessController.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function show(string $type, string $id, Request $request): JsonResponse
return response()->authorizationError();
}

return response()->json(['review_access' => AppReview::status($subject)]);
return response()->json(['review_access' => AppReview::status($subject, $type)]);
}

public function update(string $type, string $id, Request $request): JsonResponse
Expand All @@ -54,9 +54,9 @@ public function update(string $type, string $id, Request $request): JsonResponse

$enabled = $request->has('enabled') ? $request->boolean('enabled') : null;

[, $code] = AppReview::update($subject, $enabled, $request->boolean('regenerate_code'), $request->session()->get('user'));
[, $code] = AppReview::update($subject, $enabled, $request->boolean('regenerate_code'), $request->session()->get('user'), $type);

$status = AppReview::status($subject);
$status = AppReview::status($subject, $type);
if ($code !== null) {
$status['code'] = $code;
}
Expand Down
6 changes: 3 additions & 3 deletions src/Http/Controllers/OAuthServer/ResourceController.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,12 +186,12 @@ public function reviewAccess(Request $request, string $type, string $id): JsonRe
}

if ($request->isMethod('GET')) {
return new JsonResponse(['review_access' => AppReview::status($subject)], 200, ['Cache-Control' => 'no-store']);
return new JsonResponse(['review_access' => AppReview::status($subject, $type)], 200, ['Cache-Control' => 'no-store']);
}

$enabled = !$request->isMethod('DELETE');
[, $plainCode] = AppReview::update($subject, $enabled, $enabled && $request->boolean('regenerate_code'), $token->user_uuid);
$status = AppReview::status($subject);
[, $plainCode] = AppReview::update($subject, $enabled, $enabled && $request->boolean('regenerate_code'), $token->user_uuid, $type);
$status = AppReview::status($subject, $type);
if ($plainCode !== null) {
$status['code'] = $plainCode;
}
Expand Down
57 changes: 42 additions & 15 deletions src/Support/AppReview.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ public static function definition(string $type): ?array

/**
* The registered type of a subject: the first type whose model it is.
*
* Two types can share a model (an organization's Navigator app and its customer apps are
* both a Company), and this only ever finds the first. Code working with any other type
* passes it to accessFor(), isEnabledFor(), acceptsCode(), update() and status().
*/
public static function typeOf(?Model $subject): ?string
{
Expand Down Expand Up @@ -194,12 +198,34 @@ public static function resolveSubject(string $type, string $id, ?string $company
return $companyUuid ? $query->where('company_uuid', $companyUuid)->first() : null;
}

/**
* The registered type a subject is checked as: the given type when its model is the
* subject's, otherwise the subject's first type (typeOf()). A type registered for another
* model gives null, so a Store can never be read or changed as a Company's type.
*/
public static function resolveType(?Model $subject, ?string $type = null): ?string
{
if (!$subject) {
return null;
}

if ($type === null) {
return static::typeOf($subject);
}

$definition = static::definition($type);

return $definition && $subject instanceof $definition['model'] ? $type : null;
}

/**
* The App Review access record of a subject, if it has one.
*
* @param ?string $type the subject's type; defaults to typeOf($subject)
*/
public static function accessFor(?Model $subject): ?ReviewAccess
public static function accessFor(?Model $subject, ?string $type = null): ?ReviewAccess
{
$type = static::typeOf($subject);
$type = static::resolveType($subject, $type);
if (!$type || blank($subject->uuid)) {
return null;
}
Expand All @@ -212,23 +238,23 @@ public static function accessFor(?Model $subject): ?ReviewAccess
}
}

public static function isEnabledFor(?Model $subject): bool
public static function isEnabledFor(?Model $subject, ?string $type = null): bool
{
return (bool) static::accessFor($subject)?->isUsable();
return (bool) static::accessFor($subject, $type)?->isUsable();
}

/**
* Whether a code signs the subject type's review number in to this subject: its access is
* on and the code is the one it generated. Another subject's code never matches.
*/
public static function acceptsCode(?Model $subject, ?string $identity, mixed $code): bool
public static function acceptsCode(?Model $subject, ?string $identity, mixed $code, ?string $type = null): bool
{
$type = static::typeOf($subject);
$type = static::resolveType($subject, $type);
if (!$type || !static::isReviewPhone($identity, $type) || blank($code) || !is_scalar($code)) {
return false;
}

$access = static::accessFor($subject);
$access = static::accessFor($subject, $type);
if (!$access || !$access->isUsable() || !$access->checkCode((string) $code)) {
return false;
}
Expand All @@ -248,14 +274,15 @@ public static function acceptsCode(?Model $subject, ?string $identity, mixed $co
*
* @return array{0: ReviewAccess, 1: ?string} the access and the new plain code, if one was generated
*/
public static function update(Model $subject, ?bool $enabled, bool $regenerate = false, ?string $updatedByUuid = null): array
public static function update(Model $subject, ?bool $enabled, bool $regenerate = false, ?string $updatedByUuid = null, ?string $type = null): array
{
$type = static::typeOf($subject);
if (!$type) {
throw new \InvalidArgumentException('No App Review type is registered for ' . get_class($subject) . '.');
$resolved = static::resolveType($subject, $type);
if (!$resolved) {
throw new \InvalidArgumentException($type === null ? 'No App Review type is registered for ' . get_class($subject) . '.' : "App Review type [{$type}] is not registered for " . get_class($subject) . '.');
}
$type = $resolved;

$access = static::accessFor($subject) ?? new ReviewAccess([
$access = static::accessFor($subject, $type) ?? new ReviewAccess([
'company_uuid' => $subject instanceof Company ? $subject->uuid : $subject->company_uuid,
'subject_type' => $type,
'subject_uuid' => $subject->uuid,
Expand Down Expand Up @@ -285,10 +312,10 @@ public static function update(Model $subject, ?bool $enabled, bool $regenerate =
* What the Console and the API show about a subject's access. Never the code or its hash;
* a caller adds `code` only to the response that generated it.
*/
public static function status(Model $subject): array
public static function status(Model $subject, ?string $type = null): array
{
$type = static::typeOf($subject);
$access = static::accessFor($subject);
$type = static::resolveType($subject, $type);
$access = $type ? static::accessFor($subject, $type) : null;
$phone = $type ? static::phoneFor($type) : null;

return [
Expand Down
14 changes: 14 additions & 0 deletions tests/Unit/Auth/OAuthServer/OAuthServerEndpointsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ public function clear(): void

afterEach(function () {
AppReview::forget('test-navigator');
AppReview::forget('test-customer');
oauth_test_teardown();
});

Expand Down Expand Up @@ -164,6 +165,19 @@ function oauth_review_call(string $token, string $method, string $id = 'company_
expect($response->getStatusCode())->toBe(404);
});

it('changes the type in the route when another type shares the model', function () {
AppReview::register('test-customer', ['model' => Company::class, 'phone' => '+12025550145', 'name' => 'Customer apps']);
OAuthScopes::register('customer:review-access', ['description' => 'Turn App Review sign-in on or off', 'organization' => true, 'review_access_types' => ['test-customer']]);
$token = oauth_endpoint_token('openid customer:review-access');
$request = Request::create('/oauth/v1/review-access/test-customer/company_a', 'PUT', [], [], [], ['HTTP_AUTHORIZATION' => 'Bearer ' . $token]);

$on = oauth_endpoint_call($request, [], fn ($request) => (new ResourceController())->reviewAccess($request, 'test-customer', 'company_a'))->getData(true)['review_access'];

expect($on)->toMatchArray(['type' => 'test-customer', 'phone' => '+12025550145', 'enabled' => true])
->and($on['code'])->toMatch('/^\d{6}$/')
->and(ReviewAccess::pluck('subject_type')->all())->toBe(['test-customer']);
});

it('cannot reach another organization', function () {
$token = oauth_endpoint_token('openid navigator:review-access');

Expand Down
66 changes: 65 additions & 1 deletion tests/Unit/Support/AppReviewTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ function app_review_console_request(string $company, array $input = [], string $
}

afterEach(function () {
foreach (['test-store', 'test-network', 'test-navigator', 'test-guarded', 'test-resolved', 'test-unreachable'] as $type) {
foreach (['test-store', 'test-network', 'test-navigator', 'test-guarded', 'test-resolved', 'test-unreachable', 'test-customer'] as $type) {
AppReview::forget($type);
}
EloquentModel::unsetConnectionResolver();
Expand Down Expand Up @@ -249,6 +249,70 @@ function app_review_console_request(string $company, array $input = [], string $
->and(AppReview::resolveSubject('test-navigator', 'company_b', 'company-a'))->toBeNull();
});

test('two types on the same model each have their own number, code and access', function () {
app_review_database();
AppReview::register('test-customer', ['model' => Company::class, 'phone' => '+12025550145', 'name' => 'Customer apps']);
$company = Company::where('uuid', 'company-a')->first();
$other = Company::where('uuid', 'company-b')->first();

// Without a type, a company is still the first type registered for it.
expect(AppReview::typeOf($company))->toBe('test-navigator')
->and(AppReview::resolveType($company, 'test-customer'))->toBe('test-customer')
// A type registered for another model never applies to a company.
->and(AppReview::resolveType($company, 'test-store'))->toBeNull()
->and(AppReview::resolveType($company, 'nothing'))->toBeNull()
->and(AppReview::isEnabledFor($company, 'test-customer'))->toBeFalse();

[, $customerCode] = AppReview::update($company, true, false, null, 'test-customer');

expect(AppReview::isEnabledFor($company, 'test-customer'))->toBeTrue()
->and(AppReview::isEnabledFor($company))->toBeFalse()
->and(AppReview::status($company, 'test-customer'))->toMatchArray(['type' => 'test-customer', 'phone' => '+12025550145', 'phone_display' => '+1 202 555 0145', 'enabled' => true, 'has_code' => true])
->and(AppReview::status($company))->toMatchArray(['type' => 'test-navigator', 'phone' => '+12025550144', 'enabled' => false, 'has_code' => false])
->and(AppReview::acceptsCode($company, '+12025550145', $customerCode, 'test-customer'))->toBeTrue()
// The other type's number, the other type, and another company's access refuse it.
->and(AppReview::acceptsCode($company, '+12025550144', $customerCode, 'test-customer'))->toBeFalse()
->and(AppReview::acceptsCode($company, '+12025550145', $customerCode))->toBeFalse()
->and(AppReview::acceptsCode($other, '+12025550145', $customerCode, 'test-customer'))->toBeFalse()
->and(AppReview::acceptsCode($company, '+12025550145', $customerCode, 'test-store'))->toBeFalse();

do {
[, $navigatorCode] = AppReview::update($company, true, true, null, 'test-navigator');
} while ($navigatorCode === $customerCode);

expect(AppReview::acceptsCode($company, '+12025550144', $navigatorCode))->toBeTrue()
->and(AppReview::acceptsCode($company, '+12025550145', $navigatorCode, 'test-customer'))->toBeFalse()
->and(AppReview::acceptsCode($company, '+12025550145', $customerCode, 'test-customer'))->toBeTrue()
->and(ReviewAccess::where('subject_uuid', 'company-a')->orderBy('subject_type')->pluck('subject_type')->all())->toBe(['test-customer', 'test-navigator']);

// Turning one off leaves the other on.
AppReview::update($company, false, false, null, 'test-customer');
expect(AppReview::isEnabledFor($company, 'test-customer'))->toBeFalse()
->and(AppReview::isEnabledFor($company, 'test-navigator'))->toBeTrue()
->and(fn () => AppReview::update($company, true, false, null, 'test-store'))->toThrow(InvalidArgumentException::class);
});

test('the Console endpoint changes the type in its route, not the model\'s first type', function () {
app_review_database();
AppReview::register('test-customer', ['model' => Company::class, 'phone' => '+12025550145']);
app()->instance('validator', new Illuminate\Validation\Factory(new Illuminate\Translation\Translator(new Illuminate\Translation\ArrayLoader(), 'en'), app()));
Request::macro('validate', function (array $rules) {
return app('validator')->make($this->all(), $rules)->validate();
});
$controller = new ReviewAccessController();

$on = $controller->update('test-customer', 'company_a', app_review_console_request('company-a', ['enabled' => true]))->getData(true)['review_access'];
$show = $controller->show('test-customer', 'company_a', app_review_console_request('company-a', [], 'GET'))->getData(true)['review_access'];
$nav = $controller->show('test-navigator', 'company_a', app_review_console_request('company-a', [], 'GET'))->getData(true)['review_access'];
$company = Company::where('uuid', 'company-a')->first();

expect($on)->toMatchArray(['type' => 'test-customer', 'phone' => '+12025550145', 'enabled' => true])
->and($show)->toMatchArray(['type' => 'test-customer', 'enabled' => true, 'has_code' => true])
->and($nav)->toMatchArray(['type' => 'test-navigator', 'enabled' => false, 'has_code' => false])
->and(AppReview::acceptsCode($company, '+12025550145', $on['code'], 'test-customer'))->toBeTrue()
->and(ReviewAccess::first()->subject_type)->toBe('test-customer');
});

test('a subject is found by uuid or public id in the signed-in company only', function () {
app_review_database();

Expand Down
Loading