msw#RestContext TypeScript Examples

The following examples show how to use msw#RestContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TaxonomicFilter.stories.tsx    From posthog-foss with MIT License 6 votes vote down vote up
mockGetPropertyDefinitions = (
    handler: ResponseResolver<
        RestRequest<GetPropertyDefinitionsRequest, any>,
        RestContext,
        GetPropertyDefinitionsResponse
    >
) =>
    rest.get<GetPropertyDefinitionsRequest, GetPropertyDefinitionsResponse>(
        '/api/projects/@current/property_definitions',
        handler
    )
Example #2
Source File: EventSelect.stories.tsx    From posthog-foss with MIT License 5 votes vote down vote up
mockGetEventDefinitions = (
    handler: ResponseResolver<RestRequest<GetEventDefinitionsRequest, any>, RestContext, GetEventDefinitionsResponse>
) =>
    rest.get<GetEventDefinitionsRequest, GetEventDefinitionsResponse>(
        '/api/projects/:projectId/event_definitions',
        handler
    )
Example #3
Source File: TaxonomicFilter.stories.tsx    From posthog-foss with MIT License 5 votes vote down vote up
mockGetPersonProperties = (
    handler: ResponseResolver<RestRequest<GetPersonPropertiesRequest, any>, RestContext, GetPersonPropertiesResponse>
) => rest.get<GetPersonPropertiesRequest, GetPersonPropertiesResponse>('/api/person/properties', handler)
Example #4
Source File: TaxonomicFilter.stories.tsx    From posthog-foss with MIT License 5 votes vote down vote up
mockGetCohorts = (
    handler: ResponseResolver<RestRequest<GetCohortsRequest, any>, RestContext, GetCohortsResponse>
) => rest.get<GetCohortsRequest, GetCohortsResponse>('/api/projects/1/cohorts/', handler)
Example #5
Source File: PermissionIntegrationClient.test.ts    From backstage with Apache License 2.0 4 votes vote down vote up
describe('PermissionIntegrationClient', () => {
  describe('applyConditions', () => {
    let server: SetupServerApi;

    const mockConditions: PermissionCriteria<PermissionCondition> = {
      not: {
        allOf: [
          { rule: 'RULE_1', resourceType: 'test-resource', params: [] },
          { rule: 'RULE_2', resourceType: 'test-resource', params: ['abc'] },
        ],
      },
    };

    const mockApplyConditionsHandler = jest.fn(
      (_req, res, { json }: RestContext) => {
        return res(
          json({ items: [{ id: '123', result: AuthorizeResult.ALLOW }] }),
        );
      },
    );

    const mockBaseUrl = 'http://backstage:9191';
    const discovery: PluginEndpointDiscovery = {
      async getBaseUrl(pluginId) {
        return `${mockBaseUrl}/${pluginId}`;
      },
      async getExternalBaseUrl() {
        throw new Error('Not implemented.');
      },
    };

    const client: PermissionIntegrationClient = new PermissionIntegrationClient(
      {
        discovery,
      },
    );

    beforeAll(() => {
      server = setupServer();
      server.listen({ onUnhandledRequest: 'error' });
      server.use(
        rest.post(
          `${mockBaseUrl}/plugin-1/.well-known/backstage/permissions/apply-conditions`,
          mockApplyConditionsHandler,
        ),
      );
    });

    afterAll(() => server.close());

    afterEach(() => {
      jest.clearAllMocks();
    });

    it('should make a POST request to the correct endpoint', async () => {
      await client.applyConditions('plugin-1', [
        {
          id: '123',
          resourceRef: 'testResource1',
          resourceType: 'test-resource',
          conditions: mockConditions,
        },
      ]);

      expect(mockApplyConditionsHandler).toHaveBeenCalled();
    });

    it('should include a request body', async () => {
      await client.applyConditions('plugin-1', [
        {
          id: '123',
          resourceRef: 'testResource1',
          resourceType: 'test-resource',
          conditions: mockConditions,
        },
      ]);

      expect(mockApplyConditionsHandler).toHaveBeenCalledWith(
        expect.objectContaining({
          body: {
            items: [
              {
                id: '123',
                resourceRef: 'testResource1',
                resourceType: 'test-resource',
                conditions: mockConditions,
              },
            ],
          },
        }),
        expect.anything(),
        expect.anything(),
      );
    });

    it('should return the response from the fetch request', async () => {
      const response = await client.applyConditions('plugin-1', [
        {
          id: '123',
          resourceRef: 'testResource1',
          resourceType: 'test-resource',
          conditions: mockConditions,
        },
      ]);

      expect(response).toEqual(
        expect.objectContaining([{ id: '123', result: AuthorizeResult.ALLOW }]),
      );
    });

    it('should not include authorization headers if no token is supplied', async () => {
      await client.applyConditions('plugin-1', [
        {
          id: '123',
          resourceRef: 'testResource1',
          resourceType: 'test-resource',
          conditions: mockConditions,
        },
      ]);

      const request = mockApplyConditionsHandler.mock.calls[0][0];
      expect(request.headers.has('authorization')).toEqual(false);
    });

    it('should include correctly-constructed authorization header if token is supplied', async () => {
      await client.applyConditions(
        'plugin-1',
        [
          {
            id: '123',
            resourceRef: 'testResource1',
            resourceType: 'test-resource',
            conditions: mockConditions,
          },
        ],
        'Bearer fake-token',
      );

      const request = mockApplyConditionsHandler.mock.calls[0][0];
      expect(request.headers.get('authorization')).toEqual('Bearer fake-token');
    });

    it('should forward response errors', async () => {
      mockApplyConditionsHandler.mockImplementationOnce(
        (_req, res, { status }: RestContext) => {
          return res(status(401));
        },
      );

      await expect(
        client.applyConditions('plugin-1', [
          {
            id: '123',
            resourceRef: 'testResource1',
            resourceType: 'test-resource',
            conditions: mockConditions,
          },
        ]),
      ).rejects.toThrowError(/401/i);
    });

    it('should reject invalid responses', async () => {
      mockApplyConditionsHandler.mockImplementationOnce(
        (_req, res, { json }: RestContext) => {
          return res(
            json({ items: [{ id: '123', outcome: AuthorizeResult.ALLOW }] }),
          );
        },
      );

      await expect(
        client.applyConditions('plugin-1', [
          {
            id: '123',
            resourceRef: 'testResource1',
            resourceType: 'test-resource',
            conditions: mockConditions,
          },
        ]),
      ).rejects.toThrowError(/invalid input/i);
    });

    it('should batch requests to plugin backends', async () => {
      mockApplyConditionsHandler.mockImplementationOnce(
        (_req, res, { json }: RestContext) => {
          return res(
            json({
              items: [
                { id: '123', result: AuthorizeResult.ALLOW },
                { id: '456', result: AuthorizeResult.DENY },
                { id: '789', result: AuthorizeResult.ALLOW },
              ],
            }),
          );
        },
      );

      await expect(
        client.applyConditions('plugin-1', [
          {
            id: '123',
            resourceRef: 'testResource1',
            resourceType: 'test-resource',
            conditions: mockConditions,
          },
          {
            id: '456',
            resourceRef: 'testResource1',
            resourceType: 'test-resource',
            conditions: mockConditions,
          },
          {
            id: '789',
            resourceRef: 'testResource1',
            resourceType: 'test-resource',
            conditions: mockConditions,
          },
        ]),
      ).resolves.toEqual([
        { id: '123', result: AuthorizeResult.ALLOW },
        { id: '456', result: AuthorizeResult.DENY },
        { id: '789', result: AuthorizeResult.ALLOW },
      ]);

      expect(mockApplyConditionsHandler).toHaveBeenCalledTimes(1);
    });
  });

  describe('integration with @backstage/plugin-permission-node', () => {
    let server: Server;
    let client: PermissionIntegrationClient;
    let routerSpy: RequestHandler;

    beforeAll(async () => {
      const router = Router();

      router.use(
        createPermissionIntegrationRouter({
          resourceType: 'test-resource',
          getResources: async resourceRefs =>
            resourceRefs.map(resourceRef => ({
              id: resourceRef,
            })),
          rules: [
            createPermissionRule({
              name: 'RULE_1',
              description: 'Test rule 1',
              resourceType: 'test-resource',
              apply: (_resource: any, input: 'yes' | 'no') => input === 'yes',
              toQuery: () => {
                throw new Error('Not implemented');
              },
            }),
            createPermissionRule({
              name: 'RULE_2',
              description: 'Test rule 2',
              resourceType: 'test-resource',
              apply: (_resource: any, input: 'yes' | 'no') => input === 'yes',
              toQuery: () => {
                throw new Error('Not implemented');
              },
            }),
          ],
        }),
      );

      const app = express();

      routerSpy = jest.fn(router);

      app.use('/plugin-1', routerSpy);

      await new Promise<void>(resolve => {
        server = app.listen(resolve);
      });

      const discovery: PluginEndpointDiscovery = {
        async getBaseUrl(pluginId: string) {
          const listenPort = (server.address()! as AddressInfo).port;

          return `http://0.0.0.0:${listenPort}/${pluginId}`;
        },
        async getExternalBaseUrl() {
          throw new Error('Not implemented.');
        },
      };

      client = new PermissionIntegrationClient({
        discovery,
      });
    });

    afterAll(
      async () =>
        new Promise<void>((resolve, reject) =>
          server.close(err => (err ? reject(err) : resolve())),
        ),
    );

    afterEach(() => {
      jest.clearAllMocks();
    });

    it('works for simple conditions', async () => {
      await expect(
        client.applyConditions('plugin-1', [
          {
            id: '123',
            resourceRef: 'testResource1',
            resourceType: 'test-resource',
            conditions: {
              rule: 'RULE_1',
              resourceType: 'test-resource',
              params: ['no'],
            },
          },
        ]),
      ).resolves.toEqual([{ id: '123', result: AuthorizeResult.DENY }]);
    });

    it('works for complex criteria', async () => {
      await expect(
        client.applyConditions('plugin-1', [
          {
            id: '123',
            resourceRef: 'testResource1',
            resourceType: 'test-resource',
            conditions: {
              allOf: [
                {
                  allOf: [
                    {
                      rule: 'RULE_1',
                      resourceType: 'test-resource',
                      params: ['yes'],
                    },
                    {
                      not: {
                        rule: 'RULE_2',
                        resourceType: 'test-resource',
                        params: ['no'],
                      },
                    },
                  ],
                },
                {
                  not: {
                    allOf: [
                      {
                        rule: 'RULE_1',
                        resourceType: 'test-resource',
                        params: ['no'],
                      },
                      {
                        rule: 'RULE_2',
                        resourceType: 'test-resource',
                        params: ['yes'],
                      },
                    ],
                  },
                },
              ],
            },
          },
        ]),
      ).resolves.toEqual([{ id: '123', result: AuthorizeResult.ALLOW }]);
    });
  });
});
Example #6
Source File: PermissionClient.test.ts    From backstage with Apache License 2.0 4 votes vote down vote up
describe('PermissionClient', () => {
  beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
  afterAll(() => server.close());
  afterEach(() => server.resetHandlers());

  describe('authorize', () => {
    const mockAuthorizeConditional = {
      permission: mockPermission,
      resourceRef: 'foo:bar',
    };

    const mockAuthorizeHandler = jest.fn((req, res, { json }: RestContext) => {
      const responses = req.body.items.map(
        (a: IdentifiedPermissionMessage<EvaluatePermissionRequest>) => ({
          id: a.id,
          result: AuthorizeResult.ALLOW,
        }),
      );

      return res(json({ items: responses }));
    });

    beforeEach(() => {
      server.use(rest.post(`${mockBaseUrl}/authorize`, mockAuthorizeHandler));
    });

    afterEach(() => {
      jest.clearAllMocks();
    });

    it('should fetch entities from correct endpoint', async () => {
      await client.authorize([mockAuthorizeConditional]);
      expect(mockAuthorizeHandler).toHaveBeenCalled();
    });

    it('should include a request body', async () => {
      await client.authorize([mockAuthorizeConditional]);

      const request = mockAuthorizeHandler.mock.calls[0][0];

      expect(request.body).toEqual({
        items: [
          expect.objectContaining({
            permission: mockPermission,
            resourceRef: 'foo:bar',
          }),
        ],
      });
    });

    it('should return the response from the fetch request', async () => {
      const response = await client.authorize([mockAuthorizeConditional]);
      expect(response[0]).toEqual(
        expect.objectContaining({ result: AuthorizeResult.ALLOW }),
      );
    });

    it('should not include authorization headers if no token is supplied', async () => {
      await client.authorize([mockAuthorizeConditional]);

      const request = mockAuthorizeHandler.mock.calls[0][0];
      expect(request.headers.has('authorization')).toEqual(false);
    });

    it('should include correctly-constructed authorization header if token is supplied', async () => {
      await client.authorize([mockAuthorizeConditional], { token });

      const request = mockAuthorizeHandler.mock.calls[0][0];
      expect(request.headers.get('authorization')).toEqual('Bearer fake-token');
    });

    it('should forward response errors', async () => {
      mockAuthorizeHandler.mockImplementationOnce(
        (_req, res, { status }: RestContext) => {
          return res(status(401));
        },
      );
      await expect(
        client.authorize([mockAuthorizeConditional], { token }),
      ).rejects.toThrowError(/request failed with 401/i);
    });

    it('should reject responses with missing ids', async () => {
      mockAuthorizeHandler.mockImplementationOnce(
        (_req, res, { json }: RestContext) => {
          return res(
            json({
              items: [{ id: 'wrong-id', result: AuthorizeResult.ALLOW }],
            }),
          );
        },
      );
      await expect(
        client.authorize([mockAuthorizeConditional], { token }),
      ).rejects.toThrowError(/items in response do not match request/i);
    });

    it('should reject invalid responses', async () => {
      mockAuthorizeHandler.mockImplementationOnce(
        (req, res, { json }: RestContext) => {
          const responses = req.body.items.map(
            (a: IdentifiedPermissionMessage<EvaluatePermissionRequest>) => ({
              id: a.id,
              outcome: AuthorizeResult.ALLOW,
            }),
          );

          return res(json({ items: responses }));
        },
      );
      await expect(
        client.authorize([mockAuthorizeConditional], { token }),
      ).rejects.toThrowError(/invalid input/i);
    });

    it('should allow all when permission.enabled is false', async () => {
      mockAuthorizeHandler.mockImplementationOnce(
        (req, res, { json }: RestContext) => {
          const responses = req.body.map(
            (a: IdentifiedPermissionMessage<EvaluatePermissionRequest>) => ({
              id: a.id,
              result: AuthorizeResult.DENY,
            }),
          );

          return res(json({ items: responses }));
        },
      );
      const disabled = new PermissionClient({
        discovery,
        config: new ConfigReader({ permission: { enabled: false } }),
      });
      const response = await disabled.authorize([mockAuthorizeConditional]);
      expect(response[0]).toEqual(
        expect.objectContaining({ result: AuthorizeResult.ALLOW }),
      );
      expect(mockAuthorizeHandler).not.toBeCalled();
    });

    it('should allow all when permission.enabled is not configured', async () => {
      mockAuthorizeHandler.mockImplementationOnce(
        (req, res, { json }: RestContext) => {
          const responses = req.body.map(
            (a: IdentifiedPermissionMessage<EvaluatePermissionRequest>) => ({
              id: a.id,
              outcome: AuthorizeResult.DENY,
            }),
          );

          return res(json(responses));
        },
      );
      const disabled = new PermissionClient({
        discovery,
        config: new ConfigReader({}),
      });
      const response = await disabled.authorize([mockAuthorizeConditional]);
      expect(response[0]).toEqual(
        expect.objectContaining({ result: AuthorizeResult.ALLOW }),
      );
      expect(mockAuthorizeHandler).not.toBeCalled();
    });
  });

  describe('authorizeConditional', () => {
    const mockResourceAuthorizeConditional = {
      permission: mockPermission,
    };

    const mockPolicyDecisionHandler = jest.fn(
      (req, res, { json }: RestContext) => {
        const responses = req.body.items.map(
          (a: IdentifiedPermissionMessage<ConditionalPolicyDecision>) => ({
            id: a.id,
            pluginId: 'test-plugin',
            resourceType: 'test-resource',
            result: AuthorizeResult.CONDITIONAL,
            conditions: {
              resourceType: 'test-resource',
              rule: 'FOO',
              params: ['bar'],
            },
          }),
        );

        return res(json({ items: responses }));
      },
    );

    beforeEach(() => {
      server.use(
        rest.post(`${mockBaseUrl}/authorize`, mockPolicyDecisionHandler),
      );
    });

    afterEach(() => {
      jest.clearAllMocks();
    });

    it('should fetch entities from correct endpoint', async () => {
      await client.authorizeConditional([mockResourceAuthorizeConditional]);
      expect(mockPolicyDecisionHandler).toHaveBeenCalled();
    });

    it('should include a request body', async () => {
      await client.authorizeConditional([mockResourceAuthorizeConditional]);

      const request = mockPolicyDecisionHandler.mock.calls[0][0];

      expect(request.body).toEqual({
        items: [
          expect.objectContaining({
            permission: mockPermission,
          }),
        ],
      });
    });

    it('should return the response from the fetch request', async () => {
      const response = await client.authorizeConditional([
        mockResourceAuthorizeConditional,
      ]);
      expect(response[0]).toEqual(
        expect.objectContaining({
          result: AuthorizeResult.CONDITIONAL,
          conditions: {
            rule: 'FOO',
            resourceType: 'test-resource',
            params: ['bar'],
          },
        }),
      );
    });

    it('should not include authorization headers if no token is supplied', async () => {
      await client.authorizeConditional([mockResourceAuthorizeConditional]);

      const request = mockPolicyDecisionHandler.mock.calls[0][0];
      expect(request.headers.has('authorization')).toEqual(false);
    });

    it('should include correctly-constructed authorization header if token is supplied', async () => {
      await client.authorizeConditional([mockResourceAuthorizeConditional], {
        token,
      });

      const request = mockPolicyDecisionHandler.mock.calls[0][0];
      expect(request.headers.get('authorization')).toEqual('Bearer fake-token');
    });

    it('should forward response errors', async () => {
      mockPolicyDecisionHandler.mockImplementationOnce(
        (_req, res, { status }: RestContext) => {
          return res(status(401));
        },
      );
      await expect(
        client.authorizeConditional([mockResourceAuthorizeConditional], {
          token,
        }),
      ).rejects.toThrowError(/request failed with 401/i);
    });

    it('should reject responses with missing ids', async () => {
      mockPolicyDecisionHandler.mockImplementationOnce(
        (_req, res, { json }: RestContext) => {
          return res(
            json({
              items: [{ id: 'wrong-id', result: AuthorizeResult.ALLOW }],
            }),
          );
        },
      );
      await expect(
        client.authorizeConditional([mockResourceAuthorizeConditional], {
          token,
        }),
      ).rejects.toThrowError(/items in response do not match request/i);
    });

    it('should reject invalid responses', async () => {
      mockPolicyDecisionHandler.mockImplementationOnce(
        (req, res, { json }: RestContext) => {
          const responses = req.body.items.map(
            (a: IdentifiedPermissionMessage<ConditionalPolicyDecision>) => ({
              id: a.id,
              outcome: AuthorizeResult.ALLOW,
            }),
          );

          return res(json({ items: responses }));
        },
      );
      await expect(
        client.authorizeConditional([mockResourceAuthorizeConditional], {
          token,
        }),
      ).rejects.toThrowError(/invalid input/i);
    });

    it('should allow all when permission.enabled is false', async () => {
      mockPolicyDecisionHandler.mockImplementationOnce(
        (req, res, { json }: RestContext) => {
          const responses = req.body.map(
            (a: IdentifiedPermissionMessage<ConditionalPolicyDecision>) => ({
              id: a.id,
              result: AuthorizeResult.DENY,
            }),
          );

          return res(json({ items: responses }));
        },
      );
      const disabled = new PermissionClient({
        discovery,
        config: new ConfigReader({ permission: { enabled: false } }),
      });
      const response = await disabled.authorizeConditional(
        [mockResourceAuthorizeConditional],
        {
          token,
        },
      );
      expect(response[0]).toEqual(
        expect.objectContaining({ result: AuthorizeResult.ALLOW }),
      );
      expect(mockPolicyDecisionHandler).not.toBeCalled();
    });

    it('should allow all when permission.enabled is not configured', async () => {
      mockPolicyDecisionHandler.mockImplementationOnce(
        (req, res, { json }: RestContext) => {
          const responses = req.body.map(
            (a: IdentifiedPermissionMessage<ConditionalPolicyDecision>) => ({
              id: a.id,
              outcome: AuthorizeResult.DENY,
            }),
          );

          return res(json(responses));
        },
      );
      const disabled = new PermissionClient({
        discovery,
        config: new ConfigReader({}),
      });
      const response = await disabled.authorizeConditional(
        [mockResourceAuthorizeConditional],
        {
          token,
        },
      );
      expect(response[0]).toEqual(
        expect.objectContaining({ result: AuthorizeResult.ALLOW }),
      );
      expect(mockPolicyDecisionHandler).not.toBeCalled();
    });
  });
});
Example #7
Source File: ServerPermissionClient.test.ts    From backstage with Apache License 2.0 4 votes vote down vote up
describe('ServerPermissionClient', () => {
  beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
  afterAll(() => server.close());

  it('should error if permissions are enabled but a no-op token manager is configured', async () => {
    expect(() =>
      ServerPermissionClient.fromConfig(config, {
        discovery,
        tokenManager: ServerTokenManager.noop(),
      }),
    ).toThrowError(
      'Backend-to-backend authentication must be configured before enabling permissions. Read more here https://backstage.io/docs/tutorials/backend-to-backend-auth',
    );
  });

  describe('authorize', () => {
    let mockAuthorizeHandler: jest.Mock;

    beforeEach(() => {
      mockAuthorizeHandler = jest.fn((req, res, { json }: RestContext) => {
        const responses = req.body.items.map(
          (r: IdentifiedPermissionMessage<DefinitivePolicyDecision>) => ({
            id: r.id,
            result: AuthorizeResult.ALLOW,
          }),
        );

        return res(json({ items: responses }));
      });

      server.use(rest.post(`${mockBaseUrl}/authorize`, mockAuthorizeHandler));
    });
    afterEach(() => server.resetHandlers());

    it('should bypass the permission backend if permissions are disabled', async () => {
      const client = ServerPermissionClient.fromConfig(new ConfigReader({}), {
        discovery,
        tokenManager: ServerTokenManager.noop(),
      });

      await client.authorize([
        {
          permission: testBasicPermission,
        },
      ]);

      expect(mockAuthorizeHandler).not.toHaveBeenCalled();
    });

    it('should bypass the permission backend if permissions are enabled and request has valid server token', async () => {
      const tokenManager = ServerTokenManager.fromConfig(config, { logger });
      const client = ServerPermissionClient.fromConfig(config, {
        discovery,
        tokenManager,
      });

      await client.authorize([{ permission: testBasicPermission }], {
        token: (await tokenManager.getToken()).token,
      });

      expect(mockAuthorizeHandler).not.toHaveBeenCalled();
    });

    it('should call the permission backend if permissions are enabled and request does not have valid server token', async () => {
      const tokenManager = ServerTokenManager.fromConfig(config, { logger });
      const client = ServerPermissionClient.fromConfig(config, {
        discovery,
        tokenManager,
      });

      await client.authorize([{ permission: testBasicPermission }], {
        token: 'a-user-token',
      });

      expect(mockAuthorizeHandler).toHaveBeenCalled();
    });
  });

  describe('authorizeConditional', () => {
    let mockAuthorizeHandler: jest.Mock;

    beforeEach(() => {
      mockAuthorizeHandler = jest.fn((req, res, { json }: RestContext) => {
        const responses = req.body.items.map(
          (r: IdentifiedPermissionMessage<ConditionalPolicyDecision>) => ({
            id: r.id,
            result: AuthorizeResult.ALLOW,
          }),
        );

        return res(json({ items: responses }));
      });

      server.use(rest.post(`${mockBaseUrl}/authorize`, mockAuthorizeHandler));
    });
    afterEach(() => server.resetHandlers());

    it('should bypass the permission backend if permissions are disabled', async () => {
      const client = ServerPermissionClient.fromConfig(new ConfigReader({}), {
        discovery,
        tokenManager: ServerTokenManager.noop(),
      });

      await client.authorizeConditional([
        { permission: testResourcePermission },
      ]);

      expect(mockAuthorizeHandler).not.toHaveBeenCalled();
    });

    it('should bypass the permission backend if permissions are enabled and request has valid server token', async () => {
      const tokenManager = ServerTokenManager.fromConfig(config, { logger });
      const client = ServerPermissionClient.fromConfig(config, {
        discovery,
        tokenManager,
      });

      await client.authorizeConditional(
        [{ permission: testResourcePermission }],
        {
          token: (await tokenManager.getToken()).token,
        },
      );

      expect(mockAuthorizeHandler).not.toHaveBeenCalled();
    });

    it('should call the permission backend if permissions are enabled and request does not have valid server token', async () => {
      const tokenManager = ServerTokenManager.fromConfig(config, { logger });
      const client = ServerPermissionClient.fromConfig(config, {
        discovery,
        tokenManager,
      });

      await client.authorizeConditional(
        [{ permission: testResourcePermission }],
        {
          token: 'a-user-token',
        },
      );

      expect(mockAuthorizeHandler).toHaveBeenCalled();
    });
  });
});