Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@entur-partner/permission-client-node

Package Overview
Dependencies
Maintainers
0
Versions
26
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@entur-partner/permission-client-node

Node client library for Permission Store

  • 3.4.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
561
increased by38.18%
Maintainers
0
Weekly downloads
 
Created
Source

Permission Client for Node

Permission Client is a Javascript module for Node and is an SDK for Entur Permission Store providing local cache of user permissions. A similar SDK also exists for Java called Permission Client for Java.

Using Permission Client will help you satisfy Enturs Application Security Requirements related to Authorisation. If you have any questions about how to use Permission Store please use the Slack channel #work-tilgangstyring.

Other more general questions related to authentication and/or authorization can be directed to #talk-sikkerhet.

Requirements

Minimum requirements
RequirementFunctionalityComment
ES2020All
Optional requirements
RequirementFunctionalityComment
typescriptAll
@stomp/stompjs + websocketIn Memory CacheUsed to save network traffic and faster refresh rates.

Getting Started

In this getting started guide we will describe how to set up a Node application with authorisation delivered by Permission Client for Node.

Links to other frameworks and services that are mentioned/relevant for this guide:

Setup Express Application

Permission Client for Node is provided as a standalone javascript module, but in this getting started guide we will be using it along with the Express framework.

Verify your Express setup:

  • Check you have a running Express application.
  • Performs authentication and validated JWT. You can use express-oauth2-jwt-bearer or your favorite package.
  • Application has an internal/partner auth0 m2m client it can use. Internal clients can easily be provisioned for your project as described in The DevOps Handbook and how to implement authentication.
  • Set up your test framework like Jest.

Add Permission Client package

yarn add @entur-partner/permission-client-node

Create permissions

In this chapter we will show how to use Permission Client to secure a REST endpoint.

Permissions for the application will be defined in typescript to be used in Setup Permission Client for Node chapter.

Permissions defined by applications must be in line with the guidelines described in Confluence here.

Here is an example file myPermissions.ts:

import { ApplicationPermission, BusinessCapability } from '@entur-partner/permission-client-node'

export const APPLICATION_PERMISSIONS : ApplicationPermission[] = [];

// Define Business Capabilities

export const OPERATION1_CREATE : BusinessCapability = {operation: 'operation1', access: 'OPPRETT'};
APPLICATION_PERMISSIONS.push(OPERATION1_CREATE);

export const OPERATION1_READ : BusinessCapability = {operation: 'operation1', access: 'LES'};
APPLICATION_PERMISSIONS.push(OPERATION1_READ);

// Define Responsibility Sets

export const OPERATION2_READ : ApplicationPermission = {operation: 'operation2', access: 'LES', responsibilityType: 'name1.attributt1'};
APPLICATION_PERMISSIONS.push(OPERATION2_READ);

Setup Permission Client for Node

Setup of Permission Client in your Node application involves initialisation of TokenFactory and AuthorizeCache. Here is an example:

import { TokenOptions, TokenFactory } from '@entur-partner/permission-client-node'
import { AuthorizeCacheType, Application, PermissionDeliverRepository } from '@entur-partner/permission-client-node'
import PermissionClient from '@entur-partner/permission-client-node'
import { APPLICATION_PERMISSIONS } from './myPermissions'

// Define values for Auth0 internal client to be used when calling Permission Store
const clientTokenOptions : TokenOptions = {
  domain: 'internal.dev.entur.org',               // Changes to match environment.
  clientId: '<MNG_AUTH0_INT_CLIENT_ID>',          // Client ID from Google Secret Manager.
  clientSecret: '<MNG_AUTH0_INT_CLIENT_SECRET>',  // Client secret from Google Secret Manager.
  audience: 'https://api.dev.entur.io',           // Changes to match environment.
  refreshBeforeMinValidSeconds: 600               // Refresh token when valid to is less than 10 minutter.
}

const application : Application = {
  name : 'MyApplication',                         // Name of this application.
  refreshRate : 300                               // Refresh rate in seconds for in memory cache.
}

let permissionClient: AuthorizeCache;
const initPermissionClient = async () => {
  try {
    // TokenFactory will be used to get access tokens from Auth0
    const accessTokenFactory = new TokenFactory(clientTokenOptions);
    const permissionStoreUrl = new URL('permission-store URL');  // for local development: https://api.dev.entur.io/permission-store/v1 
    const repository = new PermissionDeliverRepository(application, accessTokenFactory, permissionStoreUrl);

    permissionClient = await PermissionClient(AuthorizeCacheType.IN_MEMORY, APPLICATION_PERMISSIONS, repository);
    // Optional to use WebSocket when running in Google Kubernetes Engine (GKE)       
    // const permissionClient = await PermissionClient(AuthorizeCacheType.IN_MEMORY, APPLICATION_PERMISSIONS, repository, { communicationType: CommunicationType.SocketJS });

    permissionClient.setScheduleErrorHandler((error) => {
      logger.warning('PermissionClient scheduler failed', error);
    });

    logger.info('PermissionClient initialized');
  } catch (error) {
    logger.error('Failed to initialize PermissionClient', error);
    throw Error('Failed to initialize PermissionClient. Please make sure permission store cache configurations are correct and try again.');
  }
};

export { initPermissionClient, permissionClient };

Permissions

Defining and implementing permissions checks in the application is a central part of using Permission Client. Permission Client supports two types of permissions:

  • Business Capability
  • Responsibility Set

Business Capability Permissions is typically used for securing REST endpoints. And Responsibility Permissions is a good candidate when you want you securely share data between partners.

Permissions can be:

  • Restricted to a single or every organisation.
  • Restricted with the superuser flag.

Business Capability

Business capability is a right typically used to control access to endpoints.

Business Capability are defined in code and used when creating PermissionClient. Example:

export const OPERATION_CREATE : BusinessCapability = {operation: 'operation', access: 'OPPRETT'};

Responsibility Set

Responsibility Set is a right designed to control access to data through permissions and agreements. This permission works similar to Business Capability, but in addition an agreement must be registered that the users organisation is allowed to access target data element.

Responsibility Sets are defined in code and used when creating PermissionClient. Example:

export const OPERATION_READ : ApplicationPermission = {operation: 'operation', access: 'LES', responsibilityType: 'name.attributt'};

Agreement

Agreements are used in tandem with responsibility sets to restrict access to data based on which organisation the user/client belongs to. I.e. an agreement is used to describe the relationship between an organisation and some data element.

An application using Responsibility Sets will also normally maintain Agreements in its UI or delegates this to a related UI.

Note: Agreements can only be changed by the same application that created it.

To administrate agreements using Permission Client, applications can use the following methods on PermissionDeliverRepository:

  • async getAgreements(responsibilitySet: ResponsibilitySet): Promise<Agreement[]>
  • async storeAgreement(agreement: Agreement): Promise
  • async deleteAgreement(agreementId: bigint): Promise
  • async deleteObject(objectKey: ObjectKey): Promise // Similar to deleteAgreement, difference that it will delete all Agreements related to one object.

An Agreement is defined from:

  • operation
  • access
  • responsibilityType
  • responsibilityKey
  • organisationId

Cache types

Permission Client for Node only supports one cache type: IN_MEMORY cache.

IN_MEMORY

Cache type IN-MEMORY is for production.

Optional: Push notifications

When the application is running in one of the internal GKE environments (dev, tst/staging, prd), you can tell Permission Client to use Permission Store push notifications through websockets, rather than polling the Store directly at a regular interval. To do this, add websocket dependencies:

yarn add @stomp/stompjs websocket

In addition, the following code needs to be run when starting the service:

Object.assign(global, { WebSocket: require('websocket').w3cwebsocket });

And when you create PermissionClient pass the parameter typescript{ communicationType: CommunicationType.SocketJS }

const permissionClient = await PermissionClient(AuthorizeCacheType.IN_MEMORY, APPLICATION_PERMISSIONS, repository, { communicationType: CommunicationType.SocketJS });

LOCAL_TEST_CACHE

LOCAL_TEST_CACHE is a cache type for running automatic tests. LOCAL_TEST_CACHE is not implemented for Permission Client for Node. It's expected that mock functionality in Jest will be used in automatic tests.

Miscellaneous

Use Permission Store without downtime

Starting from version 3.0.0 of Permission Client, each instance of your running service will receive a unique instance ID. This ID is used to track the permissions required by your service, allowing Permission Store to calculate the total permission requirements for your application.

When introducing new permissions, it's sometimes necessary to add them to application.yaml before using them in your code. This ensures that role management can be performed before the corresponding restrictions are enforced during code execution.

Get source

Clone module from GitHub with:

git clone https://github.com/entur/permission-client.git

Install dependencies:

yarn install

Run Jest tests:

yarn test

Publishing

Create a NPM user account on https://www.npmjs.com/signup. Send your user to tech-lead in Entur Partner and ask to be added to Entur Partner organisation.

Upgrade version with:

yarn version [--major | --minor | --patch] 

Publishing with:

yarn publish

FAQs

Package last updated on 11 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc