🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: create outline of SCIM Users support (#6439)
Steffen Schmitzd6eee1687ee0
diff --git a/fern/apis/server/definition/scim.yml b/fern/apis/server/definition/scim.ymlnew file mode 100644index 0000000000..219e6fb88a--- /dev/null+++ b/fern/apis/server/definition/scim.yml@@ -0,0 +1,199 @@+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json+imports:+ commons: ./commons.yml++service:+ auth: true+ base-path: /api/public/scim+ endpoints:+ getServiceProviderConfig:+ docs: Get SCIM Service Provider Configuration (requires organization-scoped API key)+ method: GET+ path: /ServiceProviderConfig+ response: ServiceProviderConfig++ getResourceTypes:+ docs: Get SCIM Resource Types (requires organization-scoped API key)+ method: GET+ path: /ResourceTypes+ response: ResourceTypesResponse++ getSchemas:+ docs: Get SCIM Schemas (requires organization-scoped API key)+ method: GET+ path: /Schemas+ response: SchemasResponse++ listUsers:+ docs: List users in the organization (requires organization-scoped API key)+ method: GET+ path: /Users+ request:+ name: ListUsersRequest+ query-parameters:+ filter:+ docs: Filter expression (e.g. userName eq "value")+ type: optional<string>+ startIndex:+ docs: 1-based index of the first result to return (default 1)+ type: optional<integer>+ count:+ docs: Maximum number of results to return (default 100)+ type: optional<integer>+ response: ScimUsersListResponse++ createUser:+ docs: Create a new user in the organization (requires organization-scoped API key)+ method: POST+ path: /Users+ request:+ name: CreateUserRequest+ body:+ properties:+ userName:+ docs: User's email address (required)+ type: string+ name:+ docs: User's name information+ type: ScimName+ emails:+ docs: User's email addresses+ type: optional<list<ScimEmail>>+ active:+ docs: Whether the user is active+ type: optional<boolean>+ password:+ docs: Initial password for the user+ type: optional<string>+ response: ScimUser++ getUser:+ docs: Get a specific user by ID (requires organization-scoped API key)+ method: GET+ path: /Users/{userId}+ path-parameters:+ userId: string+ response: ScimUser++ deleteUser:+ docs: Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself.+ method: DELETE+ path: /Users/{userId}+ path-parameters:+ userId: string+ response: EmptyResponse++types:+ ServiceProviderConfig:+ properties:+ schemas: list<string>+ documentationUri: string+ patch: ScimFeatureSupport+ bulk: BulkConfig+ filter: FilterConfig+ changePassword: ScimFeatureSupport+ sort: ScimFeatureSupport+ etag: ScimFeatureSupport+ authenticationSchemes: list<AuthenticationScheme>+ meta: ResourceMeta++ ScimFeatureSupport:+ properties:+ supported: boolean++ BulkConfig:+ properties:+ supported: boolean+ maxOperations: integer+ maxPayloadSize: integer++ FilterConfig:+ properties:+ supported: boolean+ maxResults: integer++ ResourceMeta:+ properties:+ resourceType: string+ location: string++ AuthenticationScheme:+ properties:+ name: string+ description: string+ specUri: string+ type: string+ primary: boolean++ ResourceTypesResponse:+ properties:+ schemas: list<string>+ totalResults: integer+ Resources: list<ResourceType>++ ResourceType:+ properties:+ schemas: optional<list<string>>+ id: string+ name: string+ endpoint: string+ description: string+ schema: string+ schemaExtensions: list<SchemaExtension>+ meta: ResourceMeta++ SchemaExtension:+ properties:+ schema: string+ required: boolean++ SchemasResponse:+ properties:+ schemas: list<string>+ totalResults: integer+ Resources: list<SchemaResource>++ SchemaResource:+ properties:+ id: string+ name: string+ description: string+ attributes: list<unknown>+ meta: ResourceMeta++ ScimUsersListResponse:+ properties:+ schemas: list<string>+ totalResults: integer+ startIndex: integer+ itemsPerPage: integer+ Resources: list<ScimUser>++ ScimUser:+ properties:+ schemas: list<string>+ id: string+ userName: string+ name: ScimName+ emails: list<ScimEmail>+ meta: UserMeta++ UserMeta:+ properties:+ resourceType: string+ created: optional<string>+ lastModified: optional<string>++ ScimName:+ properties:+ formatted: optional<string>++ ScimEmail:+ properties:+ primary: boolean+ value: string+ type: string++ EmptyResponse:+ docs: Empty response for 204 No Content responses+ properties: {}\ No newline at end of filediff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex f413c4c93b..12c44f08d4 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -2385,6 +2385,359 @@ paths:application/json:schema:$ref: '#/components/schemas/CreatePromptRequest'+ /api/public/scim/ServiceProviderConfig:+ get:+ description: >-+ Get SCIM Service Provider Configuration (requires organization-scoped+ API key)+ operationId: scim_getServiceProviderConfig+ tags:+ - Scim+ parameters: []+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ServiceProviderConfig'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []+ /api/public/scim/ResourceTypes:+ get:+ description: Get SCIM Resource Types (requires organization-scoped API key)+ operationId: scim_getResourceTypes+ tags:+ - Scim+ parameters: []+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ResourceTypesResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []+ /api/public/scim/Schemas:+ get:+ description: Get SCIM Schemas (requires organization-scoped API key)+ operationId: scim_getSchemas+ tags:+ - Scim+ parameters: []+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SchemasResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []+ /api/public/scim/Users:+ get:+ description: List users in the organization (requires organization-scoped API key)+ operationId: scim_listUsers+ tags:+ - Scim+ parameters:+ - name: filter+ in: query+ description: Filter expression (e.g. userName eq "value")+ required: false+ schema:+ type: string+ nullable: true+ - name: startIndex+ in: query+ description: 1-based index of the first result to return (default 1)+ required: false+ schema:+ type: integer+ nullable: true+ - name: count+ in: query+ description: Maximum number of results to return (default 100)+ required: false+ schema:+ type: integer+ nullable: true+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ScimUsersListResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []+ post:+ description: >-+ Create a new user in the organization (requires organization-scoped API+ key)+ operationId: scim_createUser+ tags:+ - Scim+ parameters: []+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ScimUser'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ userName:+ type: string+ description: User's email address (required)+ name:+ $ref: '#/components/schemas/ScimName'+ description: User's name information+ emails:+ type: array+ items:+ $ref: '#/components/schemas/ScimEmail'+ nullable: true+ description: User's email addresses+ active:+ type: boolean+ nullable: true+ description: Whether the user is active+ password:+ type: string+ nullable: true+ description: Initial password for the user+ required:+ - userName+ - name+ /api/public/scim/Users/{userId}:+ get:+ description: Get a specific user by ID (requires organization-scoped API key)+ operationId: scim_getUser+ tags:+ - Scim+ parameters:+ - name: userId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ScimUser'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []+ delete:+ description: >-+ Remove a user from the organization (requires organization-scoped API+ key). Note that this only removes the user from the organization but+ does not delete the user entity itself.+ operationId: scim_deleteUser+ tags:+ - Scim+ parameters:+ - name: userId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/EmptyResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []/api/public/score-configs:post:description: >-@@ -5705,6 +6058,301 @@ components:- promptallOf:- $ref: '#/components/schemas/BasePrompt'+ ServiceProviderConfig:+ title: ServiceProviderConfig+ type: object+ properties:+ schemas:+ type: array+ items:+ type: string+ documentationUri:+ type: string+ patch:+ $ref: '#/components/schemas/ScimFeatureSupport'+ bulk:+ $ref: '#/components/schemas/BulkConfig'+ filter:+ $ref: '#/components/schemas/FilterConfig'+ changePassword:+ $ref: '#/components/schemas/ScimFeatureSupport'+ sort:+ $ref: '#/components/schemas/ScimFeatureSupport'+ etag:+ $ref: '#/components/schemas/ScimFeatureSupport'+ authenticationSchemes:+ type: array+ items:+ $ref: '#/components/schemas/AuthenticationScheme'+ meta:+ $ref: '#/components/schemas/ResourceMeta'+ required:+ - schemas+ - documentationUri+ - patch+ - bulk+ - filter+ - changePassword+ - sort+ - etag+ - authenticationSchemes+ - meta+ ScimFeatureSupport:+ title: ScimFeatureSupport+ type: object+ properties:+ supported:+ type: boolean+ required:+ - supported+ BulkConfig:+ title: BulkConfig+ type: object+ properties:+ supported:+ type: boolean+ maxOperations:+ type: integer+ maxPayloadSize:+ type: integer+ required:+ - supported+ - maxOperations+ - maxPayloadSize+ FilterConfig:+ title: FilterConfig+ type: object+ properties:+ supported:+ type: boolean+ maxResults:+ type: integer+ required:+ - supported+ - maxResults+ ResourceMeta:+ title: ResourceMeta+ type: object+ properties:+ resourceType:+ type: string+ location:+ type: string+ required:+ - resourceType+ - location+ AuthenticationScheme:+ title: AuthenticationScheme+ type: object+ properties:+ name:+ type: string+ description:+ type: string+ specUri:+ type: string+ type:+ type: string+ primary:+ type: boolean+ required:+ - name+ - description+ - specUri+ - type+ - primary+ ResourceTypesResponse:+ title: ResourceTypesResponse+ type: object+ properties:+ schemas:+ type: array+ items:+ type: string+ totalResults:+ type: integer+ Resources:+ type: array+ items:+ $ref: '#/components/schemas/ResourceType'+ required:+ - schemas+ - totalResults+ - Resources+ ResourceType:+ title: ResourceType+ type: object+ properties:+ schemas:+ type: array+ items:+ type: string+ nullable: true+ id:+ type: string+ name:+ type: string+ endpoint:+ type: string+ description:+ type: string+ schema:+ type: string+ schemaExtensions:+ type: array+ items:+ $ref: '#/components/schemas/SchemaExtension'+ meta:+ $ref: '#/components/schemas/ResourceMeta'+ required:+ - id+ - name+ - endpoint+ - description+ - schema+ - schemaExtensions+ - meta+ SchemaExtension:+ title: SchemaExtension+ type: object+ properties:+ schema:+ type: string+ required:+ type: boolean+ required:+ - schema+ - required+ SchemasResponse:+ title: SchemasResponse+ type: object+ properties:+ schemas:+ type: array+ items:+ type: string+ totalResults:+ type: integer+ Resources:+ type: array+ items:+ $ref: '#/components/schemas/SchemaResource'+ required:+ - schemas+ - totalResults+ - Resources+ SchemaResource:+ title: SchemaResource+ type: object+ properties:+ id:+ type: string+ name:+ type: string+ description:+ type: string+ attributes:+ type: array+ items: {}+ meta:+ $ref: '#/components/schemas/ResourceMeta'+ required:+ - id+ - name+ - description+ - attributes+ - meta+ ScimUsersListResponse:+ title: ScimUsersListResponse+ type: object+ properties:+ schemas:+ type: array+ items:+ type: string+ totalResults:+ type: integer+ startIndex:+ type: integer+ itemsPerPage:+ type: integer+ Resources:+ type: array+ items:+ $ref: '#/components/schemas/ScimUser'+ required:+ - schemas+ - totalResults+ - startIndex+ - itemsPerPage+ - Resources+ ScimUser:+ title: ScimUser+ type: object+ properties:+ schemas:+ type: array+ items:+ type: string+ id:+ type: string+ userName:+ type: string+ name:+ $ref: '#/components/schemas/ScimName'+ emails:+ type: array+ items:+ $ref: '#/components/schemas/ScimEmail'+ meta:+ $ref: '#/components/schemas/UserMeta'+ required:+ - schemas+ - id+ - userName+ - name+ - emails+ - meta+ UserMeta:+ title: UserMeta+ type: object+ properties:+ resourceType:+ type: string+ created:+ type: string+ nullable: true+ lastModified:+ type: string+ nullable: true+ required:+ - resourceType+ ScimName:+ title: ScimName+ type: object+ properties:+ formatted:+ type: string+ nullable: true+ ScimEmail:+ title: ScimEmail+ type: object+ properties:+ primary:+ type: boolean+ value:+ type: string+ type:+ type: string+ required:+ - primary+ - value+ - type+ EmptyResponse:+ title: EmptyResponse+ type: object+ description: Empty response for 204 No Content responses+ properties: {}ScoreConfigs:title: ScoreConfigstype: objectdiff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.jsonindex bb52619a2f..cb184995ef 100644--- a/web/public/generated/postman/collection.json+++ b/web/public/generated/postman/collection.json@@ -1828,6 +1828,233 @@}]},+ {+ "_type": "container",+ "description": null,+ "name": "Scim",+ "item": [+ {+ "_type": "endpoint",+ "name": "Get Service Provider Config",+ "request": {+ "description": "Get SCIM Service Provider Configuration (requires organization-scoped API key)",+ "url": {+ "raw": "{{baseUrl}}/api/public/scim/ServiceProviderConfig",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "scim",+ "ServiceProviderConfig"+ ],+ "query": [],+ "variable": []+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Get Resource Types",+ "request": {+ "description": "Get SCIM Resource Types (requires organization-scoped API key)",+ "url": {+ "raw": "{{baseUrl}}/api/public/scim/ResourceTypes",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "scim",+ "ResourceTypes"+ ],+ "query": [],+ "variable": []+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Get Schemas",+ "request": {+ "description": "Get SCIM Schemas (requires organization-scoped API key)",+ "url": {+ "raw": "{{baseUrl}}/api/public/scim/Schemas",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "scim",+ "Schemas"+ ],+ "query": [],+ "variable": []+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "List Users",+ "request": {+ "description": "List users in the organization (requires organization-scoped API key)",+ "url": {+ "raw": "{{baseUrl}}/api/public/scim/Users?filter=&startIndex=&count=",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "scim",+ "Users"+ ],+ "query": [+ {+ "key": "filter",+ "value": "",+ "description": "Filter expression (e.g. userName eq \"value\")"+ },+ {+ "key": "startIndex",+ "value": "",+ "description": "1-based index of the first result to return (default 1)"+ },+ {+ "key": "count",+ "value": "",+ "description": "Maximum number of results to return (default 100)"+ }+ ],+ "variable": []+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Create User",+ "request": {+ "description": "Create a new user in the organization (requires organization-scoped API key)",+ "url": {+ "raw": "{{baseUrl}}/api/public/scim/Users",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "scim",+ "Users"+ ],+ "query": [],+ "variable": []+ },+ "header": [],+ "method": "POST",+ "auth": null,+ "body": {+ "mode": "raw",+ "raw": "{\n \"userName\": \"example\",\n \"name\": {\n \"formatted\": \"example\"\n },\n \"emails\": [\n {\n \"primary\": true,\n \"value\": \"example\",\n \"type\": \"example\"\n }\n ],\n \"active\": true,\n \"password\": \"example\"\n}",+ "options": {+ "raw": {+ "language": "json"+ }+ }+ }+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Get User",+ "request": {+ "description": "Get a specific user by ID (requires organization-scoped API key)",+ "url": {+ "raw": "{{baseUrl}}/api/public/scim/Users/:userId",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "scim",+ "Users",+ ":userId"+ ],+ "query": [],+ "variable": [+ {+ "key": "userId",+ "value": "",+ "description": null+ }+ ]+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Delete User",+ "request": {+ "description": "Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself.",+ "url": {+ "raw": "{{baseUrl}}/api/public/scim/Users/:userId",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "scim",+ "Users",+ ":userId"+ ],+ "query": [],+ "variable": [+ {+ "key": "userId",+ "value": "",+ "description": null+ }+ ]+ },+ "header": [],+ "method": "DELETE",+ "auth": null,+ "body": null+ },+ "response": []+ }+ ]+ },{"_type": "container","description": null,diff --git a/web/src/__tests__/async/scim-api.servertest.ts b/web/src/__tests__/async/scim-api.servertest.tsnew file mode 100644index 0000000000..870cadc350--- /dev/null+++ b/web/src/__tests__/async/scim-api.servertest.ts@@ -0,0 +1,671 @@+/** @jest-environment node */++import {+ makeZodVerifiedAPICall,+ makeAPICall,+} from "@/src/__tests__/test-utils";+import { z } from "zod";+import {+ createAndAddApiKeysToDb,+ createBasicAuthHeader,+} from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";+import { randomUUID } from "crypto";+import { verifyPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";++// Schema for SCIM User response+const ScimUserSchema = z.object({+ schemas: z.array(z.string()),+ id: z.string(),+ userName: z.string(),+ name: z.object({+ formatted: z.string().nullable(),+ }),+ emails: z.array(+ z.object({+ primary: z.boolean(),+ value: z.string(),+ type: z.string(),+ }),+ ),+ meta: z.object({+ resourceType: z.string(),+ created: z.string().optional(),+ lastModified: z.string().optional(),+ }),+});++// Schema for SCIM Users list response+const ScimUsersListSchema = z.object({+ schemas: z.array(z.string()),+ totalResults: z.number(),+ startIndex: z.number(),+ itemsPerPage: z.number(),+ Resources: z.array(ScimUserSchema),+});++// Schema for SCIM Service Provider Config response+const ServiceProviderConfigSchema = z.object({+ schemas: z.array(z.string()),+ documentationUri: z.string(),+ patch: z.object({+ supported: z.boolean(),+ }),+ bulk: z.object({+ supported: z.boolean(),+ maxOperations: z.number(),+ maxPayloadSize: z.number(),+ }),+ filter: z.object({+ supported: z.boolean(),+ maxResults: z.number(),+ }),+ changePassword: z.object({+ supported: z.boolean(),+ }),+ sort: z.object({+ supported: z.boolean(),+ }),+ etag: z.object({+ supported: z.boolean(),+ }),+ authenticationSchemes: z.array(+ z.object({+ name: z.string(),+ description: z.string(),+ specUri: z.string(),+ type: z.string(),+ primary: z.boolean(),+ }),+ ),+ meta: z.object({+ resourceType: z.string(),+ location: z.string(),+ }),+});++// Schema for SCIM Schemas response+const SchemasResponseSchema = z.object({+ schemas: z.array(z.string()),+ totalResults: z.number(),+ Resources: z.array(+ z.object({+ id: z.string(),+ name: z.string(),+ description: z.string(),+ attributes: z.array(z.any()),+ meta: z.object({+ resourceType: z.string(),+ location: z.string(),+ }),+ }),+ ),+});++// Schema for SCIM Resource Types response+const ResourceTypesResponseSchema = z.object({+ schemas: z.array(z.string()),+ totalResults: z.number(),+ Resources: z.array(+ z.object({+ schemas: z.array(z.string()),+ id: z.string(),+ name: z.string(),+ endpoint: z.string(),+ description: z.string(),+ schema: z.string(),+ schemaExtensions: z.array(+ z.object({+ schema: z.string(),+ required: z.boolean(),+ }),+ ),+ meta: z.object({+ resourceType: z.string(),+ location: z.string(),+ }),+ }),+ ),+});++describe("SCIM API", () => {+ // Test variables+ const orgId = "seed-org-id";+ const orgApiKey = `pk-lf-org-${randomUUID().substring(0, 8)}`;+ const orgSecretKey = `sk-lf-org-${randomUUID().substring(0, 8)}`;+ const projectApiKey = "pk-lf-1234567890";+ const projectSecretKey = "sk-lf-1234567890";+ const invalidApiKey = "pk-lf-invalid";+ const invalidSecretKey = "sk-lf-invalid";+ let testUserId: string;++ beforeAll(async () => {+ await createAndAddApiKeysToDb({+ prisma,+ entityId: orgId,+ scope: "ORGANIZATION",+ predefinedKeys: {+ publicKey: orgApiKey,+ secretKey: orgSecretKey,+ },+ });+ });++ describe("GET /api/public/scim/ServiceProviderConfig", () => {+ it("should return service provider configuration with valid organization API key", async () => {+ const response = await makeZodVerifiedAPICall(+ ServiceProviderConfigSchema,+ "GET",+ "/api/public/scim/ServiceProviderConfig",+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body.schemas).toContain(+ "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig",+ );+ expect(response.body.patch.supported).toBe(false);+ expect(response.body.filter.supported).toBe(true);+ });++ it("should return 401 when invalid API keys are provided", async () => {+ const result = await makeAPICall(+ "GET",+ "/api/public/scim/ServiceProviderConfig",+ undefined,+ createBasicAuthHeader(invalidApiKey, invalidSecretKey),+ );+ expect(result.status).toBe(401);+ expect(result.body.detail).toBeDefined();+ });++ it("should return 403 when using project API key instead of organization API key", async () => {+ const result = await makeAPICall(+ "GET",+ "/api/public/scim/ServiceProviderConfig",+ undefined,+ createBasicAuthHeader(projectApiKey, projectSecretKey),+ );+ expect(result.status).toBe(403);+ expect(result.body.detail).toContain(+ "Organization-scoped API key required",+ );+ });++ it("should return 405 for non-GET methods", async () => {+ const result = await makeAPICall(+ "POST",+ "/api/public/scim/ServiceProviderConfig",+ {},+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(405);+ expect(result.body.detail).toContain("Method not allowed");+ });+ });++ describe("GET /api/public/scim/Schemas", () => {+ it("should return schemas with valid organization API key", async () => {+ const response = await makeZodVerifiedAPICall(+ SchemasResponseSchema,+ "GET",+ "/api/public/scim/Schemas",+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body.schemas).toContain(+ "urn:ietf:params:scim:api:messages:2.0:ListResponse",+ );+ expect(response.body.Resources.length).toBeGreaterThan(0);+ expect(response.body.Resources[0].id).toContain(+ "urn:ietf:params:scim:schemas:core:2.0:User",+ );+ });++ it("should return 401 when invalid API keys are provided", async () => {+ const result = await makeAPICall(+ "GET",+ "/api/public/scim/Schemas",+ undefined,+ createBasicAuthHeader(invalidApiKey, invalidSecretKey),+ );+ expect(result.status).toBe(401);+ expect(result.body.detail).toBeDefined();+ });++ it("should return 403 when using project API key instead of organization API key", async () => {+ const result = await makeAPICall(+ "GET",+ "/api/public/scim/Schemas",+ undefined,+ createBasicAuthHeader(projectApiKey, projectSecretKey),+ );+ expect(result.status).toBe(403);+ expect(result.body.detail).toContain(+ "Organization-scoped API key required",+ );+ });++ it("should return 405 for non-GET methods", async () => {+ const result = await makeAPICall(+ "POST",+ "/api/public/scim/Schemas",+ {},+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(405);+ expect(result.body.detail).toContain("Method not allowed");+ });+ });++ describe("GET /api/public/scim/ResourceTypes", () => {+ it("should return resource types with valid organization API key", async () => {+ const response = await makeZodVerifiedAPICall(+ ResourceTypesResponseSchema,+ "GET",+ "/api/public/scim/ResourceTypes",+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body.schemas).toContain(+ "urn:ietf:params:scim:api:messages:2.0:ListResponse",+ );+ expect(response.body.Resources.length).toBeGreaterThan(0);+ expect(response.body.Resources[0].id).toBe("User");+ expect(response.body.Resources[0].endpoint).toBe(+ "/api/public/scim/Users",+ );+ });++ it("should return 401 when invalid API keys are provided", async () => {+ const result = await makeAPICall(+ "GET",+ "/api/public/scim/ResourceTypes",+ undefined,+ createBasicAuthHeader(invalidApiKey, invalidSecretKey),+ );+ expect(result.status).toBe(401);+ expect(result.body.detail).toBeDefined();+ });++ it("should return 403 when using project API key instead of organization API key", async () => {+ const result = await makeAPICall(+ "GET",+ "/api/public/scim/ResourceTypes",+ undefined,+ createBasicAuthHeader(projectApiKey, projectSecretKey),+ );+ expect(result.status).toBe(403);+ expect(result.body.detail).toContain(+ "Organization-scoped API key required",+ );+ });++ it("should return 405 for non-GET methods", async () => {+ const result = await makeAPICall(+ "POST",+ "/api/public/scim/ResourceTypes",+ {},+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(405);+ expect(result.body.detail).toContain("Method not allowed");+ });+ });++ describe("SCIM Users API", () => {+ // Clean up test users after each test+ afterEach(async () => {+ if (testUserId) {+ await prisma.user.deleteMany({+ where: {+ id: testUserId,+ },+ });+ testUserId = "";+ }+ });++ describe("GET /api/public/scim/Users", () => {+ it("should return users with valid organization API key", async () => {+ const response = await makeZodVerifiedAPICall(+ ScimUsersListSchema,+ "GET",+ "/api/public/scim/Users",+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body.schemas).toContain(+ "urn:ietf:params:scim:api:messages:2.0:ListResponse",+ );+ expect(response.body.totalResults).toBeGreaterThanOrEqual(0);+ expect(response.body.startIndex).toBe(1);+ });++ it("should support filtering by userName", async () => {+ // First create a test user+ const uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;+ const createResponse = await makeAPICall(+ "POST",+ "/api/public/scim/Users",+ {+ userName: uniqueEmail,+ name: {+ formatted: "Test User",+ },+ emails: [+ {+ primary: true,+ value: uniqueEmail,+ type: "work",+ },+ ],+ active: true,+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );++ expect(createResponse.status).toBe(201);+ testUserId = createResponse.body.id;++ // Now filter for this user+ const response = await makeZodVerifiedAPICall(+ ScimUsersListSchema,+ "GET",+ `/api/public/scim/Users?filter=userName eq "${uniqueEmail}"`,+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body.totalResults).toBe(1);+ expect(response.body.Resources[0].userName).toBe(uniqueEmail);+ });++ it("should return 401 when invalid API keys are provided", async () => {+ const result = await makeAPICall(+ "GET",+ "/api/public/scim/Users",+ undefined,+ createBasicAuthHeader(invalidApiKey, invalidSecretKey),+ );+ expect(result.status).toBe(401);+ expect(result.body.detail).toBeDefined();+ });++ it("should return 403 when using project API key instead of organization API key", async () => {+ const result = await makeAPICall(+ "GET",+ "/api/public/scim/Users",+ undefined,+ createBasicAuthHeader(projectApiKey, projectSecretKey),+ );+ expect(result.status).toBe(403);+ expect(result.body.detail).toContain(+ "Organization-scoped API key required",+ );+ });++ it("should return 405 for non-GET/POST methods", async () => {+ const result = await makeAPICall(+ "PUT",+ "/api/public/scim/Users",+ {},+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(405);+ expect(result.body.detail).toContain("Method not allowed");+ });+ });++ describe("POST /api/public/scim/Users", () => {+ it("should create a new user with valid organization API key", async () => {+ const uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;+ const response = await makeZodVerifiedAPICall(+ ScimUserSchema,+ "POST",+ "/api/public/scim/Users",+ {+ userName: uniqueEmail,+ name: {+ formatted: "Test User",+ },+ emails: [+ {+ primary: true,+ value: uniqueEmail,+ type: "work",+ },+ ],+ active: true,+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 201,+ );++ expect(response.status).toBe(201);+ expect(response.body.userName).toBe(uniqueEmail);+ expect(response.body.name.formatted).toBe("Test User");+ expect(response.body.emails[0].value).toBe(uniqueEmail);++ testUserId = response.body.id;++ // Verify the user was actually created in the database+ const user = await prisma.user.findUnique({+ where: { id: testUserId },+ });+ expect(user).not.toBeNull();+ expect(user?.email).toBe(uniqueEmail);+ expect(user?.name).toBe("Test User");+ });++ it("should create a new user with password", async () => {+ const uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;+ const password = `password-${randomUUID().substring(0, 8)}`;+ const response = await makeZodVerifiedAPICall(+ ScimUserSchema,+ "POST",+ "/api/public/scim/Users",+ {+ userName: uniqueEmail,+ name: {+ formatted: "Test User With Password",+ },+ emails: [+ {+ primary: true,+ value: uniqueEmail,+ type: "work",+ },+ ],+ active: true,+ password: password,+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 201,+ );++ expect(response.status).toBe(201);+ expect(response.body.userName).toBe(uniqueEmail);+ expect(response.body.name.formatted).toBe("Test User With Password");+ expect(response.body.emails[0].value).toBe(uniqueEmail);+ // Password should not be returned in the response+ expect(response.body.password).toBeUndefined();++ testUserId = response.body.id;++ // Verify the user was actually created in the database+ const user = await prisma.user.findUnique({+ where: { id: testUserId },+ });+ expect(user).not.toBeNull();+ expect(user?.email).toBe(uniqueEmail);+ expect(user?.name).toBe("Test User With Password");+ // Verify password was created+ expect(user?.password).not.toBeNull();+ expect(await verifyPassword(password, user?.password ?? "")).toBe(true);+ });++ it("should return 400 when userName is missing", async () => {+ const result = await makeAPICall(+ "POST",+ "/api/public/scim/Users",+ {+ name: {+ formatted: "Test User",+ },+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(400);+ expect(result.body.detail).toContain("userName is required");+ });++ it("should return 409 when user with the same userName already exists", async () => {+ const uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;++ // First create a user+ const createResponse = await makeAPICall(+ "POST",+ "/api/public/scim/Users",+ {+ userName: uniqueEmail,+ name: {+ formatted: "Test User",+ },+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(createResponse.status).toBe(201);+ testUserId = createResponse.body.id;++ // Try to create another user with the same userName+ const duplicateResult = await makeAPICall(+ "POST",+ "/api/public/scim/Users",+ {+ userName: uniqueEmail,+ name: {+ formatted: "Another User",+ },+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(duplicateResult.status).toBe(409);+ expect(duplicateResult.body.detail).toContain("already exists");+ });+ });++ describe("GET /api/public/scim/Users/{id}", () => {+ beforeEach(async () => {+ // Create a test user+ const uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;+ const user = await prisma.user.create({+ data: {+ email: uniqueEmail,+ name: "Test User",+ },+ });+ await prisma.organizationMembership.create({+ data: {+ userId: user.id,+ orgId: orgId,+ role: "NONE",+ },+ });++ testUserId = user.id;+ });++ it("should return a specific user with valid organization API key", async () => {+ const response = await makeZodVerifiedAPICall(+ ScimUserSchema,+ "GET",+ `/api/public/scim/Users/${testUserId}`,+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body.id).toBe(testUserId);+ expect(response.body.name.formatted).toBe("Test User");+ });++ it("should return 404 when user does not exist", async () => {+ const nonExistentUserId = randomUUID();+ const result = await makeAPICall(+ "GET",+ `/api/public/scim/Users/${nonExistentUserId}`,+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(404);+ expect(result.body.detail).toContain("User not found");+ });+ });++ describe("DELETE /api/public/scim/Users/{id}", () => {+ beforeEach(async () => {+ // Create a test user+ const uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;+ const user = await prisma.user.create({+ data: {+ email: uniqueEmail,+ name: "Test User",+ },+ });+ await prisma.organizationMembership.create({+ data: {+ userId: user.id,+ orgId: orgId,+ role: "NONE",+ },+ });+ testUserId = user.id;+ });++ it("should delete a user with valid organization API key", async () => {+ try {+ await makeAPICall(+ "DELETE",+ `/api/public/scim/Users/${testUserId}`,+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ } catch (e) {+ // ignore+ }++ const orgMemberships = await prisma.organizationMembership.findMany({+ where: { id: testUserId },+ });+ expect(orgMemberships.length).toBe(0);+ });++ it("should return 404 when user does not exist", async () => {+ const nonExistentUserId = randomUUID();+ const result = await makeAPICall(+ "DELETE",+ `/api/public/scim/Users/${nonExistentUserId}`,+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(404);+ expect(result.body.detail).toContain("User not found");+ });+ });+ });+});diff --git a/web/src/pages/api/public/scim/ResourceTypes.ts b/web/src/pages/api/public/scim/ResourceTypes.tsnew file mode 100644index 0000000000..1f7b24e322--- /dev/null+++ b/web/src/pages/api/public/scim/ResourceTypes.ts@@ -0,0 +1,72 @@+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";++import { type NextApiRequest, type NextApiResponse } from "next";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ await runMiddleware(req, res, cors);++ if (req.method !== "GET") {+ logger.error(+ `Method not allowed for ${req.method} on /api/public/scim/ResourceTypes`,+ );+ return res.status(405).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "Method not allowed",+ status: 405,+ });+ }++ // CHECK AUTH+ const authCheck = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);+ if (!authCheck.validKey) {+ return res.status(401).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: authCheck.error,+ status: 401,+ });+ }+ // END CHECK AUTH++ // Check if using an organization API key+ if (+ authCheck.scope.accessLevel !== "organization" ||+ !authCheck.scope.orgId+ ) {+ return res.status(403).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail:+ "Invalid API key. Organization-scoped API key required for this operation.",+ status: 403,+ });+ }++ // Return the resource types+ return res.status(200).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],+ totalResults: 1,+ Resources: [+ {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:ResourceType"],+ id: "User",+ name: "User",+ endpoint: "/api/public/scim/Users",+ description: "User Account",+ schema: "urn:ietf:params:scim:schemas:core:2.0:User",+ schemaExtensions: [],+ meta: {+ resourceType: "ResourceType",+ location: "/api/public/scim/ResourceTypes/User",+ },+ },+ ],+ });+}diff --git a/web/src/pages/api/public/scim/Schemas.ts b/web/src/pages/api/public/scim/Schemas.tsnew file mode 100644index 0000000000..fc69dbff69--- /dev/null+++ b/web/src/pages/api/public/scim/Schemas.ts@@ -0,0 +1,216 @@+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";++import { type NextApiRequest, type NextApiResponse } from "next";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ await runMiddleware(req, res, cors);++ if (req.method !== "GET") {+ logger.error(+ `Method not allowed for ${req.method} on /api/public/scim/Schemas`,+ );+ return res.status(405).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "Method not allowed",+ status: 405,+ });+ }++ // CHECK AUTH+ const authCheck = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);+ if (!authCheck.validKey) {+ return res.status(401).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: authCheck.error,+ status: 401,+ });+ }+ // END CHECK AUTH++ // Check if using an organization API key+ if (+ authCheck.scope.accessLevel !== "organization" ||+ !authCheck.scope.orgId+ ) {+ return res.status(403).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail:+ "Invalid API key. Organization-scoped API key required for this operation.",+ status: 403,+ });+ }++ // Return the schemas+ return res.status(200).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],+ totalResults: 2,+ Resources: [+ // User Schema+ {+ id: "urn:ietf:params:scim:schemas:core:2.0:User",+ name: "User",+ description: "User Account",+ attributes: [+ {+ name: "id",+ type: "string",+ multiValued: false,+ description: "Unique identifier for the User",+ required: true,+ caseExact: true,+ mutability: "readOnly",+ returned: "always",+ uniqueness: "server",+ },+ {+ name: "userName",+ type: "string",+ multiValued: false,+ description:+ "Unique identifier for the User, typically the email address",+ required: true,+ caseExact: false,+ mutability: "readWrite",+ returned: "always",+ uniqueness: "server",+ },+ {+ name: "name",+ type: "complex",+ multiValued: false,+ description: "The components of the user's name",+ required: false,+ subAttributes: [+ {+ name: "formatted",+ type: "string",+ multiValued: false,+ description: "The user's full name",+ required: false,+ caseExact: false,+ mutability: "readWrite",+ returned: "default",+ uniqueness: "none",+ },+ ],+ mutability: "readWrite",+ returned: "default",+ uniqueness: "none",+ },+ {+ name: "emails",+ type: "complex",+ multiValued: true,+ description: "Email addresses for the user",+ required: false,+ subAttributes: [+ {+ name: "value",+ type: "string",+ multiValued: false,+ description: "Email address value",+ required: false,+ caseExact: false,+ mutability: "readWrite",+ returned: "default",+ uniqueness: "none",+ },+ {+ name: "primary",+ type: "boolean",+ multiValued: false,+ description: "Primary email indicator",+ required: false,+ mutability: "readWrite",+ returned: "default",+ uniqueness: "none",+ },+ {+ name: "type",+ type: "string",+ multiValued: false,+ description: "Email type (work, home, other)",+ required: false,+ caseExact: false,+ mutability: "readWrite",+ returned: "default",+ uniqueness: "none",+ },+ ],+ mutability: "readWrite",+ returned: "default",+ uniqueness: "none",+ },+ {+ name: "password",+ type: "string",+ multiValued: false,+ description: "The user's password",+ required: false,+ caseExact: false,+ mutability: "writeOnly",+ returned: "never",+ uniqueness: "none",+ },+ {+ name: "meta",+ type: "complex",+ multiValued: false,+ description: "Resource metadata",+ required: false,+ subAttributes: [+ {+ name: "resourceType",+ type: "string",+ multiValued: false,+ description: "The resource type",+ required: false,+ caseExact: true,+ mutability: "readOnly",+ returned: "default",+ uniqueness: "none",+ },+ {+ name: "created",+ type: "dateTime",+ multiValued: false,+ description: "The resource creation time",+ required: false,+ mutability: "readOnly",+ returned: "default",+ uniqueness: "none",+ },+ {+ name: "lastModified",+ type: "dateTime",+ multiValued: false,+ description: "The resource last modification time",+ required: false,+ mutability: "readOnly",+ returned: "default",+ uniqueness: "none",+ },+ ],+ mutability: "readOnly",+ returned: "default",+ uniqueness: "none",+ },+ ],+ meta: {+ resourceType: "Schema",+ location:+ "/api/public/scim/Schemas/urn:ietf:params:scim:schemas:core:2.0:User",+ },+ },+ ],+ });+}diff --git a/web/src/pages/api/public/scim/ServiceProviderConfig.ts b/web/src/pages/api/public/scim/ServiceProviderConfig.tsnew file mode 100644index 0000000000..eb1b98daf3--- /dev/null+++ b/web/src/pages/api/public/scim/ServiceProviderConfig.ts@@ -0,0 +1,91 @@+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";++import { type NextApiRequest, type NextApiResponse } from "next";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ await runMiddleware(req, res, cors);++ if (req.method !== "GET") {+ logger.error(+ `Method not allowed for ${req.method} on /api/public/scim/ServiceProviderConfig`,+ );+ return res.status(405).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "Method not allowed",+ status: 405,+ });+ }++ // CHECK AUTH+ const authCheck = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);+ if (!authCheck.validKey) {+ return res.status(401).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: authCheck.error,+ status: 401,+ });+ }+ // END CHECK AUTH++ // Check if using an organization API key+ if (+ authCheck.scope.accessLevel !== "organization" ||+ !authCheck.scope.orgId+ ) {+ return res.status(403).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail:+ "Invalid API key. Organization-scoped API key required for this operation.",+ status: 403,+ });+ }++ // Return the service provider configuration+ return res.status(200).json({+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"],+ documentationUri: "https://docs.langfuse.com/scim",+ patch: {+ supported: false,+ },+ bulk: {+ supported: false,+ maxOperations: 0,+ maxPayloadSize: 0,+ },+ filter: {+ supported: true,+ maxResults: 100,+ },+ changePassword: {+ supported: false,+ },+ sort: {+ supported: false,+ },+ etag: {+ supported: false,+ },+ authenticationSchemes: [+ {+ name: "Basic Authentication",+ description: "Authentication via HTTP Basic Auth",+ specUri: "https://tools.ietf.org/html/rfc2617",+ type: "httpbasic",+ primary: true,+ },+ ],+ meta: {+ resourceType: "ServiceProviderConfig",+ location: "/api/public/scim/ServiceProviderConfig",+ },+ });+}diff --git a/web/src/pages/api/public/scim/Users/[id].ts b/web/src/pages/api/public/scim/Users/[id].tsnew file mode 100644index 0000000000..c3e2f5930b--- /dev/null+++ b/web/src/pages/api/public/scim/Users/[id].ts@@ -0,0 +1,153 @@+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";+import { prisma } from "@langfuse/shared/src/db";+import { type User } from "@langfuse/shared";+import { logger, redis } from "@langfuse/shared/src/server";++import { type NextApiRequest, type NextApiResponse } from "next";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ await runMiddleware(req, res, cors);++ if (!["GET", "DELETE"].includes(req.method || "")) {+ logger.error(+ `Method not allowed for ${req.method} on /api/public/scim/Users/[id]`,+ );+ return res.status(405).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "Method not allowed",+ status: 405,+ });+ }++ // CHECK AUTH+ const authCheck = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);+ if (!authCheck.validKey) {+ return res.status(401).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: authCheck.error,+ status: 401,+ });+ }+ // END CHECK AUTH++ // Check if using an organization API key+ if (+ authCheck.scope.accessLevel !== "organization" ||+ !authCheck.scope.orgId+ ) {+ return res.status(403).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail:+ "Invalid API key. Organization-scoped API key required for this operation.",+ status: 403,+ });+ }++ const orgMembership = await prisma.organizationMembership.findFirst({+ where: {+ orgId: authCheck.scope.orgId,+ user: {+ id: req.query.id as string,+ },+ },+ select: {+ id: true,+ user: true,+ },+ });++ if (!orgMembership?.user) {+ return res.status(404).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "User not found",+ status: 404,+ });+ }++ // Route to the appropriate handler based on HTTP method+ try {+ switch (req.method) {+ case "GET":+ return handleGet(req, res, orgMembership.user);+ case "DELETE":+ return handleDelete(+ req,+ res,+ orgMembership.user,+ authCheck.scope.orgId,+ );+ default:+ // This should never happen due to the check at the beginning+ return res.status(405).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "Method not allowed",+ status: 405,+ });+ }+ } catch (error) {+ logger.error(+ `Error handling SCIM user ${req.query.id} for ${req.method}`,+ error,+ );+ return res.status(500).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "Internal server error",+ status: 500,+ });+ }+}++// GET - Retrieve a specific user+async function handleGet(+ req: NextApiRequest,+ res: NextApiResponse,+ user: User,+) {+ // Transform to SCIM format+ return res.status(200).json({+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ id: user.id,+ userName: user.email,+ name: {+ formatted: user.name,+ },+ emails: [+ {+ primary: true,+ value: user.email,+ type: "work",+ },+ ],+ meta: {+ resourceType: "User",+ created: user.createdAt?.toISOString(),+ lastModified: user.updatedAt?.toISOString(),+ },+ });+}++// DELETE - Remove user from organization+async function handleDelete(+ req: NextApiRequest,+ res: NextApiResponse,+ user: User,+ orgId: string,+) {+ // Delete just removes the user from the organization+ await prisma.organizationMembership.deleteMany({+ where: {+ userId: user.id,+ orgId: orgId,+ },+ });++ // Return empty response with 204 No Content.+ return res.status(204).end();+}diff --git a/web/src/pages/api/public/scim/Users/index.ts b/web/src/pages/api/public/scim/Users/index.tsnew file mode 100644index 0000000000..8e00029d42--- /dev/null+++ b/web/src/pages/api/public/scim/Users/index.ts@@ -0,0 +1,214 @@+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";++import { type NextApiRequest, type NextApiResponse } from "next";+import { hashPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ await runMiddleware(req, res, cors);++ if (req.method !== "GET" && req.method !== "POST") {+ logger.error(+ `Method not allowed for ${req.method} on /api/public/scim/Users`,+ );+ return res.status(405).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "Method not allowed",+ status: 405,+ });+ }++ // CHECK AUTH+ const authCheck = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);+ if (!authCheck.validKey) {+ return res.status(401).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: authCheck.error,+ status: 401,+ });+ }+ // END CHECK AUTH++ // Check if using an organization API key+ if (+ authCheck.scope.accessLevel !== "organization" ||+ !authCheck.scope.orgId+ ) {+ return res.status(403).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail:+ "Invalid API key. Organization-scoped API key required for this operation.",+ status: 403,+ });+ }++ if (req.method === "GET") {+ try {+ const { filter, startIndex = 1, count = 100 } = req.query;++ // Parse startIndex and count to integers+ const parsedStartIndex = parseInt(startIndex as string, 10) || 1;+ const parsedCount = parseInt(count as string, 10) || 100;++ let whereClause = {};+ if (filter && typeof filter === "string") {+ // Parse filter for userName eq "value"+ const match = filter.match(/userName eq "([^"]+)"/i);+ if (match && match[1]) {+ whereClause = {+ ...whereClause,+ email: match[1].toLowerCase(),+ };+ }+ }++ // Get total count for pagination+ const totalCount = await prisma.organizationMembership.count({+ where: {+ user: whereClause,+ orgId: authCheck.scope.orgId,+ },+ });++ // Get users with pagination+ const userMapping = await prisma.organizationMembership.findMany({+ where: {+ user: whereClause,+ orgId: authCheck.scope.orgId,+ },+ skip: parsedStartIndex - 1, // SCIM uses 1-based indexing+ take: parsedCount,+ select: {+ id: true,+ user: true,+ },+ });++ // Transform to SCIM format+ const scimUsers = userMapping+ .map((userMap) => userMap.user)+ .map((user) => ({+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ id: user.id,+ userName: user.email,+ name: {+ formatted: user.name,+ },+ emails: [+ {+ primary: true,+ value: user.email,+ type: "work",+ },+ ],+ meta: {+ resourceType: "User",+ },+ }));++ return res.status(200).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],+ totalResults: totalCount,+ startIndex: parsedStartIndex,+ itemsPerPage: scimUsers.length,+ Resources: scimUsers,+ });+ } catch (error) {+ logger.error("Error retrieving SCIM users", error);+ return res.status(500).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "Internal server error",+ status: 500,+ });+ }+ }++ if (req.method === "POST") {+ try {+ const { userName, name, password } = req.body;++ if (!userName) {+ return res.status(400).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "userName is required",+ status: 400,+ });+ }++ // Check if user already exists+ const existingUser = await prisma.organizationMembership.findMany({+ where: {+ user: {+ email: userName,+ },+ orgId: authCheck.scope.orgId,+ },+ });++ if (existingUser.length > 0) {+ return res.status(409).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "User with this userName already exists",+ status: 409,+ });+ }++ // Create the user+ const user = await prisma.user.upsert({+ where: {+ email: userName.toLowerCase(),+ },+ create: {+ email: userName.toLowerCase(),+ name: name.formatted,+ password: password ? await hashPassword(password) : undefined,+ },+ update: {},+ });+ await prisma.organizationMembership.create({+ data: {+ userId: user.id,+ orgId: authCheck.scope.orgId,+ role: "NONE",+ },+ });++ // Return SCIM formatted user+ return res.status(201).json({+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ id: user.id,+ userName: user.email,+ name: {+ formatted: user.name,+ },+ emails: [+ {+ primary: true,+ value: user.email,+ type: "work",+ },+ ],+ meta: {+ resourceType: "User",+ created: user.createdAt?.toISOString(),+ lastModified: user.updatedAt?.toISOString(),+ },+ });+ } catch (error) {+ logger.error("Failed to create SCIM user", error);+ return res.status(500).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "Internal server error",+ status: 500,+ });+ }+ }+}