A free open source IT asset/license management system
Merge branch 'develop' into use_new_laravel_scim_server
Brady Wetherington9d33a2c52432
diff --cc app/Models/Group.phpindex fbe98162dc,dd00417dc7..1cf1f2d955--- a/app/Models/Group.php+++ b/app/Models/Group.php@@@ -56,15 -72,9 +72,15 @@@ class Group extends SnipeMode*/public function users(){- return $this->belongsToMany(\App\Models\User::class, 'users_groups');+ return $this->belongsToMany(User::class, 'users_groups');}+ /* this is just a shim for SCIM to work */+ public function members()+ {+ return $this->users();+ }+/*** Get the user that created the group*diff --cc app/Models/SCIMUser.phpindex 87b023dc58,e893638cc1..125f3dd737--- a/app/Models/SCIMUser.php+++ b/app/Models/SCIMUser.php@@@ -13,11 -13,4 +13,12 @@@ class SCIMUser extends Use$attributes['password'] = $this->noPassword();parent::__construct($attributes);}-}++ // Have to re-define this here because Eloquent will try to 'guess' a foreign key of s_c_i_m_user_id+ // from SCIMUser+ public function groups()+ {+ return $this->belongsToMany(\App\Models\Group::class, 'users_groups', 'user_id', 'group_id');+ }+++}diff --cc app/Models/SnipeSCIMConfig.phpindex 188870dad6,411e44678e..b7fcaf29e8--- a/app/Models/SnipeSCIMConfig.php+++ b/app/Models/SnipeSCIMConfig.php@@@ -2,484 -2,248 +2,487 @@@namespace App\Models;-use ArieTimmerman\Laravel\SCIMServer\Attribute\AttributeMapping;+use ArieTimmerman\Laravel\SCIMServer\Exceptions\SCIMException;+use ArieTimmerman\Laravel\SCIMServer\Helper;+use ArieTimmerman\Laravel\SCIMServer\Parser\Path;use ArieTimmerman\Laravel\SCIMServer\SCIM\Schema;-use ArieTimmerman\Laravel\SCIMServer\SCIMConfig;+use ArieTimmerman\Laravel\SCIMServer\Attribute\Attribute;+use ArieTimmerman\Laravel\SCIMServer\Attribute\Collection;+use ArieTimmerman\Laravel\SCIMServer\Attribute\Complex;+use ArieTimmerman\Laravel\SCIMServer\Attribute\Constant;+use ArieTimmerman\Laravel\SCIMServer\Attribute\Eloquent;+use ArieTimmerman\Laravel\SCIMServer\Attribute\JSONCollection;+use ArieTimmerman\Laravel\SCIMServer\Attribute\Meta;+use ArieTimmerman\Laravel\SCIMServer\Attribute\MutableCollection;+use ArieTimmerman\Laravel\SCIMServer\Attribute\Schema as AttributeSchema;use Illuminate\Database\Eloquent\Model;++use ArieTimmerman\Laravel\SCIMServer\Attribute\AttributeMapping;++use ArieTimmerman\Laravel\SCIMServer\SCIMConfig;-class SnipeSCIMConfig extends SCIMConfig+function a($name = null): Attribute{- public function getUserConfig()+ return new Attribute($name);+}++function complex($name = null): Complex+{+ return new Complex($name);+}++function eloquent($name, $attribute = null): Attribute+{+ return new Eloquent($name, $attribute);+}++class EloquentWithRemove extends Eloquent+{+ public function remove($value, Model &$object, Path $path = null)+ {+ $object->{$this->attribute} = null;+ }++}++class MappedTable extends Attribute+{+ public function __construct(+ private string $scim_attribute_name,+ private string $relationship_name,+ private string $relationship_class,+ private string $relationship_id_field,+ private string $relationship_field)+ {+ parent::__construct($this->scim_attribute_name);+ }++ protected function doRead(&$object, $attributes = [])+ {+ return $object->{$this->relationship_name}?->{$this->relationship_field};+ }++ public function add($value, Model &$object)+ {+ $object->{$this->relationship_id_field} = $value ? $this->relationship_class::firstOrCreate([$this->relationship_field => $value])->id : null;+ }++ public function replace($value, Model &$object, $path = null, $removeIfNotSet = false)+ {+ $object->{$this->relationship_id_field} = $value ? $this->relationship_class::firstOrCreate([$this->relationship_field => $value])->id : null;+ }++ public function patch($operation, $value, Model &$object, Path $path = null, $removeIfNotSet = false)+ {+ $object->{$this->relationship_id_field} = $value ? $this->relationship_class::firstOrCreate([$this->relationship_field => $value])->id : null;+ }++}++class UpdatableComplex extends Complex+{++ public function doWrite($operation, $subop, $value, Model &$object, Path $path = null, $removeIfNotSet = false){- // Much of this is copied verbatim from the library, then adjusted for our needs+ throw new \Exception("doWrite is not implemented yet for Operation: $operation " . ($subop ? "($subop)" : "") . "on attribute " . $this->getFullKey());+ }++ public function add($value, Model &$object)+ {+ $this->doWrite("add", null, $value, $object);+ }- /*- more snipe-it attributes I'd like to check out (to map to 'enterprise' maybe?):- - website- - notes?- - remote???- - location_id ?- - company_id to "organization?"- */+ public function replace($value, Model &$object, Path $path = null, $removeIfNotSet = false)+ {+ $this->doWrite("replace", null, $value, $object, $path, $removeIfNotSet);+ }- $user_prefix = 'urn:ietf:params:scim:schemas:core:2.0:User:';- $enterprise_prefix = 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:';+ public function patch($operation, $value, Model &$object, Path $path = null, $removeIfNotSet = false)+ {+ $this->doWrite("patch", $operation, $value, $object, $path, $removeIfNotSet);+ }++ public function remove($value, Model &$object, Path $path = null)+ {+ $this->doWrite("remove", null, null, $object, $path);+ }+}+++class SnipeSCIMConfig+{+ public function __construct()+ {+ }++ public function getConfigForResource($name)+ {+ $result = $this->getConfig();+ return @$result[$name];+ }++ public function getGroupClass()+ {+ return Group::class;+ }+ const ENTERPRISE = 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User';+ const GROKABILITY = 'urn:ietf:params:scim:schemas:extension:grokability:2.0:User';++ public function getUserConfig()+ {return [// Set to 'null' to make use of auth.providers.users.model (App\User::class)- 'class' => SCIMUser::class,-- 'validations' => [- $user_prefix.'userName' => 'required',- $user_prefix.'displayName' => 'nullable|string',- $user_prefix.'name.givenName' => 'required',- $user_prefix.'name.familyName' => 'nullable|string',- $user_prefix.'externalId' => 'nullable|string',- $user_prefix.'emails' => 'nullable|array',- $user_prefix.'emails.*.value' => 'nullable|email',- $user_prefix.'active' => 'boolean',- $user_prefix.'phoneNumbers' => 'nullable|array',- $user_prefix.'phoneNumbers.*.value' => 'nullable|string',- $user_prefix.'addresses' => 'nullable|array',- $user_prefix.'addresses.*.streetAddress' => 'nullable|string',- $user_prefix.'addresses.*.locality' => 'nullable|string',- $user_prefix.'addresses.*.region' => 'nullable|string',- $user_prefix.'addresses.*.postalCode' => 'nullable|string',- $user_prefix.'addresses.*.country' => 'nullable|string',- $user_prefix.'title' => 'nullable|string',- $user_prefix.'preferredLanguage' => 'nullable|string',-- // Enterprise validations:- $enterprise_prefix.'employeeNumber' => 'nullable|string',- $enterprise_prefix.'department' => 'nullable|string',- $enterprise_prefix.'manager' => 'nullable',- $enterprise_prefix.'manager.value' => 'nullable|string',- ],-+ 'class' => ScimUser::class,'singular' => 'User',- 'schema' => [Schema::SCHEMA_USER],- //eager loading+ // eager loading'withRelations' => [],- 'map_unmapped' => false,- // 'unmapped_namespace' => 'urn:ietf:params:scim:schemas:laravel:unmapped','description' => 'User Account',- // Map a SCIM attribute to an attribute of the object.- 'mapping' => [+ 'map' => complex()->withSubAttributes(+ new class ('schemas', [+ "urn:ietf:params:scim:schemas:core:2.0:User",+ self::ENTERPRISE,+ self::GROKABILITY+ ]) extends Constant {+ public function replace($value, &$object, $path = null)+ {+ // do nothing+ $this->dirty = true;+ }+ },+ (new class ('id', null) extends Constant { // TODO - this 'id' is in the same namespace for objects OR groups?+ protected function doRead(&$object, $attributes = [])+ {+ return (string)$object->id;+ }- 'id' => (new AttributeMapping)->setRead(- function (&$object) {- return (string) $object->id;+ public function remove($value, &$object, $path = null)+ {+ // do nothing}- )->disableWrite(),-- 'externalId' => AttributeMapping::eloquent('scim_externalid'), // FIXME - I have a PR that changes a lot of this.-- 'meta' => [- 'created' => AttributeMapping::eloquent('created_at')->disableWrite(),- 'lastModified' => AttributeMapping::eloquent('updated_at')->disableWrite(),-- 'location' => (new AttributeMapping)->setRead(- function ($object) {- return route(- 'scim.resource',- [- 'resourceType' => 'Users',- 'resourceObject' => $object->id,- ]- );+ }+ ),+ new Meta('Users'),+ (new AttributeSchema(Schema::SCHEMA_USER, true))->withSubAttributes(+ eloquent('userName', 'username')->ensure('required'),+ (new class ('active', 'activated') extends Eloquent {+ protected function doRead(&$object, $attributes = [])+ {+ return (bool)$object->activated; // need this extension to force boolean-ness}- )->disableWrite(),+ }),+ complex('name')->withSubAttributes(+ eloquent('givenName', 'first_name')->ensure('required'),+ eloquent('familyName', 'last_name'),+ ), // ->ensure('required'), It *is* a bit weird, but I would've thought 'name' is required since 'givenName' is required? But apparently not?+ eloquent('displayName', 'display_name'), //yes, this is *not* under 'name' - that's the spec+ //eloquent('password')->ensure('nullable')->setReturned('never'),+ eloquent('externalId', 'scim_externalid'),- 'resourceType' => AttributeMapping::constant('User'),- ],-- 'schemas' => AttributeMapping::constant(- [- 'urn:ietf:params:scim:schemas:core:2.0:User',- 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User',- ]- )->ignoreWrite(),+ // Email chonk+ (new class ('emails') extends UpdatableComplex {+ protected function doRead(&$object, $attributes = [])+ {+ return collect([$object->email])->map(function ($email) {+ return [+ 'value' => $email,+ 'type' => 'work', //TODO - is this how we always have done it?+ 'primary' => true+ ];+ })->toArray();+ }- 'urn:ietf:params:scim:schemas:core:2.0:User' => [+ public function doWrite($operation, $subop, $value, Model &$object, Path $path = null, $removeIfNotSet = false)+ {+ if ($value) {+ $object->email = $value[0]['value'];+ } else {+ $object->email = null;+ }+ }+ })->withSubAttributes(+ eloquent('value', 'email')->ensure('email', 'nullable'), //Weird, this 'needs' nullable to work?+ new Constant('type', 'work'),+ new Constant('primary', true)->ensure('boolean')+ )->ensure('array')+ ->setMultiValued(true),- 'userName' => AttributeMapping::eloquent('username'),+ // phone chonk+ (new class ('phoneNumbers') extends UpdatableComplex {+ protected function doRead(&$object, $attributes = [])+ {+ $phones = [];+ if ($object->phone) {+ $phones[] = [+ 'value' => $object->phone,+ 'type' => 'work'+ ];+- 'name' => [- 'formatted' => (new AttributeMapping)->ignoreWrite()->setRead(- function (&$object) {- return $object->getFullNameAttribute();}- ),- 'familyName' => AttributeMapping::eloquent('last_name'),- 'givenName' => AttributeMapping::eloquent('first_name'),- 'middleName' => null,- 'honorificPrefix' => null,- 'honorificSuffix' => null,- ],-- 'displayName' => AttributeMapping::eloquent('display_name'),- 'nickName' => null,- 'profileUrl' => null,- 'title' => AttributeMapping::eloquent('jobtitle'),- 'userType' => null,- 'preferredLanguage' => AttributeMapping::eloquent('locale'), // Section 5.3.5 of [RFC7231]- 'locale' => null, // see RFC5646- 'timezone' => null, // see RFC6557- 'active' => (new AttributeMapping)->setAdd(- function ($value, &$object) {- $object->activated = $value;- }- )->setReplace(- function ($value, &$object) {- $object->activated = $value;- }- )->setRead(- // this works as specified.- function (&$object) {- return (bool) $object->activated;+ if ($object->mobile) {+ $phones[] = [+ 'value' => $object->mobile,+ 'type' => 'mobile'+ ];+ }+ return $phones;}- ),- 'password' => AttributeMapping::eloquent('password')->disableRead(),-- // Multi-Valued Attributes- 'emails' => [[- 'value' => AttributeMapping::eloquent('email'),- 'display' => null,- 'type' => AttributeMapping::constant('work')->ignoreWrite(),- 'primary' => AttributeMapping::constant(true)->ignoreWrite(),- ]],-- 'phoneNumbers' => [[- 'value' => AttributeMapping::eloquent('phone'),- 'display' => null,- 'type' => AttributeMapping::constant('work')->ignoreWrite(),- 'primary' => AttributeMapping::constant(true)->ignoreWrite(),- ]],-- 'ims' => [[- 'value' => null,- 'display' => null,- 'type' => null,- 'primary' => null,- ]], // Instant messaging addresses for the User-- 'photos' => [[- 'value' => null,- 'display' => null,- 'type' => null,- 'primary' => null,- ]],-- 'addresses' => [[- 'type' => AttributeMapping::constant('work')->ignoreWrite(),- 'formatted' => AttributeMapping::constant('n/a')->ignoreWrite(), // TODO - is this right? This doesn't look right.- 'streetAddress' => AttributeMapping::eloquent('address'),- 'locality' => AttributeMapping::eloquent('city'),- 'region' => AttributeMapping::eloquent('state'),- 'postalCode' => AttributeMapping::eloquent('zip'),- 'country' => AttributeMapping::eloquent('country'),- 'primary' => AttributeMapping::constant(true)->ignoreWrite(), // this isn't in the example?- ]],-- 'groups' => [[- 'value' => null,- '$ref' => null,- 'display' => null,- 'type' => null,- ]],-- 'entitlements' => null,- 'roles' => null,- 'x509Certificates' => null,- ],-- 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User' => [- 'employeeNumber' => AttributeMapping::eloquent('employee_num'),- 'department' => (new AttributeMapping)->setAdd( // FIXME parent?- function ($value, &$object) {- $department = Department::where('name', $value)->first();- if ($department) {- $object->department_id = $department->id;++ public function doWrite($operation, $subop, $value, Model &$object, Path $path = null, $removeIfNotSet = false)+ {+ \Log::debug("Phones 'value' is: " . print_r($value, true));+ if ($operation == "patch") {+ if ($path->getValuePathFilter() != null) {+ if ((string)$path == 'phoneNumbers[type eq "mobile"].value') {+ $object->mobile = $value; //I don't know why the value is the raw value, but it is?+ return;+ }+ if ((string)$path == 'phoneNumbers[type eq "work"].value') {+ $object->phone = $value; //similar, don't know why, but it is+ return;+ }+ }+ parent::patch($subop, $value, $object, $path, $removeIfNotSet);+ return;+ }+ foreach ($value as $phone) {+ switch ($phone['type']) {+ case 'work':+ $object->phone = $phone['value'];+ break;++ case 'mobile':+ $object->mobile = $phone['value'];+ break;++ default:+ throw new SCIMException("Unknown phone type '" . @$phone['type'] . "'", 400);+ }}}- )->setReplace(- function ($value, &$object) {- $department = Department::where('name', $value)->first();- if ($department) {- $object->department_id = $department->id;++ })->withSubAttributes( // TODO: I suspect these 'sub-attributes' aren't being checked at all+ new Constant('value', 'email')->ensure('string'), // TODO - this is WRONG, but it works somehow? Probably because it's ignored+ new Constant('type', 'other'), // TODO uh, *also* wrong? but, again, seems to be ignored+ )->ensure('array')+ ->setMultiValued(true),++ // addresses chonk+ (new class ('addresses') extends UpdatableComplex {+ static $addressmap = [+ 'streetAddress' => 'address',+ 'locality' => 'city',+ 'region' => 'state',+ 'postalCode' => 'zip',+ 'country' => 'country'+ ];++ protected function doRead(&$object, $attributes = [])+ {+ $address = [];+ foreach (self::$addressmap as $scim_field => $db_field) {+ if ($object->{$db_field}) {+ $address[$scim_field] = $object->{$db_field};+ }}+ if (count($address) > 0) {+ $address['type'] = 'work';+ $address['primary'] = true;+ }+ return $address;}- )->setRead(- function (&$object) {- return $object->department ? $object->department->name : null;++ public function doWrite($operation, $subop, $value, Model &$object, Path $path = null, $removeIfNotSet = false)+ {+ // TODO - this is validated *just* for 'patch' operations, so this may not work in other write contexts+ if ($path->getValuePathFilter() != null) {+ \Log::debug("path for update $path");+ // get the part of the $path that we actually care about - something like:+ // addresses[type eq "work"]+ $matches = null;+ if (!preg_match('/^.+\[type eq "([a-zA-Z]+)"](?:\.([a-zA-Z]+))?$/', (string)$path, $matches)) {+ throw new \Exception("Unknown path type '$path'");+ }+ $type = $matches[1];+ if ($type != 'work') {+ throw new \Exception("Unknown object type '$type'");+ }+ $attribute = array_key_exists(2, $matches) ? $matches[2] : null;+ if (array_key_exists($attribute, self::$addressmap)) {+ $object->{self::$addressmap[$attribute]} = $value;+ return;+ }+++ throw new \Exception("path for update $path");+ }}++ })->withSubAttributes(+ eloquent('streetAddress', 'address'),+ eloquent('locality', 'city'),+ eloquent('region', 'state'),+ eloquent('postalCode', 'zip'),+ eloquent('country', 'country'),+ new Constant('type', 'other'),+ new Constant('primary', true)->ensure('boolean')+ )->ensure('array')+ ->setMultiValued(true),++ eloquent('title', 'jobtitle'),+ eloquent('preferredLanguage', 'locale'),+ (new Collection('groups'))->withSubAttributes(+ eloquent('value', 'id'),+ (new class ('$ref') extends Eloquent {+ protected function doRead(&$object, $attributes = [])+ {+ return route(+ 'scim.resource',+ [+ 'resourceType' => 'Group',+ 'resourceObject' => $object->id ?? "not-saved"+ ]+ );+ }+ }),+ eloquent('display', 'name')),- 'manager' => [- // FIXME - manager writes are disabled. This kinda works but it leaks errors all over the place. Not cool.- // '$ref' => (new AttributeMapping())->ignoreWrite()->ignoreRead(),- // 'displayName' => (new AttributeMapping())->ignoreWrite()->ignoreRead(),- // NOTE: you could probably do a 'plain' Eloquent mapping here, but we don't for future-proofing- 'value' => (new AttributeMapping)->setAdd(- function ($value, &$object) {- $manager = User::find($value);- if ($manager) {- $object->manager_id = $manager->id;- }+ (new JSONCollection('roles'))->withSubAttributes( // TODO - what is this?+ eloquent('value')->ensure('required', 'min:3', 'alpha_dash:ascii'),+ eloquent('display')->ensure('nullable', 'min:3', 'alpha_dash:ascii'),+ eloquent('type')->ensure('nullable', 'min:3', 'alpha_dash:ascii'),+ eloquent('primary')->ensure('boolean')->default(false)+ )->ensure('nullable', 'array', 'max:20')+ ),+ (new AttributeSchema(self::ENTERPRISE, false))->withSubAttributes(+ eloquent('employeeNumber', 'employee_num')->ensure('nullable'),+ new MappedTable('department', 'department', Department::class, 'department_id', 'name'),+ (new class('manager') extends UpdatableComplex {+ protected function doRead(&$object, $attributes = [])+ {+ if (!$object->manager) {+ return null;}- )->setReplace(- function ($value, &$object) {- $manager = User::find($value);- if ($manager) {- $object->manager_id = $manager->id;+ return [+ 'value' => $object->manager->id, //TODO - ID's aren't unique like they're supposed to be :/+ '$ref' => route('scim.resource', ['resourceType' => 'User', 'resourceObject' => $object->manager->id]),+ 'displayName' => $object->manager->display_name,+ ];+ }++ public function doWrite($operation, $subop, $value, Model &$object, $path = null, $removeIfNotSet = false)+ {+ \Log::debug("What type of value is value? " . gettype($value));+ $manager_id = null;+ if (is_scalar($value)) {+ \Log::debug("Weird Microsoft mode - set manager to the \$value and move on with life?");+ $manager_id = $value;+ } elseif (array_key_exists('$ref', $value)) {+ // Here's the spec: https://datatracker.ietf.org/doc/html/rfc7643#section-4.3++ // according to the spec it's _recommended_ to do:+ // $ref - which should be the URI of the manager++ // extract ID from URL, jam it in?+ $url = $value['$ref'];+ $users_prefix = route('scim.resources', ['resourceType' => 'User']) . '/';+ if (string_starts_with($url, $users_prefix)) {+ $manager_id = substr($url, strlen($users_prefix));}+ } elseif (array_key_exists('value', $value)) {+ // this is _Snipe-IT_'s ID being passed as 'value' I believe?+ // if you use the 'managerId' field in Okta, you get:+ // [value] => 9999999+ // that, at least, is the spec - but *what* ID is that?! It's supposed to be a Snipe-IT one!+ $manager_id = $value['value'];+ }+ \Log::debug("Non-Microsoft - Trying to '$operation' for manager with value: " . print_r($value, true));+ if ($manager_id && User::find($manager_id)) {+ $object->manager_id = $manager_id;+ return;}- )->setRead(- function (&$object) {- return $object->manager_id;+ throw new SCIMException("No manager given, or manager doesn't exist", 400);+ }+ }) // ->withSubAttributes() ... -> ensure() ?+ ),+ (new AttributeSchema(self::GROKABILITY, false))->withSubAttributes(+ new MappedTable('location', 'location', Location::class, 'location_id', 'name'),+ new MappedTable('company', 'company', Company::class, 'company_id', 'name'),+ )+ ),+ ];+ }++ public function getGroupConfig()+ {+ return [++ 'class' => $this->getGroupClass(),+ 'singular' => 'Group',++ //eager loading+ 'withRelations' => [],+ 'description' => 'Group',++ 'map' => complex()->withSubAttributes(+ new class ('schemas', [+ "urn:ietf:params:scim:schemas:core:2.0:Group",+ ]) extends Constant {+ public function replace($value, &$object, $path = null)+ {+ // do nothing+ $this->dirty = true;+ }+ },+ (new class ('id', null) extends Constant {+ protected function doRead(&$object, $attributes = [])+ {+ return (string)$object->id;+ }++ public function remove($value, &$object, $path = null)+ {+ // do nothing+ }+ }+ ),+ new EloquentWithRemove('externalId', 'scim_externalid'),+ new Meta('Groups'),+ (new AttributeSchema(Schema::SCHEMA_GROUP, true))->withSubAttributes(+ eloquent('displayName', 'name')->ensure('required', 'min:3', function ($attribute, $value, $fail) {+ // check if group does not exist or if it exists, it is the same group+ $group = $this->getGroupClass()::where('name', $value)->first();+ if ($group && (request()->route('resourceObject') == null || $group->id != request()->route('resourceObject')->id)) {+ $fail('The name has already been taken.');+ }+ }),+ (new MutableCollection('members'))->withSubAttributes(+ eloquent('value', 'id')->ensure('required'),+ (new class ('$ref') extends Eloquent {+ protected function doRead(&$object, $attributes = [])+ {+ return route(+ 'scim.resource',+ [+ 'resourceType' => 'Users',+ 'resourceObject' => $object->id ?? "not-saved"+ ]+ );}- ),- ],- ],- ],+ }),+ eloquent('display', 'name')+ )->ensure('nullable', 'array')+ )+ ),+ ];+ }++ public function getConfig()+ {+ return [+ 'Users' => $this->getUserConfig(),+ 'Groups' => $this->getGroupConfig(),];}}