CDS pluginCDS plugintypeInstalls into a CAP project and extends the runtime. CAP loads it through cds.requires or the plugin hook.See every one →What this type is →by SAPby SAPoriginPublished by SAP itself. A visible facet, never an input to a reading — a dormant official plugin reads exactly like a dormant independent one.See every one →

@sap/ams

Decides what a signed-in user may do in a Node.js application that authenticates through SAP Cloud Identity Services, from policies written in DCL.

@sap/ams checks, inside the running service, what a user signed in through Cloud Identity Services is allowed to do. A privilege check comes back as a decision in one of three states, granted, denied or conditional, the last meaning the answer still rests on attributes that have not been grounded to values; where a policy assigning a role carries attribute filters, requests reaching the annotated elements are filtered on the conditions AMS computes. From version 1.17.0 the decision is taken by an in-process engine reading DCN files, which the README calls the Authorization Decision Controller. In a CAP project it is a plugin for the cds CLI: an ams build task runs during cds build, and whenever a model is loaded under cds serve, cds watch or cds.test, and unless generation is switched off it writes base policies for the roles that occur in @requires and @restrict, a schema.dcl of the attributes it infers from @ams.attributes, and a policy deployer application under gen/policies. It also ships the deploy-dcl script that deployer runs to push the DCL bundle to the bound Identity service instance, and leaves a DCL file someone has edited by hand alone the next time the task runs; what it does not do is administer the policies, which are managed in the administration console of Cloud Identity Services once the application is deployed. @sap/ams-dev is the development-time half that compiles DCL to DCN for a local run.

Facts

Latestv3.10.0ReleasedLicenceSAP DEVELOPER LICENSE AGREEMENT 3.2

Where it sits

Lives in
Provides
AuthorizationCAPAuthorizationcapabilityDeciding who may read or change what, at service, entity and instance level — role checks, forwarded user context, and restrictions evaluated as query filters rather than after the fact.
Flavors
Requires
@sap/cds≥ 7.5@sap/cdsartifactThe peer range, as published.Cloud Identity ServicesCloud Identity Servicesartifactthe identity tenant whose users it authorizes, and whose administration console the policies are managed in

Who is behind it

SAPSAPOrganisationMaintains this
In the atlas: maintains 137, wrote 14
@SAP
maintainer

Before choosing this

Conditions

LicenceSAP Developer License Agreement 3.2 CAP§ 1, 2, 3A cds-plugin is used with SAP CAP materials, or an artifact is explicitly identified as a CAP plugin or application.
  • § 1 License. Productive customer applications are limited to SAP BTP or another SAP-licensed platform, and mass extraction to a non-SAP product is restricted except where solely required for SAP interoperability.
  • § 2 Intellectual Property. The agreement retains SAP's rights in the covered materials and limits making APIs, tools or software available to third parties, while preserving ownership of customer applications subject to SAP's underlying rights.
  • § 3 Artificial Intelligence Training. The agreement prohibits use of the covered materials and customer applications for training artificial-intelligence models or systems.
SAP Developer License Agreement 3.2 CAP →

What it declares

Every artifact

Type
CDS plugin
Origin
By SAP
Runtime
Node.js

As a CDS plugin

Declared for
>=7.5
Distributed through
npm

Connections3

@sap/ams connections@sap/amsPROVIDES→ provides1provides stated Evaluates AMS authorization policies in the application process for users authenticated through SAP [Cloud Identity Services](artifact:btp-cloud-identity-services), answering each privilege check as granted, denied or conditional, and filtering the resources a request reaches on the attribute conditions AMS computes. In a CAP project it also generates the base DCL policies for the roles the @requires and @restrict annotations already name. @sap/ams 3.9.0 — README: https://cdn.jsdelivr.net/npm/@sap/ams@3.9.0/README.md @sap/ams 3.9.0 — README, decision states: https://cdn.jsdelivr.net/npm/@sap/ams@3.9.0/README.md @sap/ams 3.9.0 — README, instance-based authorization: https://cdn.jsdelivr.net/npm/@sap/ams@3.9.0/README.md The cds Plugin @sap/ams — SAP Cloud Identity Services developer guide: https://sap.github.io/cloud-identity-developer-guide/CAP/cds-Plugin.htmlAuthorizationNEEDS→ connects to1connects to stated the policy bundle the application downloads to decide with, and the DCL bundle the deploy-dcl script pushes to the bound instance @sap/ams 3.9.0 — README, Hybrid testing: https://cdn.jsdelivr.net/npm/@sap/ams@3.9.0/README.md @sap/ams 3.9.0 — README, deploy-dcl script: https://cdn.jsdelivr.net/npm/@sap/ams@3.9.0/README.mdCloud Identity Services→ needs1needs stated the identity tenant whose users it authorizes, and whose administration console the policies are managed in @sap/ams 3.9.0 — README: https://cdn.jsdelivr.net/npm/@sap/ams@3.9.0/README.md @sap/ams 3.9.0 — README, CAP integration: https://cdn.jsdelivr.net/npm/@sap/ams@3.9.0/README.mdCloud Identity Services

Install

npm add @sap/ams

Derived from the package name. No recipe recorded; the README has the configuration.

Where it sits in your app

Download
Your CAP applicationYour SAP BTP subaccount@sap/ams 3.9.0 — README, Hybrid testing, checked 2026-09-19: “An application bound to an `ias` instance for authentication will always download its policy bundle from the corresponding AMS instance.”outbound@sap/ams, module@sap/amsCloud Identity Services, service instanceCloud IdentityServices
SAPnot SAP's, or the project's ownstated in the document

README

quoted from @sap/ams@3.10.0 under SAP DEVELOPER LICENSE AGREEMENT, read
@sap/ams@3.10.0/README.mdOn npm

@sap/ams

This is the Node.Js runtime library used to perform authorization checks in applications which authenticate users via the SAP Cloud Identity Services.

The module @sap/ams-dev provides the corresponding tooling support during application development.

As ADC (Authorization Decision Controller) an in-process engine based on DCN (Data Control Notation) files is used in versions >= 1.17.0. Follow the migration guide in the CHANGELOG of @sap/ams-dev for version 1.0.0 to update your local test setup from OPA to DCN Engine. When using newer versions, the OPA buildpack on CF can be removed once a policy deployer application has been configured for the upload of the base policies.

Table of Contents

Installation

Via public npmjs repository:

npm install @sap/ams
Maintenance

Keep the version of this dependency up-to-date since it's a crucial part of your application's security, for example by regularly running:

npm update @sap/ams # or: npm update

This is especially important when you deploy your application with a package-lock.json that locks the version that gets installed to a fixed version, until the next npm update.

When in doubt, check which version of the module is installed via

npm list @sap/ams

This will print a dependency tree that shows which versions of the module are installed, including transitive dependencies.

Version 3

Version 3 drastically changes the core API. Instead of checking privileges on a PolicyDecisionPoint with an Attributes object, an AuthProvider prepares an Authorizations object for the same purpose. This separates what to check from how to check it. The necessary configuration for advanced authorization scenarios, such as principal propagation or non-standard authorization strategies, are configured once during application start. As a result, the authorization checks themselves remain straight-forward in version 3, with a focus on the application domain.

New features:

  • Out-of-the-box support for technical communication scenarios via SAP Cloud Identity Services
  • Flexible configuration and extensibility for non-standard authorization strategies, for example when authenticating both via XSUAA and SAP Cloud Identity Services tokens
  • Exports Typescript Types for a better development experience
  • Improved events that allow correlating authorization checks with requests for logging and auditing
  • Support for SAP Cloud Identity Services credentials with certificates changing at runtime, for example when using ZTIS or mounted Kyma service bindings
Breaking Changes

CAP Node.js Applications should not need to make changes when updating to version 3.

For Non-CAP Node.js applications, please refer to the migration guide.

Usage

The following snippets give an example for the usage of the core API of the library.

Set-up
const { AuthorizationManagementService, IdentityServiceAuthProvider, AmsError } = require("@sap/ams");

let ams;
if (process.env.NODE_ENV === 'test') {
  // For local tests, init AMS with a locally compiled policy bundle and mocked policy assignments
  ams = AuthorizationManagementService.fromLocalDcn("./test/dcn", { // your compile target directory of the @sap/ams-dev compile-dcl script
    assignments: "./test/mockPolicyAssignments.json" // a file path of your choice or an in-memory structure
  });
} else {
  // For production, init AMS with the cloud policy and assignment bundle from the AMS server
  const identityService = ... // your @sap/xssec 4 IdentityService instance used for authentication
  ams = AuthorizationManagementService.fromIdentityService(identityService);
}

// Use the standard IdentityServiceAuthProvider or if necessary, write your own AuthProvider implementation instead
const authProvider = new IdentityServiceAuthProvider(ams)
    .withApiMapper(mapTechnicalUserApi, TECHNICAL_USER_FLOW)                // Optional: to authorize technical user tokens
    .withApiMapper(mapPrincipalPropagationApi, PRINCIPAL_PROPAGATION_FLOW); // Optional: to authorize principal propagation tokens

// Recommendation: Register a middleware behind the authentication middleware that allows authorization checks via the req object
const amsMw = authProvider.getMiddleware(); // IdentityServiceAuthProvider provides a pre-configured instance of AmsMiddleware
app.use(/^\/(?!health).*/i, authenticate, amsMw.authorize());

// You can identity Errors from @sap/ams via instanceof, for example in the express error handler:
app.use((err, req, res, next) => {
    if(err instance of AmsError) {
      // Error from @sap/ams library
      LOG.error("Error while authorizing user: ", err);
    } else {
      ... // other Error
    }

    return res.sendStatus(500);
});

// Make sure the readiness check of the application returns false before the following Promise resolves as AMS has not yet loaded the policy bundle required for authorization checks.
const AMS_STARTUP_TIMEOUT = process.env.AMS_STARTUP_TIMEOUT || 30; // maximum wait time in seconds
await ams.whenReady(AMS_STARTUP_TIMEOUT);
Authorization checks

Authorization checks are performed on Authorization objects created by implementations of the AuthProvider interface. Typically, authorizations are based on a security context that is created from a valid token during authentication. For instance, IdentityServiceAuthProvider expects an instance of IdentityServiceSecurityContext.

const securityContext = await createSecurityContext(identityService, { req }); // @sap/xssec 4 authentication
const authorizations = await authProvider.getAuthorizations(securityContext);

If the AmsMiddleware#authorize() handler is registered, it streamlines this process for all requests by placing an Authorization instance on the req object under the AMS_AUTHORIZATIONS symbol exported by @sap/ams.

const { AMS_AUTHORIZATIONS } = require("@sap/ams");

function createOrder(req, res) {
  const authorizations = req[AMS_AUTHORIZATIONS];
}
Handling Decisions

An authorization check will return a Decision object. A decision can be in one of three states:

  • granted: the checked privilege is unconditionally granted
  • denied: the checked privilege is unconditionally denied
  • conditional: the checked privilege might be granted but there are outstanding conditions whose attributes have not been grounded to values in the attribute input.

It provides the following methods to distinguish between these cases:

let decision;

// context-free privilege-check
decision = authorizations.checkPrivilege('delete', 'orders')
if(!decision.isGranted()) {
    return res.sendStatus(403);
}  

// contextual privilege check for a single entity
decision = authorizations.checkPrivilege('create', 'orders', { "$app.product.category" : "accessory" });
if(!decision.isGranted()) {
  return res.sendStatus(403);
}

// contextual privilege check for many entities
decision = authorizations.checkPrivilege('read', 'orders');
if(decision.isDenied()) {
  return res.sendStatus(403);
} else if (decision.isGranted()) {
  // definitive GRANT without outstanding WHERE condition
  return res.json(db.readAllOrders());
} else {
  // instance-based GRANT with outstanding WHERE condition
  const filter = decision.visitDCN(convertCall, convertValue); // convert condition to a filter for the DB layer
  return res.json(db.readOrders(filter));
}
AmsMiddleware

Besides authorize(), the AmsMiddleware provides additional handlers to define early privilege (pre-)checks on the endpoint layer:

// returns 403 when no definitive (= no outstanding WHERE condition) GRANT delete ON orders is assigned to user
app.delete('/orders/:id', amsMw.checkPrivilege('delete', 'orders'), deleteOrder);

// returns 403 when no GRANT read ON orders is assigned to user. A potential WHERE condition for the GRANT is acceptable which needs to be evaluated in the service handler.
app.get('/orders', amsMw.precheckPrivilege('read', 'orders'), getOrders);

// returns 403 when no definitive GRANT read ON products or no (definitive or conditional) GRANT create ON orders is assigned to user
app.post('/orders', amsMw.checkPrivilege('read', 'products'), amsMw.precheckPrivilege('create', 'orders'), createOrder);

The benefits of defining privilege checks on the endpoint level are:

  • concise syntax
  • provides central overview of required privileges for different parts of the application
  • prevents accidental information leaks, for example by returning 404 instead of 403 while preparing the actual authorization check in the service handler
Technical communication

Technical communication via SAP Cloud Identity Services is supported out-of-the-box by the IdentityServiceAuthProvider.

Testing

For CAP applications, see here.

To test your application locally, without real SAP Cloud Identity Services tokens and AMS server, we recommend mocking an @sap/xssec SecurityContext during authentication that contains the relevant information. Then, the IdentityServiceAuthProvider will execute the same way it does in production, resulting in realistic authorization behavior of the application.

The DCL package called local has a special semantic. It is meant for DCL files with policies that are only relevant for testing but not for production. Its policies are ignored during the base policy upload, even if they are contained during the upload. You can use it to test runtime policies that build on top of your base policies without deploying them.

Follow the @sap/ams-dev documentation to set up your application for testing.

Events/Logging

Consumer applications can listen to events of the AuthorizationManagementService instance to log authorization checks and/or create audit log events:

ams.on("authorizationCheck", event => {
  if(event.type === "checkPrivilege") {
    if (event.decision.isGranted()) {
      console.log(`Privilege '${event.action} ${event.resource}' for ${event.context.token.scimId} was granted based on input`, event.input);
    }
  } else if (event.type === "getPotentialPrivileges") {
    ...
  }
});
Samples

The ams-samples-node repository contains samples that demonstrate the usage of this library.

API

AuthorizationManagementService
Construction
  • fromIdentityService(identityService, config?): AuthorizationManagementService
    Creates an instance using the DCN and policy assignments fetched with SAP Cloud Identity Services credentials.

    • identityService (object): SAP Cloud Identity Services object with certificate-based credentials.
  • fromLocalDcn(dcnRoot, config?): AuthorizationManagementService
    Creates an instance using locally compiled DCL files for testing.

    • dcnRoot (string): Root directory of the DCN bundle.
    • config (object, optional):
      • watch (boolean, default: false): Watch for file changes.
      • assignments (string | PolicyAssignments, optional): Path to JSON file or PolicyAssignments object.
      • debounceDelay (number, default: 1000): Debounce delay in ms.
      • start (boolean, default: true): Control whether to immediately start downloading the AMS bundle.

If an instance has been constructed with config.start=false, the loading of the AMS bundle must be started manually. This is useful when ZTIS is used and the credentials do not yet contain a certificate when the instance is created:

const ams = AuthorizationManagementService.fromIdentityService(identityService, { start: false });
// fill credentials with certificate asynchronously from ZTIS
getCertificateFromZTIS().then((cert, key) => {
  identityService.setCertificateAndKey(cert, key);
  ams.start();
});
Readiness Checks
  • whenReady(timeoutSeconds = 0): Promise<void>
    Returns a Promise that resolves once the instance is ready for authorization checks. If it has not received policies and assignments after the specified timeout interval, the Promise is rejected.

    • timeoutSeconds (number): Max wait time in seconds.
  • isReady(): boolean
    Checks if the instance is ready for authorization checks.


AuthProvider <<interface>>

This is a generic interface. Its implementations define how to construct instances of Authorizations and from which application context.

  • C: The generic type of the context object.
Methods
  • getAuthorizations(context: C): Promise<Authorizations>
    • context (C): The context object from which authorizations are derived.
Implementations
  • AuthorizationManagementService: Implements AuthProvider<PolicySet>.
  • XssecAuthProvider: Abstract base class implementing AuthProvider<SecurityContext> for authorization with an @sap/xssec SecurityContext.
    • IdentityServiceAuthProvider: Implements AuthProvider<IdentityServiceSecurityContext> for authorization of SAP Cloud Identity Services tokens.
      • HybridAuthProvider: Implements AuthProvider<IdentityServiceSecurityContext | XsuaaSecurityContext> for authorization of SAP Cloud Identity Services tokens or XSUAA tokens.
  • CdsAuthProvider: Abstract base class implementing AuthProvider<CdsContext> for authorization with a cds context in CAP applications.
    • CdsXssecAuthProvider Extends CdsAuthProvider for cds contexts with an @sap/xssec SecurityContext in cdsContext.http.req.authInfo.
      • CdsMockedAuthProvider: Extends CdsXssecAuthProvider by mocking an @sap/xssec SecurityContext for auth.kind = mocked users.
IdentityServiceAuthProvider
  • Implements AuthProvider<IdentityServiceSecurityContext>.
Methods
  • constructor(ams: AuthorizationManagementService): IdentityServiceAuthProvider

  • withApiMapper(mapApi: ApiMapper, flow?: TechnicalUserFlow): IdentityServiceAuthProvider
    Defines an API mapper for mapping consumed SAP Cloud Identity Services APIs to policies.

    • mapApi ((api : string, securityContext : IdentityServiceSecurityContext) => string | string[] | undefined): A function that maps a consumed API to no (undefined), one (string) or multiple (string[]) fully-qualified policy name(s).
    • flow (TECHNICAL_USER_FLOW | PRINCIPAL_PROPAGATION_FLOW, optional): A technical user flow exported by @sap/ams for which to apply the mapper. If omitted, applies it for both flows.
  • withServicePlanMapper(servicePlanMapper: ServicePlanMapper): IdentityServiceAuthProvider
    Defines a service plan mapper for BTP reuse service for mapping BTP service plans of consumers to policies.

    • servicePlanMapper ((plan : string, securityContext : IdentityServiceSecurityContext) => string | string[] | undefined): A function that maps a service plan to no (undefined), one (string) or multiple (string[]) fully-qualified policy name(s).
  • getAuthorizations(securityContext: IdentityServiceSecurityContext): Promise<Authorizations>
    Returns the results of getUserAuthorizations or getTechnicalAuthorizations depending on the token. If both are available, returns the logical intersection (principal propagation).

  • getUserAuthorizations(securityContext: IdentityServiceSecurityContext): Promise<Authorizations | null>
    Extracts authorizations for a user based on assigned policies.

  • getTechnicalAuthorizations(securityContext: IdentityServiceSecurityContext): Promise<Authorizations | null>
    Extracts authorizations for technical communication scenarios based on the provided API or service plan mappers.

  • getInput(securityContext: IdentityServiceSecurityContext): AttributeInput
    Returns default input for env.env.user attributes used in all authorization checks.

  • supportsSecurityContext(securityContext: SecurityContext): boolean
    Checks if the given security context is supported, for example to skip authorization or early exits.

HybridAuthProvider
  • Implements AuthProvider<IdentityServiceSecurityContext | XsuaaSecurityContext> by extending IdentityServiceAuthProvider.
Methods:
  • constructor(ams: AMS, scopeToPolicyMapper: (ScopeMapper)
    • mapScope ((scope: string, securityContext: XsuaaSecurityContext) => string | string[] | undefined): A function that maps a consumed API to no (undefined), one (string) or multiple (string[]) fully-qualified policy name(s).
  • getAuthorizations(securityContext: IdentityServiceSecurityContext | XsuaaSecurityContext): Promise<Authorizations>
    • For XsuaaSecurityContext: Maps token scopes to policies and identifies the tenant using the zid field.
    • For IdentityServiceSecurityContext: Delegates to the base class implementation.

CdsXssecAuthProvider
  • Implements CdsAuthProvider<CdsContext> for CdsContexts with an @sap/xssec SecurityContext in cdsContext.http.req.authInfo.
Public Properties
  • xssecAuthProvider The XssecAuthProvider implementation used to build Authorizations from the SecurityContext. Can be customized or replaced with a custom implementation.
Methods
  • getAuthorizations(cdsContext: CdsContext): Promise<Authorizations>
    Retrieves the SecurityContext from cdsContext.http.req.authInfo and uses xssecAuthProvider to build Authorizations from it.

  • getCdsInput(cdsContext: CdsContext, definition: @sap/cds.linked.LinkedDefinitions, event: string): AttributeInput
    Returns default input for AMS attributes used in all authorization checks. By default, returns the input provided by xssecAuthProvider but can be overwritten with an implementation that returns custom input when authorizing requests for the given cds event on the given cds model definition.

  • supportsCdsContext(cdsContext: CdsContext): boolean
    Checks if the given cds context is supported to be handled by this implementation, for example to skip authorization or early exits.

Authorizations

An abstract representation of authorizations determined by the strategy of the AuthProvider from which it was constructed.

Methods
  • constructor(ams: AuthorizationManagementService, policySet: PolicySet, context: any): Authorizations

  • checkPrivilege(action: string, resource: string, input?: AttributeInput): Decision
    Checks if the action is allowed on the resource.

    • input (AttributeInput, optional): A flat input object that grounds fully-qualified attribute names to values, for example { "$app.product.category" : "accessory" }. Attributes that are not grounded in the input are considered unknown and may result in a conditional Decision.
  • getPotentialResources(): Set<string>
    Collects all resources for which at least one action is potentially granted, ignoring conditions.

  • getPotentialActions(resource: string): Set<string>
    Collects all actions that are potentially granted for a given resource, ignoring conditions.

  • getPotentialPrivileges(): Array<{action: string, resource: string}>
    Collects all action/resource combinations that are potentially granted, ignoring conditions.

  • withDefaultInput(input: AttributeInput): Authorizations
    Sets default input used for all authorization checks.

    • input (AttributeInput, optional): A flat input object that grounds fully-qualified attribute names to values, for example { "env.env.user.origin" : "EU" }
  • limitedTo(other: Authorizations): Authorizations
    Limits the authorizations of this instance to the authorizations of another instance. Subsequent authorization checks on this instance will use the logical intersection of its authorizations and those of the other Authorization instances.


Decision

Represents the result of an authorization check. A decision can be in one of three states: granted, denied, or conditional.

Methods
  • isGranted(): boolean
    Returns true if the authorization check resulted in a definitive GRANT with no outstanding conditions.

  • isDenied(): boolean
    Returns true if the authorization check resulted in a definitive DENY with no outstanding conditions.

  • <T,V>visit(visitCall: CallVisitor, visitValue: ValueVisitor) : T This method can be used to visit the condition tree bottom-up. The visitor calls visitValue whenever it encounters a value (attribute reference or literal) or visitCall when it encounters a function call in the condition, for example a call to the "EQ" function to compare two arguments for equality.

    • visitCall ((call : string, args : (DcnReference|DcnValue|V)[]) => T): A function that visits the given call and its arguments, for example to transform ("EQ", args) => "args[0] = args[1]". The call names are the constants from DclConstants.operators.
    • transformValue ((value : DcnReference|DcnValue) => DcnReference|DcnValue|V): A function that visits the given attribute reference or literal, for example to translate AMS references to database field names.
    • {{ref:string}} DcnReference
    • {number|string|boolean|number[]|string[]|boolean[]} DcnValue
  • filterUnknown(unknowns: string[]): Decision
    Returns a new Decision instance that is the result of keeping only the fully-qualified attributes as unknown, evaluating the remaining attributes as unset.

  • apply(flatInput: { [attributeName: string]: DcnValue }): Decision
    EXPERIMENTAL: If you plan to use this method in production, please open a ServiceNow ticket on component BC-CP-CF-SEC-LIB. Uses the data provided in flatInput to create a new Decision. Simple example on a decision d that represents a = 3 and b = 4:

    d.apply({ a: 3 }) // returns a Decision that represents b=4
    d.apply({ a: 3, b: 4 }) // returns a Decision that represents true
    d.apply({ a: 1 }) // returns a Decision that represents false
    d.apply({ a:3 }).apply({ b: 4 }) // returns a Decision that represents true
Events

Instances of AuthorizationManagementService emit the following events to which consumers can subscribe via the on(eventName: string, function(event: AmsEvent) : void) method.

  • authorizationCheck: Emitted during various authorization operations by the methods of Authorizations. The event object contains the following properties based on the type of operation:

    • type: The type of the event. Possible values are:
      • "checkPrivilege": Emitted during a privilege check. Additional payload:
        • action: The action being checked.
        • resource: The resource being checked.
        • input: The input used for the authorization check.
        • decision: The decision of the authorization check.
      • "getPotentialActions": Emitted when collecting potential actions for a resource. Additional payload:
        • resource: The resource for which actions are being collected.
        • potentialActions: The set of actions that are potentially granted for the given resource.
      • "getPotentialResources": Emitted when collecting potential resources. Additional payload:
        • potentialResources: The set of resources for which at least one action is potentially granted.
      • "getPotentialPrivileges": Emitted when collecting potential privileges. Additional payload:
        • potentialPrivileges: The list of potentially granted privileges, each containing:
          • action: The action.
          • resource: The resource.
    • authorizations: The Authorizations instance that triggered the event.
    • context: The context of the event from which the Authorizations instance was created.
  • error: Emitted when an error occurs in a background operation. The event object contains the following properties:

    • type: The type of the event. Possible values are:
      • "bundleRefreshError": Emitted when the BundleLoader fails to refresh the current policies and assignments bundle, for example due to a failed request to the AMS server. This event is not emitted when the initial loading fails. Use the whenReady method instead to check for the initial readiness of AMS.
    • error: The AmsError instance that describes the error.

CAP integration

AMS can be used for authorization in CAP applications to provide both role and instance-based authorization management at runtime. The integration is based on the standard cds annotations for authorization via roles and optional ams-specific annotations for instance-based authorization filters.

For production, AMS is meant to be used with SAP Cloud Identity Services as authentication solution but mocked authentication can be used to test authorization without the need for SAP Cloud Identity Services tokens. This is useful when the application is started locally or to execute automated tests.

When deployed, the application's authorization policies are managed in your application using the administration console of SAP Cloud Identity Services. During development, policies can be edited in the IDE and assigned to mocked users via the cds env configuration of non-production profiles.

The plugin runtime has the following expectations on the project environment. If your projects differs from this, for example due to a custom auth middleware, you can customize the plugin via cds env configuration and the plugin runtime configuration.

DefaultValueCustomize
SAP Cloud Identity Services credentials locationcds.env.requires.auth.credentialsProvide credentials manually
amsPluginRuntime.authProvider.xssecAuthProviderDefaults to IdentityServiceAuthProviderReplace default XssecAuthProvider
@sap/xssec SecurityContext locationIdentityServiceSecurityContext expected under cds.context.http.req.authInfoReplace default CdsAuthProvider
amsPluginRuntime.authProviderDefaults to CdsXssecAuthProviderReplace default CdsAuthProvider
cds add ams

The cds add ams command configures the application for AMS.

It installs both the AMS runtime plugin for cds (@sap/ams) and the AMS development plugin for cds (@sap/ams-dev):

npm i @sap/ams
npm i --save-dev @sap/ams-dev

Additionally, it configures the application's deployment artefacts (mta, helm, cf-manifest) for AMS, for example by adding configuration for the ams policy deployer application.

Features
Role-based authorization

AMS can be used to assign roles from the cds authorization model to users via authorization policies. For example, the following policy would grant the Admin role when assigned to a user:

POLICY Admin {
  ASSIGN ROLE Admin;
}

The AMS plugin implements a middleware that computes the roles of SAP Cloud Identity Services users before each request by overriding the user.is function.

Instance-based authorization

Policies that assign roles can be extended with attribute filters for instance-based authorization. This allows administrators to create custom policies at runtime for fine-grained control. This is most useful to give customer administrators in multi-tenant applications fine-grained control over their user's rights.

Via @ams.attributes annotations, the AMS attributes are mapped to elements (or association paths) in the cds model. Whenever requests access cds resources with those elements, the result is filtered based on the attribute conditions computed by AMS. The conditions are based on the WHERE condition behind role assignments in policies.

ams.attributes annotations are supported on aspects, entities and actions/functions bound to a single entity as those are the cds resources that support where conditions.

Example annotations

aspect media {
    price: Integer;
    genre: Association to Genres;
}

annotate media with @ams.attributes: {
    price: (price),
    genre: (genre.name)
};

@restrict: [{ grant:['READ'], to: ['Reader'] }]
entity Books : media {
  // ...
}

Example schema.dcl

SCHEMA {
  genre: String,
  price: Number
}

Example basePolicies.dcl

POLICY "Reader" {
    ASSIGN ROLE "Reader" WHERE genre IS NOT RESTRICTED AND price IS NOT RESTRICTED;
}

Example admin policy (created at runtime via the administration console of SAP Cloud Identity Services)

POLICY JuniorReader {
    USE "Reader" RESTRICT genre IN ('Fantasy', 'Fairy Tale'), price < 20;
}
Validation

The AMS plugin @sap/ams adds a custom build task for ams.

It validates @ams.attributes annotations for syntactic correctness and type coherence during cds build, and whenever a model is loaded if the application was started via cds serve, cds watch or cds.test. This gives early feedback about the correctness of the annotations during development:

  • validates that @ams.attributes annotations map AMS attributes syntactically correct to cds elements via expression syntax.
  • if a manually written/adjusted schema.dcl is used, validates that all AMS attributes mapped via @ams.attributes annotations exist and have a type that fits each cds element to which they are mapped.
  • if a generated schema.dcl is used, validates that the inferred type of each AMS attribute is coherent across all @ams.attributes mappings in which it is mapped to a cds element.
Base Policy Generation

Unless disabled, the AMS build task generates base policies for roles that occur in the @requires and @restrict annotations of the cds model.

Example annotation

@restrict: [{ grant:['READ'], to: ['Reader', 'Inquisitor'] }]
entity Books as projection on my.Books { *,

Example basePolicies.dcl

POLICY "Reader" {
  ASSIGN ROLE "Reader";
}

POLICY "Inquisitor" {
  ASSIGN ROLE "Inquisitor";
}

It also generates a schema.dcl that defines AMS attributes with inferred types based on @ams.attributes annotation for instance-based authorization.

ℹ️ Policy generation also occurs during cds serve, cds watch and cds.test to react to changes of cds annotations.

DCL Files that have been modified manually will not be overridden during generation to allow manual changes of the schema and base policies. To force re-generation of a generated DCL file, delete it prior to the next DCL generation.

Base Policy Upload

During cds build, a policy deployer application will be generated in <cds.build.target>/policies:

[Node.js default] gen/policies
[Java default] srv/src/gen/policies

It requires a certificate-based binding to the Identity service and must be deployed together with the application to upload the base policies to the AMS. For helm chart deployments, it can be built via containerize as a Node.js image and deployed with the content-deployment helm template.

Testing policies

The DCL package called local has a special semantic. It is meant for DCL files with policies that are only relevant for testing but not for production. Its policies are ignored during the base policy upload, even if they are contained during the upload.

For example, you can create fictitious admin policies inside this package to test whether extensions of base policies work as expected.

@sap/ams-dev automatically compiles DCL files to the DCN format which is required for local policy evaluations. This happens when the application is started via cds start, cds watch or via cds.test, so that the application should be able to do authorization checks via AMS even during development without deploying the policies first to the SAP Cloud Identity Services.

Mocked user testing

For testing and development purposes, policies can be assigned to mocked users via the cds env configuration of non-production profiles:

{
    "requires": {
        "auth": {
            "[development]": {
                "kind": "mocked",
                "users": {
                    "carol": {
                        "policies": [
                            "cap.Reader"
                        ]
                    },
                    "dave": {
                        "policies": [
                            "cap.Admin",
                            "cap.Reader"
                        ]

It is important to assign policies via their fully-qualified name which includes the DCL package (cap in this example).

Of course, you can still assign roles via the roles array directly to mocked users. Assigning policies instead of roles is mostly useful for testing instance-based authorization via AMS as the attribute filters only apply to roles assigned via AMS policies.

Hybrid testing

If autoDeployDcl is enabled when bound to an ias instance for authentication, for example during Hybrid testing, the AMS plugin uploads the base policies to the AMS server instead of compiling them to DCN. From there, they will be downloaded into the DCN engine shortly after that via polling and subsequently used for authorization checks.

Be very careful though with autoDeployDcl and do not enable it when bound against a productive system or it will override the deployed base policies with the current development state!

An application bound to an ias instance for authentication will always download its policy bundle from the corresponding AMS instance. This means, hybrid testing can be used to run an application locally with the policies from an AMS instance (including admin policies created at runtime) without overriding them. Downloading policies in hybrid mode does not require autoDeployDcl to be enabled.

Configuration

The AMS plugins are configured inside the requires.auth.ams property of the cds env.
It supports the following properties with the following [default]:

  • generateDcl true/false [true]: unless set to false, generates basePolicies.dcl and schema.dcl from the cds model (see Base Policy Generaiton)
  • dclRoot string [ams/dcl]: the root DCL folder (containing the schema.dcl) which is used for generating DCL, compiling DCL to DCN during development, uploading DCL etc.
  • dclGenerationPackage string [cap]: name of the DCL package to which basePolicies.dcl is generated
  • dcnRoot string [gen/dcn / srv/src/gen/ams/dcn (Java)]: folder for DCL to DCN compilation results during development (see Testing Policies)
  • policyDeployerRoot string [gen/policies / srv/src/gen/policies (Java)]: folder of the ams policy deployer application created during cds build (see Base Policy Upload)
  • authPushDcl true/false [false]: if enabled, uploads the base policies to the AMS server (see Hybrid testing

All AMS properties also work lowercased (for example generatedcl) and this casing has priority of the camelCase (for example generateDcl) version of properties. This means, all cds env sources including case-insensitive ones are supported such as setting properties via environment variables (CDS_REQUIRES_AUTH_AMS_GENERATEDCL) which gets mapped to lowercased versions of the property.

Plugin Runtime

It is possible to replace the following defaults in the runtime of the plugin to configure it for non-standard project environments.

Custom SAP Cloud Identity Services credential location

If the SAP Cloud Identity Services credentials are not available under the default location (cds.env.requires.auth.credentials), you need to manually provide them:

server.js

const { amsCapPluginRuntime } = require("@sap/ams");

amsCapPluginRuntime.credentials = { ... } // manually provide the SAP Cloud Identity Services credentials from service binding
Custom XssecAuthProvider

It is possible to override the XssecAuthProvider implementation used by the default CdsAuthProvider internally to a different implementation. For example, the following snippet shows how it can be replaced in projects that authenticate both via SAP Cloud Identity Services and XSUAA.

server.js

const { amsCapPluginRuntime, HybridAuthProvider } = require("@sap/ams");

const mapScope = (scope, securityContext) => scope; // your custom scope to policy mapper
amsCapPluginRuntime.authProvider.xssecAuthProvider = new HybridAuthProvider(amsCapPluginRuntime.ams, mapScope) // authorization for both SAP Cloud Identity Services and XSUAA tokens
Custom CdsAuthProvider

server.js

const { amsCapPluginRuntime } = require("@sap/ams");

amsCapPluginRuntime.authProvider = new MyCustomCdsAuthProvider(); // your custom CdsAuthProvider implementation if you do not authorize based on @sap/xssec SecurityContexts
Technical communication

By default, the plugin runtime uses an IdentityServiceAuthProvider which supports technical communication via SAP Cloud Identity Services out-of-the-box. You can access it as follows in the default plugin runtime to configure which policies to use for technical communication scenarios:

const { amsCapPluginRuntime, TECHNICAL_USER_FLOW, PRINCIPAL_PROPAGATION_FLOW } = require("@sap/ams");
const { mapTechnicalUserApi, mapPrincipalPropagationApi } = require('../ams/apis.js'); // your custom API mappers

const identityServiceAuthProvider = amsCapPluginRuntime.authProvider.xssecAuthProvider;
identityServiceAuthProvider
  .withApiMapper(mapTechnicalUserApi, TECHNICAL_USER_FLOW)
  .withApiMapper(mapPrincipalPropagationApi, PRINCIPAL_PROPAGATION_FLOW);
Logging

The AMS CAP plugins log to namespace ams in CAP. To see debug logs during development, turn it on for this namespace, for example via

DEBUG=ams cds watch

Deploy DCL

The DCL bundle is typically deployed together with the application to ensure the application's authorization checks are always done with the most current set of policies.

DCL Deployer Application

The recommended way to deploy DCL, is by deploying a minimal Node.js* application along with your application that contains the DCL bundle and has a service binding to the target SAP Cloud Identity Services instance.

This module provides a ready-to-use package.json for such an application:

{
  "name": "ams-dcl-content-deployer",
  "version": "2.0.0",
  "dependencies": {
    "@sap/ams": "^2"
  },
  "engines": {
    "node": ">=18"
  },
  "scripts": {
    "start": "npx --package=@sap/ams deploy-dcl"
  }
}

It expects to find the DCL bundle in a folder called dcl next to the package.json. As you can see, the application's start script simply calls the deploy-dcl script of this module. Afterwards, it exits with exit code 0 (success) or 1 (error).

* A Node.js installation is not required during development, so this method also works nicely for applications written in other languages such as Java.

Building the DCL Deployer Application
  1. Create a new folder for the Deployer application with the ready-to-use package.json.
  2. Extend your build script to copy your DCL root folder to the dcl folder of your Deployer application
Deploying the DCL Deployer Application

It depends on the target platform and deployment method how best to deploy the DCL Deployer Application alongside your application. Below is a list of templates for the most common scenarios.

Make sure to always bind the DCL deployer to the Identity service instance with a certificate-based service binding because this is required by the AMS server for authentication.

MTA


The following entry defines a module that registers and executes a CF task to deploy the DCL bundle and shuts down on success to free resources.

mta.yaml

modules:
  - name: {{appName}}-ams-policies-deployer
      type: javascript.nodejs
      path: {{dclDeployerAppFolder}}
      parameters:
        buildpack: nodejs_buildpack
        no-route: true
        no-start: true
        tasks:
          - name: deploy-dcl
            command: npm start
            memory: 512M
      requires:
        - name: {{identityServiceInstanceName}}
          parameters:
            config:
              credential-type: X509_GENERATED
              app-identifier: policy-deployer
CF Manifest


Unlike MTAs, CF manifests do not support the execution of CF tasks and CF considers applications as crashed, even when their process exits with status code 0. For this reason, the deployer application needs to idle and be manually stopped after the DCL deployment. It will report about success or failure in its logs.

manifest.yml

applications:
  - name: {{appName}}-ams-policies-deployer
    path: {{dclDeployerAppFolder}}
    no-route: true
    health-check-type: none
    memory: 256M
    instances: 1
    buildpack: nodejs_buildpack
    command: (npm start && echo "This application may now be stopped to free resources." || echo "AMS policy deployment unsuccessful.") && sleep infinity
    services:
      - name: {{identityServiceInstanceName}}
        parameters:
          credential-type: X509_GENERATED
          app-identifier: policy-deployer
Unified Runtime Helm Charts Build and deploy an image from your Application deployer and replace {{YourAmsDclDeployerImage}} below with its URL.


Charts.yaml

dependencies:
    # ...

  - name: content-deployment
    alias: ams-policies-deployer
    version: ">0.0.0"

values.yaml

# ...

ams-policies-deployer:
    image:
        repository: {{YourAmsDclDeployerImage}}
    bindings:
        identity:
            serviceInstanceName: {{identityServiceInstanceName}}
            parameters:
                credential-type: X509_GENERATED
                app-identifier: policy-deployer
Kubernetes Job Build and deploy an image from your Application deployer and replace {{YourAmsDclDeployerImage}} below with its URL.


ams-dcl-deployer.yml

apiVersion: batch/v1
kind: Job
metadata:
  name: {{appName}}-ams-policies-deployer
spec:
  completions: 1
  parallelism: 1
  ttlSecondsAfterFinished: 1209600
  template:
    spec:
      imagePullSecrets:
        - name: {{imagePullSecret}}
      containers:
      - image: {{YourAmsDclDeployerImage}}
        name: ams-policies-deployer
        env:
        - name: SERVICE_BINDING_ROOT
          value: /bindings
        securityContext:
          allowPrivilegeEscalation: false
          capabilities:
            drop:
            - ALL
          privileged: false
          runAsNonRoot: true
          readOnlyRootFilesystem: false
        volumeMounts:        
        - mountPath: /bindings/identity/
          name: identity-binding
          readOnly: true
      restartPolicy: OnFailure
      volumes:      
      - name: identity-binding
        secret:
          secretName: {{certBasedIdentityBinding}}
deploy-dcl script

The script pushes a DCL bundle (including schema.dcl, DCL root package and all subpackages) to the Identity service instance from the environment (see deploy-dcl --help):

Usage: deploy-dcl -d [DCL_ROOT_DIR] -c [CREDENTIALS_FILE] -n [DEPLOYER_APP_NAME]

Options:
      --help         Show help                                         [boolean]
      --version      Show version number                               [boolean]
  -d, --dcl          [optional] path to the directory that contains the DCL root
                     package. If a path is provided via environment variable
                     AMS_DCL_ROOT, it overrides this option.
                                                       [string] [default: "dcl"]
  -c, --credentials  [optional] path to a JSON file containing the credentials
                     object of an Identity service binding. If omitted, will try
                     to find and use an Identity service binding from the
                     process environment.                               [string]
  -n, --name         [optional] a descriptive name of this deployer application
                     to trace back the currently deployed DCL bundle on the AMS
                     server to its source when DCL is deployed from more than
                     one source. If a name is provided directly via environment
                     variable AMS_APP_NAME or indirectly as application_name via
                     VCAP_APPLICATION on Cloud Foundry or the pod name on K8s,
                     it overrides this option.
                                   [string] [default: "@sap/ams:deploy-dcl"]

Examples:
  deploy-dcl                                Pushes the DCL content in ./dcl
                                            (including schema.dcl, DCL root
                                            package and all subpackages) to the
                                            identity service instance from the
                                            environment.
  deploy-dcl -d src/dcl -c config/ias.json  Pushes the DCL content from
  -n bookshop-dcl-deployer                  ./src/dcl using the SAP Cloud Identity Services
                                            credentials in ./config/ias.json.
                                            The deployer app name for this
                                            upload will be set to
                                            "bookshop-dcl-deployer" to be able
                                            to trace back the upload source to
                                            this deployer.

Resources

Getting Support

As registered SAP customers, report your issue in creating a ticket for component BC-CP-CF-SEC-LIB on the SAP Support Portal See also Getting Support in the SAP BTP documentation.

Note that consulting can not be offered via the support channels unless it is part of a customer's service plan.

SAP Cloud Identity 1.0

SAP DEVELOPER LICENSE AGREEMENT 3.2, read licence

History

Latest

v3.10.0

Other 2

Notes
  • Finalized the HybridAuthProvider with combined authorization functionality for AMS applications with XSUAA legacy. A usage guide will eventually follow in the SCI Developer Guide.
  • Fix DCN version check to accept both version "1" and 1 for improved resilience with previous compilation results.
  1. v3.9.0

    Other 1

    Notes
    • Added support for SAP "act-as" support users: IdentityServiceAuthProvider now builds Authorizations with a preference for claims from the sap_support_act_as claim structure over top-level claims.
  2. v3.8.0

    Other 5

    Notes
    • IdentityServiceAuthProvider now populates any String/String[] $user attributes from the AMS schema based on token claims with the same name (e.g. department -> user.department),notjustthedefault‘user.department), not just the default `user` attributes.
    • The IdentityServiceBundleLoader now uses a default request timeout of 30s
    • AuthorizationManagementService#getPolicyAssignments is now explicitly marked as Internal/Deprecated API. To be safe from breaking changes if the bundle distribution architecture is changed, please use IdentityServiceAuthProvider#getAuthorizations instead to construct an Authorizations object for named users.
    • Added a check to reject DCN versions != 1
    • [CAP] Changed error message for when plugin configuration is missing on startup
  3. v3.7.0

    Other 7

    Notes
    • [CAP] Support additional CXL operators (NOT_LIKE, IS_NULL, IS_NOT_NULL, BETWEEN, NOT_BETWEEN) when translating DCL operators to CXL.
    • Fix: [CAP] Fixed merging of generated CXL condition with static where conditions when static conditions have complex format (e.g. EXISTS predicates).
    • Fix: [CAP] Relative paths are now resolved from cds.root instead of the current working directory to allow running cds build from a different folder than the project root.
    • Fix: Policies that USE with multiple RESTRICT now have correct OR semantics across the restrictions instead of OR semantics across restriction predicates of individual attributes.
    • Fix: Fixed missing JsDoc type definitions to fix generated typescript definition files.
    • Fix: When no error listeners are registered, the log level of failed bundle refresh requests was changed to WARN from ERROR (initial bundle fetch errors are still logged with ERROR severity).
    • Added check for supported DCN version of bundle.
  4. v3.6.0

    Other 2

    Notes
    • Feature: added configuration option for fetching authorization bundles from an AMS Edge Service.
    • Fix: [CAP] prevent base policy generation for internal-user pseudo role.
  5. v3.5.1

    Other 4

    Notes
    • use authorization_bundle_url from credentials instead of hard-coded /bundle-gateway endpoint for AMS bundle download
    • send user-agent header during AMS bundle download with value @sap/ams/<version> to allow better identification of the client in AMS server logs for support purposes
    • send x-correlation-id header during AMS bundle download with a random UUID value to allow correlating AMS bundle download requests with error logs for support purposes
    • AuthorizationManagementService#fromIdentityService(identityService, config) now correctly forwards the config object to the authorization bundle loader. Added type definitions for config options.
  6. v3.5.0

    Other 6

    Notes
    • Fix: Catch request errors such as TLS certificate expiration errors during AMS bundle download and emit them via "bundleInitializationError" or "bundleRefreshError" events
    • Fix: Duplicated log output in CAP applications
    • improve bundle download error messages to include relevant information for support, such as bundle URL and region
    • IdentityServiceAuthProvider#withApiMapper and IdentityServiceAuthProvider#withServicePlanMapper now also accept plain objects for mapping APIs/service plans to policies as a simpler alternative to mapper functions.
    • ignore "local" DCL sub-packages during bundle upload case-insensitively
    • ignore legacy DCL test files ending in _test.dcl during bundle upload
  7. v3.4.0

    Other 6

    Notes
    • Removed some unused npm dependencies
    • Fix: AuthorizationManagementService no longer emits "error" events on failed bundle requests when no listeners are registered. Instead, it logs the error to console.error.
    • [CAP] Fix: use cds.context.user.authInfo instead of deprecated cds.context.http.req.authInfo if available (@sap/cds >= 9.3.0) to avoid deprecation warning
    • [CAP] Fix: During cds serve|watch|test in production profile, the CSN model is no longer traversed to validate AMS annotations or generate DCL at server start (only in development profile). During cds build, the model is still traversed regardless of the profile.
    • [CAP] Removed requires.auth.ams.cache default configuration for cds env as a cache has no longer been necessary since version 2.0.0.
    • [CAP] Added requires.auth.generatePoliciesDeployer configuration property (default: auto) that can be set to false to disable generation of an ams policy deployer application during cds build in applications that use a dedicated deployer application instead of the main application for deploying DCL files. In a future release, the auto option may receive intelligent behavior to detect whether a deployer application is required or not, while true can be used to enforce it.
  8. v3.3.1

    Other 2

    Notes
    • IdentityServiceAuthProvider now fills userinputwithoutuser input without env prefix which is semantically equal but more concise.
    • AuthorizationManagementService now emits different "error" events depending on its readiness state: bundleInitializationError or bundleRefreshError. The latter contains a new secondsSinceLastRefresh property.
  9. v3.3.0

    Other 3

    Notes
    • Make API Permission Group -> Policy Mapper optional for app2app principal propagation flow (error log messages reduced to debug level)
    • Simplify attribute input handling in Authorizations#checkPrivilege method, so attribute names work the same as in DCL where appandapp and env prefixes are inferred automatically
    • Fix getPotentialActions and getPotentialResources methods in app2app principal propagation flow
  10. v3.2.0

    Other 6

    Notes
    • IdentityServiceAuthProvider now has special handling for API consumption of principal-propagation API by not limiting user authorizations to policies of consumed API(s) in this case
    • much improved DEBUG logging
    • authorizationCheck events now have additional relevant properties and log better to console
    • various fixes in error handlers
    • internal values of TECHNICAL_USER_FLOW and PRINCIPAL_PROPAGATION_FLOW changed from a Symbol to string constants for better loggability
    • fix type definition of callName to be one of several lowercased instead of uppercased call names in first callback of Decision#visit
  11. v3.1.3

    Other 3

    Notes
    • Fix in TarReader for AMS Bundle Download
    • Fix error handling in IdentityServiceAuthProvider
    • Fix error handling in CAP Build Plugin
  12. v3.1.2

    Other 4

    Notes
    • Fix: Do not throw error from IdentityServiceAuthProvider#getAuthorizations for not yet supported token scenarios (e.g. internal client_credentials token). Instead, return an Authorizations object with 0 policies.
    • Typescript improvements for Decision#visit
    • fix LICENSE file
    • fix start command path in ams-dcl-content-deployer Dockerfile for version 3
  13. v3.1.1

    Other 1

    Notes
    • provide Typescript typings
  14. v3.1.0

    Other 6

    Notes
    • fix error logging in deploy-dcl script for AMS policy deployer
    • add config.start flag to AuthorizationManagementService factory methods to manually start AMS bundle load when ZTIS is used
    • fix getPotentialActions for policies that GRANT <actions> ON *.

    [CAP Node.js]

    • remove check for requires.auth.kind = 'ias' to support custom authentication middlewares without overriding AuthProvider
    • Identity Service credentials may be manually provided via amsCapPluginRuntime.credentials = ... when not available under cds.env.requires.auth.credentials.

    [CAP Java]

    • Fix error due to missing @sap/xssec dependency when using @sap/ams as cds plugin
  15. v3.0.0

    Notes

    Refactored core API for non-CAP projects.

  16. v2.4.0

    Other 1

    Notes
    • [CAP]
      • bug fixes and improvements for attribute filtering via @ams.attributes annotations
      • add support for attribute filtering of roles required by @restrict on service level
      • remove unnecessary brackets from generated CQL in where condition
  17. v2.3.0

    Other 2

    Notes
    • Improved DCL upload error logging
    • [CAP] several bug fixes for both Node.js and Java projects:
      • fix CAP Java projects requiring @sap/xssec during cds build when using @sap/ams as cds plugin
      • fix some validation errors being swallowed instead of reported
      • fix DCL generation crashing instead of throwing a proper error when a cds type cannot be inferred
      • throw meaningful error message when schema.dcl parsing fails during validation
      • add proper type validation for nested attributes (parts of nested attribute names must not be mapped to data types as they need to be a structure)
      • do CDS -> DCL compilation for DCL generation and schema validation only during dev-time and not during runtime
  18. v2.2.0

    Other 1

    Notes
    • [CAP] fix: add early exits to AMS plugin handlers to prevent errors when authenticating with technical user tokens or tokens that are not from SAP Identity Service (e.g. to make hybrid XSUAA/IAS authentication scenarios possible)
  19. v2.1.0

    Other 3

    Notes
    • [CAP Java] fix: prevent dcl root folder deletion at the beginning of cds build
    • [CAP] added dclGenerationPackage (default: cap) configuration property to change the name of the package to which basePolicies.dcl is generated.
    • DCL (sub-)packages called local are no longer included in the archive during deploy-dcl (the AMS server ignores them anyways)
  20. v2.0.0

    Other 14

    Notes
    • Added deploy-dcl script (previously in @sap/ams-dev)
    • Improved CAP integration (see Features for details)
    • Removed deprecated parameters and exports (see Breaking Changes for details)
    CAP Node.js
    • Fix roles middleware by overriding user.is instead of adding roles to user.roles which may not exist on custom auth middlewares
    • Changed default cache TTL from 20s to 15min which is used for both role computations and role-based attribute filters computed by the AMS plugin
    • Disabled cache by default in development profile
    • Removed support for instance-based authorization via @ams.publicFields annotations.
    • Added support for instance-based authorization via @ams.attributes annotations.
    • Changed default DCL generation output folder from gen/srv/ams/dcl to ams/dcl which fixes problems with the VSCode Data Control Language extension
    CAP Node.js and Java
    • Changed DCL generation algorithm. It now requires manual changes in basePolicies.dcl for applications with instance-based authorization via AMS
    • autoCompile configuration property renamed to generateDcl but for backward-compatibility, both are supported
    • dclFolder configuration property renamed to dclRoot but for backward-compatibility, both are supported
    • Removed customDclRoot / customDclFolder configuration property as there is no longer a need for a separate DCL folder with custom DCL
    • Removed tooling for copying file changes from custom policy folder to generated policy folder as it is no longer necessary to have a separate folder for custom DCL content
  21. v1.18.0

    Other 3

    Notes
    • [CAP] provide auto-configuration for AMS plugins
    • [CAP] log AMS bundle load events
    • [CAP] reduce log level of "AMS plugin not loaded" to debug
  22. v1.17.0

    Other 1

    Notes
    • [CAP] added support for cds 8

    PolicyDecisionPoint now evaluates authorization checks with a new in-process DCN engine instead of an OPA sidecar process. The url parameter of its constructor is not used anymore.

    Authorization Bundle Loading

    With the removal of the sidecar, the authorization bundle now has to be loaded into the application directly. For backwards-compatibility, the PolicyDecisionPoint constructor configures a BundeLoader for this automatically, unless an explicit BundleLoader is passed to the new, third constructor argument.
    By default, it loads the bundle from the SAP Identity Service instance to which the application is bound, e.g. when running on CF or Kyma*. For local tests, DCL can be compiled to DCN with @sap/ams-dev >= 1.0.0. When environment variable AMS_DCN_ROOT is set to the DCN output folder, the default BundleLoader will try to load the bundle from there instead.

    For details and a migration guide for your local test setup, refer to the documentation of @sap/ams-dev 1.0.0.

    *The k8s sidecar can be removed. The mount path of the apps' identity binding should follow the SAP Kubernetes Service Bindings Spec, e.g. by setting env variable SERVICE_BINDING_ROOT=/bindings and using /bindings/identity as mounth path. We strongly suggest following this new standard to enforce uniform mount paths across all services. However, technically there are alternative fixes: the mount path /etc/secrets/sapbtp/identity/auth previously required by the k8s sidecar can be changed to /etc/secrets/sapcp/identity/auth or env variable SERVICE_BINDING_ROOT=/etc/secrets/sapbtp can be used with the old path.

  23. v1.16.0

    Other 3

    Notes
    • add AmsScopeExtension for XSUAA/IAS hybrid transition stage 0
    • fire event before pdp evaluations for XSUAA/IAS hybrid transition stage 1 to set policies based on XSUAA scopes
    • [CAP] remove deprecation warning related to req.user.tenant
  24. v1.15.1

    Other 1

    Notes
    • [CAP] fix crash in RestrictionsProvider for CAP entities whose restrictions are null or undefined
  25. v1.15.0

    Other 2

    Notes
    • [CAP] add AmsEventService
    • [CAP] fire getRestrictionsEvent from AmsEventService that allows changing the attributes before they are sent to pdp
  26. v1.14.2

    Other 1

    Notes
    • provide separate README for npmjs release and clean up docs
  27. v1.14.1

    Other 1

    Notes
    • [CAP] fix IAS app_tid and scim_id access for @sap/cds 7.5.2 as the information has been removed from user.attr
  28. v1.14.0

    Other 3

    Notes
    • add @sap/cds@7.5.0 as optional peer depenency
    • [CAP] bugfix missing await in RolesMiddleware
    • [CAP] several changes for new "cds build --for ams" feature
  29. v1.13.1

    Other 1

    Notes
    • support users with empty tenant in CAP
  30. v1.13.0

    Other 2

    Notes
    • add limit for maximum entries to RolesCache. In CAP, this can be configured via requires.auth.ams.cache.limit
    • fix CAP watch mode detection under Windows file systems
  31. v1.12.0

    Other 1

    Notes
    • refactor runtime package
  32. v1.11.0

    Other 1

    Notes

    refactoring of CAP plugin:

    • _dcl_.cap file is now called entityMapping
  33. v1.10.1

    Other 1

    Notes
    • export the new functionality from 1.10.0 via index.js
  34. v1.10.0

    Other 1

    Notes
    • the API and cache for retrieving a user's roles based on specific role policies has been moved from the corresponding CAP-specific RolesMiddleware to a standalone class (RolesProvider). RolesMiddleware has been changed to configure and use RolesProvider.
  35. v1.0.9

    Other 1

    Notes
    • change warning to debug message when roles middleware is handling request without user object
  36. v1.0.8

    Other 1

    Notes
    • the cache TTL (time-to-live) of the roles middleware can now be configured in the CAP config via property requires.auth.ams.cache.TTL
  37. v1.0.7

    Other 1

    Notes
    • add runtime for AmsInstance functionality
  38. v1.0.6

    Other 1

    Notes
    • fixed cds-plugin.js missing from previous builds and releases
  39. v1.0.5

    Other 1

    Notes
    • improved logging of cds plugin
  40. v1.0.4

    Other 1

    Notes
    • convert to cds plugin
  41. v1.0.3

    Other 1

    Notes
    • small bugfixes and improvements for CAP integration
  42. v1.0.2

    Other 1

    Notes
    • small bugfixes and improvements for CAP integration
  43. v1.0.1

    Other 1

    Notes
    • small bugfixes and improvements for CAP integration
  44. v1.0.0

    Other 1

    Notes
    • add CAP integration code to src/cap
  45. v0.4.0

    Other 1

    Notes
    • update ams-dev lib
  46. v0.3.0

    Other 1

    Notes
    • update ams-dev lib
  47. v0.2.2

    Other 1

    Notes
    • fix pdp url if set from outside
  48. v0.2.1

    Other 1

    Notes
    • fix connection refused bug for node versions 17 upwards
  49. v0.2.0

    Other 1

    Notes
    • support for scim id in attributes setTokenInfo
  50. v0.1.5

    Other 1

    Notes
    • add getHealthStatus and startupCheck functions
  51. v0.1.4

    Other 1

    Notes
    • update ams-dev to version 0.2.3
  52. v0.1.3

    Other 1

    Notes
    • update ams dev lib
  53. v0.1.2

    Other 1

    Notes
    • update to new ams-compiler and opa version in ams-dev-lib
  54. v0.1.1

    Other 1

    Notes
    • updated dcl compiler to version 0.10.0
  55. v0.1.0

    Other 1

    Notes
    • Updated ams-dev lib which contained vulnerability
  56. v0.0.2

    Other 1

    Notes
    • First release
4,232downloads per week, npm
Weekly downloads for @sap/ams26 complete calendar weeks from 2026-04-20 to 2026-10-18; the latest total is 4232.20 Apr – 26 Apr: 6,41627 Apr – 3 May: 5,1854 May – 10 May: 6,13811 May – 17 May: 5,63318 May – 24 May: 7,19825 May – 31 May: 5,4531 Jun – 7 Jun: 4,2628 Jun – 14 Jun: 6,31515 Jun – 21 Jun: 7,02922 Jun – 28 Jun: 7,98829 Jun – 5 Jul: 6,7096 Jul – 12 Jul: 7,53313 Jul – 19 Jul: 7,16320 Jul – 26 Jul: 7,03227 Jul – 2 Aug: 8,2273 Aug – 9 Aug: 6,82210 Aug – 16 Aug: 7,17717 Aug – 23 Aug: 7,29524 Aug – 30 Aug: 6,94931 Aug – 6 Sept: 6,5757 Sept – 13 Sept: 4,83214 Sept – 20 Sept: 5,09021 Sept – 27 Sept: 6,23428 Sept – 4 Oct: 6,9615 Oct – 11 Oct: 6,47012 Oct – 18 Oct: 4,232
Authorization
  1. SAP Authorization and Trust Management serviceOAuth server issuing JWTs and holding scopes for BTP appsfrom BTP/BAIP
  2. OAuth 2.0 on SAP BTPOAuth 2.0 grant flows for applications and APIs in Neo regionsfrom BTP/BAIP
  3. com.sap.cds:cds-services-bomMaven bill of materials pinning CAP Java module versionsfrom CAP
  4. cap-toolkitUtility bundle for CAP handlers: builder, roles, validation, queriesfrom CAP
  5. @sap/ams-devCompiler from AMS DCL policies to DCN for local runs and testsfrom CAP
  6. @sap/cdsCAP Node.js runtimefrom CAP
  7. sap-usi-authority-checkAuthority check helper class used across SchwarzIT's USI reportsfrom ABAP
  8. cds-entra-idMaps Microsoft Entra ID groups and app roles onto cds.User rolesfrom CAP

Details

Sources5
npm registrydiscovered here, npm:scope:@sapchecked
npm registrydiscovered here, npm:cds-pluginchecked
npm registrydiscovered here, npm:sap cap pluginchecked
npm registry, @sap/amsversion, releases, installschecked
README.mdquoted, and what the entry declareschecked

Sources are graph entities: the same page may back several entries, and an unreachable source flags every row that rests on it.

Compatibility and provenance
runtimesnode
declared for>=7.5
latestv3.10.0
first release
releases and cadence29, ~52d median
discovered vianpm registry · npm:scope:@sap, npm registry · npm:cds-plugin, npm registry · npm:sap cap plugin
first seen in the atlas
ecosystem and domaincap, security-and-compliance
Flavors1
Node.js
“This is the Node.Js runtime library used to perform authorization checks in applications which authenticate users via the SAP Cloud Identity Services.” — @sap/ams 3.9.0 — READMEchecked
History in the atlas1
  1. First seen.
For your agent