A free open source IT asset/license management system
Better handle SCIM with malformed attributes
snipe5efdb46f0a5c
diff --git a/app/Models/SnipeSCIMConfig.php b/app/Models/SnipeSCIMConfig.phpindex 4a3963b636..a5d54d1dc6 100644--- a/app/Models/SnipeSCIMConfig.php+++ b/app/Models/SnipeSCIMConfig.php@@ -17,6 +17,7 @@ use ArieTimmerman\Laravel\SCIMServer\Parser\Path;use ArieTimmerman\Laravel\SCIMServer\SCIM\Schema;use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Model;+use Tmilos\ScimFilterParser\Error\FilterException;function a($name = null): Attribute{@@ -60,7 +61,18 @@ class SnipeRootComplex extends Complexthrow new SCIMException('Invalid key: '.$key.' for complex object '.$this->getFullKey());}- $path = Parser::parse($key);+ // Malformed keys like `[type eq "work"]` (a value-path filter+ // with no leading attribute name) make the Tmilos parser throw+ // FilterException before we can inspect the parsed shape.+ // Same class of misconfigured-client problem as the null-guard+ // below, one layer further back — turn it into a 400 so the+ // caller sees "your key is malformed" instead of a 500 that+ // looks like our fault.+ try {+ $path = Parser::parse($key);+ } catch (FilterException $e) {+ throw new SCIMException('SnipeRootComplex::add: Malformed SCIM key: '.$key.' ('.$e->getMessage().')', 400);+ }if ($path->isNotEmpty()) {// Path::isNotEmpty() returns true when EITHER the@@ -128,7 +140,11 @@ class SnipeRootComplex extends Complex$key = trim($key);if (strpos($key, ':') !== false) {- $parsed = Parser::parse($key);+ try {+ $parsed = Parser::parse($key);+ } catch (FilterException $e) {+ throw new SCIMException('SnipeRootComplex::replace: Malformed SCIM key: '.$key.' ('.$e->getMessage().')', 400);+ }$schemaUrn = $parsed->getAttributePath()?->path?->schema;$attrName = $parsed->getAttributePathAttributes()[0] ?? null;if ($schemaUrn !== null && $attrName !== null) {@@ -138,7 +154,14 @@ class SnipeRootComplex extends Complex$subNode = $this->getSubNode($key);}} else {- $path = Parser::parse($key);+ // See the matching try/catch in add() — malformed keys+ // starting with `[` throw FilterException from the parser+ // itself, before any of our null-guards fire.+ try {+ $path = Parser::parse($key);+ } catch (FilterException $e) {+ throw new SCIMException('SnipeRootComplex::replace: Malformed SCIM key: '.$key.' ('.$e->getMessage().')', 400);+ }if ($path->isNotEmpty()) {// See the matching guard in add() — isNotEmpty() lets// a value-path-only key through (e.g. emails[type eq@@ -437,11 +460,18 @@ class SnipeSCIMConfigreturn null;}- return [+ // RFC 7643 §4.1.2: multi-valued attributes MUST be+ // JSON arrays even when they hold a single element.+ // Return an array-of-objects so `emails` serializes+ // as `[{...}]`. Previously returned a bare+ // associative array and Rollbar surfaced downstream+ // clients constructing malformed filter keys against+ // the scalar shape.+ return [['value' => $object->email,- 'type' => 'work', // TODO - is this how we always have done it?+ 'type' => 'work','primary' => true,- ];+ ]];}public function doWrite($operation, $subop, $value, Model &$object, ?Path $path = null, $removeIfNotSet = false)diff --git a/tests/Feature/Scim/ReplaceUserWithMalformedKeyTest.php b/tests/Feature/Scim/ReplaceUserWithMalformedKeyTest.phpnew file mode 100644index 0000000000..ea5f5f1f8e--- /dev/null+++ b/tests/Feature/Scim/ReplaceUserWithMalformedKeyTest.php@@ -0,0 +1,66 @@+<?php++namespace Tests\Feature\Scim;++use App\Models\User;+use Laravel\Passport\Passport;+use Tests\TestCase;++class ReplaceUserWithMalformedKeyTest extends TestCase+{+ /**+ * Regression for a Rollbar 500 traced to keys the Tmilos filter parser+ * can't parse at all, distinct from the ReplaceUserWithFilterKeyTest+ * case where the parser succeeds but returns a value-path-only Path.+ * Here the key starts with `[` with no leading attribute name, and+ * Parser::parse() itself throws:+ *+ * Tmilos\ScimFilterParser\Error\FilterException [Syntax Error]+ * line 0, col 0: Error: Expected attribute path, got '['+ *+ * SnipeSCIMConfig::add() and ::replace() now wrap the Parser::parse+ * calls in try/catch and rethrow as SCIMException, so the client sees+ * a 400 pointing at the malformed key instead of an uncaught 500.+ */+ public function test_put_with_malformed_key_returns_400_not_500(): void+ {+ Passport::actingAs(User::factory()->superuser()->create());+ $target = User::factory()->create();++ $response = $this->putJson('/scim/v2/Users/'.$target->id, [+ 'schemas' => ['urn:ietf:params:scim:schemas:core:2.0:User'],+ 'userName' => $target->username,+ // The bad key: a bare value-path filter with no leading+ // attribute name. Reproduces the FilterException-from-parser+ // 500 seen in Rollbar.+ '[type eq "work"]' => '[email protected]',+ ]);++ $response->assertStatus(400);+ }++ public function test_patch_with_malformed_add_value_key_returns_400_not_500(): void+ {+ // Same malformed key shape but arriving through the PATCH add()+ // path (SnipeRootComplex::add()) instead of PUT replace(). Azure+ // and Entra send add/replace ops without a top-level path field+ // and put attribute keys inside `value`, so this exercises the+ // sibling try/catch we added.+ Passport::actingAs(User::factory()->superuser()->create());+ $target = User::factory()->create();++ $response = $this->patchJson('/scim/v2/Users/'.$target->id, [+ 'schemas' => ['urn:ietf:params:scim:api:messages:2.0:PatchOp'],+ 'Operations' => [+ [+ 'op' => 'add',+ 'value' => [+ '[type eq "work"]' => '[email protected]',+ ],+ ],+ ],+ ]);++ $response->assertStatus(400);+ }+}diff --git a/tests/Feature/Scim/UserEmailsShapeTest.php b/tests/Feature/Scim/UserEmailsShapeTest.phpnew file mode 100644index 0000000000..18cebe9497--- /dev/null+++ b/tests/Feature/Scim/UserEmailsShapeTest.php@@ -0,0 +1,78 @@+<?php++namespace Tests\Feature\Scim;++use App\Models\User;+use Laravel\Passport\Passport;+use Tests\TestCase;++/**+ * Regression: `emails` on a SCIM user was serializing as a bare+ * associative object (e.g. `{"value":"...","type":"work","primary":true}`)+ * instead of the JSON array RFC 7643 §4.1.2 mandates for multi-valued+ * attributes. Some SCIM clients treated the scalar shape as reason to+ * construct malformed filter keys against the attribute, which then+ * blew up server-side (see the malformed-key 400 fix in the same PR).+ *+ * SnipeSCIMConfig's `emails` doRead now wraps the object in an outer+ * array so `emails` always serializes as `[{...}]`.+ */+class UserEmailsShapeTest extends TestCase+{+ public function test_emails_is_returned_as_a_json_array_on_get(): void+ {+ Passport::actingAs(User::factory()->superuser()->create());+ $target = User::factory()->create(['email' => '[email protected]']);++ $response = $this->getJson('/scim/v2/Users/'.$target->id);++ $response->assertOk();++ $emails = $response->json('emails');++ $this->assertIsArray($emails, '`emails` must be a JSON array per RFC 7643 §4.1.2');+ $this->assertArrayHasKey(0, $emails, '`emails` must be a list-shaped array, not an associative object');+ $this->assertSame('[email protected]', $emails[0]['value']);+ $this->assertSame('work', $emails[0]['type']);+ $this->assertTrue($emails[0]['primary']);+ }++ public function test_emails_key_is_omitted_when_the_user_has_no_email(): void+ {+ // Guard the "no email → attribute omitted from response" path+ // still holds after the array-wrapping change. Empty array+ // would also be spec-compliant, but the library's Complex::read+ // treats an empty result as "omit the attribute", which is+ // what we want here.+ Passport::actingAs(User::factory()->superuser()->create());+ $target = User::factory()->create(['email' => null]);++ $response = $this->getJson('/scim/v2/Users/'.$target->id);++ $response->assertOk();+ $this->assertArrayNotHasKey('emails', $response->json());+ }++ public function test_emails_shape_is_consistent_across_users_in_list_response(): void+ {+ // Direct reproduction of the ListResponse Snipe pasted from the+ // scim log: multiple users, `emails` on each should be an+ // array. Regression guard against a future one-off doRead+ // returning a bare object when a caller passes an unusual+ // attribute filter.+ Passport::actingAs(User::factory()->superuser()->create());+ User::factory()->count(3)->create();++ $response = $this->getJson('/scim/v2/Users?count=10');++ $response->assertOk();++ foreach ($response->json('Resources') as $resource) {+ if (! array_key_exists('emails', $resource)) {+ continue;+ }+ $this->assertIsArray($resource['emails']);+ $this->assertArrayHasKey(0, $resource['emails']);+ }+ }+}