## SAML delegation

Some advanced SAML use cases involve a single logical transaction that spans one or more intermediate
clients or servers. A common example includes a SAML-enabled web site acting on behalf of a logged-in
user while accessing additional SAML-enabled services, which are not directly accessible 
by the user agent, e.g. a database. Generalizing this example, a number of intermediaries might be 
traversed before the final point of access. Popular ways of making this happen are
__SAML impersonation__, __SAML assertion forwarding__ and __SAML IdP proxy__.

All of them suck:

* SAML impersonation forces principal to disclose credentials to an SP.
* SAML forwarding makes IdP lose track of who and when is using forwarded assertions.
* IdP proxy requires a second IdP in exotic configuration.

When a SAML assertion is used as a security token to authenticate/authorize people and software 
against a mission-critical service, it is important that the identities and order of intermediaries,
if any, are expressed within the token in some fashion.

__SAML assertion delegation__ moves beyond the forwarding scenario by adding information to the 
assertion that explicitly identifies the chain of parties through which a transaction flows.
Delegation assures that all requests in the chain are routed back through the identity provider at 
each hop to cryptographically guarantee that each party has been authenticated and appropriate 
policy enforced. This finegrained and real-time enforcement capability is a key advantage over 
pure SAML forwarding and impersonation, at a price of additional back-channel operation for 
each delegation hop. 

[__Shibboleth Identity Provider__]() implements SAML 2.0 profile for assertion delegation (Liberty/IDWSF).

__hana-saml-wsse__ is the corresponding client. It also implements an __ECP__ client, which is handy 
for testing your delegation configuration, but can be very useful in its own right, e.g.
if you are implementing impersonation or fowarding model.

The package name is historical; the client has been originally implemented for a specific use case 
that involved a SAP HANA database backend. Making Shibboleth delegation work with SAP HANA requires
additional IdP configuration, which is not covered here. 

## Compatibility

This implementation is known to work with Shibboleth IdP 3.2. There is some indication that ECP 
and ID-WSF profiles are supported by some other open source and commercial IdP
systems, but none of them were tested.

## X.509 authentication

As it should be clear from the example below, ID-WSF requires that your IdP is configured to support
__X.509 client certificate authentication__. The same applies to all TLS middleware you might have 
in front of your IdP, e.g. nginx, httpd, netscaler, etc. This is at least as complicated as it
sounds, so good luck. Good starting points are:

* [Tomcat SSLValve](https://tomcat.apache.org/tomcat-8.0-doc/api/org/apache/catalina/valves/SSLValve.html)
* [X.509 Client-Side Certificate Auth with Nginx](http://nategood.com/client-side-certificate-authentication-in-ngi)

> Things get easier if you want to use this library in ECP mode. Although ECP *does* support X.509 auth,
> it is optional (you can use basic HTTP auth method).

## Security

- The client signs all outgoing AuthRequests.
- The client expects incoming assertions to be both encrypted and signed.
- `inResponseTo` validation is supported and enabled by default.
- `NotBeforeOrAfter` is not validated, but is returned in `assertionInfo` object.
- `wsa` profile does not work over plain HTTP, and never will.
- `ecp` mode _should_ work over plain HTTP, but this is a very bad idea. 

## Install

```
$ npm install hana-saml-wsse
```

## IdP configuration

The following configuration snippet assumes the following scenario:

- A Service Provider idendified as `webserver-sp` is allowed to obtain a 
delegatable assertion using ECP at any time. Assertion is valid for 10 hours.
- By itself, a delegatable assertion in not usable by any other SP other than 
`webserver-sp` as its `Audience` restriction is limited to `webserver-sp`.
- However, for as long as delegatable assertion remains valid, `webserver-sp` can 
request additional, "delegated" assertions which will be valid for `database-sp`,
each valid for 60 seconds. These delegated assertions are no further delegatable, 
i.e. `database-sp` is the final point of access.

___

> Note that, while requesting a delegated assertion, `webserver-sp` does not need
> to present actual credentials of the user (generally, username and password), and it 
> is not expected to have them - instead, it presents a delegatable assertion as the 
> means of confirming that it has the authority to impersonate that user on `database-sp`
> or elsewhere. The communication takes place over authenticated TLS channel, i.e. 
> IdP uses TLS to ensure it is actually talking to the SP to which the delegatable
> assertion was originally issued. __In essence, this is the whole idea of how 
> assertion delegation works__.
___

```xml
<!-- conf/relying-party.xml -->

<!-- 
     "delegation-predicate" is a reference to a bean that implements
     com.google.common.base.Predicate<ProfileRequestContext<?,?>> interface.
     It can be used to implement additional custom logic to selectively allow
     or disallow delegation. In the most basic case, you want to implement a predicate that
     always returns true.
-->

<bean parent="RelyingPartyByName" c:relyingPartyIds="#{{ 'webserver-sp' }}">
  <property name="profileConfigurations">
    <list>
      <!-- serve long-lived delegatable assertions via ECP -->
      <bean id="SAML2.ECP"
        class="net.shibboleth.idp.saml.saml2.profile.config.ECPProfileConfiguration"
        p:inboundInterceptorFlows="security-policy/saml2-ecp"
        p:allowDelegation-ref="delegation-predicate"
        p:assertionLifetime="PT600M"
      />
      <!-- serve short-lived delegated assertions via ID-WSF -->
      <bean id="Liberty.SSOS"
        class="net.shibboleth.idp.saml.idwsf.profile.config.SSOSProfileConfiguration"
        p:inboundInterceptorFlows="security-policy/saml2-idwsf-ssos"
        p:maximumTokenDelegationChainLength="1"
        p:allowDelegation="false"
        p:delegationPredicate-ref="delegation-predicate"
        p:additionalAudiencesForAssertion="#{{ 'database-sp' }}"
        p:assertionLifetime="PT1M"
      />
     </list>
  </property>
</bean>
```

## SP configuration

SP metadata must inform IdP that SP is ready and willing to consume delegatable assertions,
as shown below. The `Location` attribute of `AssertionConsumerService` must match `consumerURL` parameter
of `hana-saml-wsse` client configuration, but this is a formality as SP is not expected
to actually respond on that URL. 

```xml
...
<!-- SSOS -->
<AssertionConsumerService
  Binding="urn:oasis:names:tc:SAML:2.0:bindings:PAOS"
  Location="https://my.org/Liberty/SSOS"/>

<AttributeConsumingService>
  <RequestedAttribute
    NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
    Name="urn:liberty:ssos:2006-08"
    FriendlyName="assertionDelegation"
    isRequired="false" />
</AttributeConsumingService>
...
```

## Usage

The example below matches the IdP configuration above and:

1. Binds to your Identity Provider's ECP endpoint using TLS transport.
2. Authenticates using either user/password or X.509 certificate of the user.
3. Retrieves, verifies and decrypts a delegatable assertion.
4. Creates an ID-WSF AuthRequest using delegatable assertion as a security token.
5. Binds to the ID-WSF endpoint using TLS transport.
6. Authenticates using X.509 certificate of the SP.
7. Retrieves, verifies and decrypts a delegate assertion.
8. Tests it by using it as a security token to connect to a SAP HANA backend.
9. Optionally repeats steps 4-7 every `deleg_test_repeat_ms` milliseconds.
___

```javascript
// test.js
var
  hdb = require('hdb'),
  precise = require('precise'),
  moment = require('moment'),
  xmlfmt = require('xmlfmt'),
  WSS = require('hana-saml-wsse')
;
 
var
  deleg_test_repeat_ms = 3000,
  idpHost = 'idphost',
  idpPort = 443,
  http_ua = 'hana-wss-client/1.0',
  hdb_conf = {
    host: 'hanahost',
    port: 30015
  }
;
 
var conf = {
  user         : 'tj_holowaychuk',
  pass         : null, // leave blank for TLS CCA (@see user_key/user_cert) 

  idpHost      : idpHost,
  idpPort      : idpPort,

  idpId        : 'idp-id',
  spId         : 'webserver-sp',

  url: { 
    ecp        : '/idp/profile/SAML2/SOAP/ECP',
    wsa        : '/idp/profile/IDWSF/SSOS'
  },

  consumerURL  : 'https://my.org/Liberty/SSOS',

  idp_cert     : './idp.pem',

  // used both for signing and X.509 auth (WSA only)
  sp_key       : './sp_private_key.pem',
  sp_cert      : './sp_public_key.pem',

  // optional TLS CCA authentication (ECP only) 
  user_key     : './user.key',
  user_cert    : './user.crt',

  sig_alg      : 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',

  tls_opt: {
    hostname   : idpHost,
    port       : idpPort,
    method     : 'POST',
    headers    : {
      'Content-Type'      : 'text/xml',
      'Transfer-Encoding' : 'chunked',
      'User-Agent'        : http_ua
    },
    // die on bad IdP cert 
    rejectUnauthorized: true
  },

  log: console.log
};

var client = new WSS.client(conf);

function hdbtest(assertion, cb) {
  var hdbclient = hdb.createClient(hdb_conf);
  hdbclient.connect({ assertion: assertion }, (err) => {
    if (err) {
      console.error('[hdb] error:', err);
    } else {
      console.log('[hdb] i am', hdbclient.get('user'));
    }
    hdbclient.end();
    cb && cb(err);
  });
}

client.get('ecp', (err, delegatableAssertion, assertionInfo) => {
  if (err)
    return conf.log('[ecp] error:', err);

  conf.log('[ecp] rcvd delegatable assertion, expires',
    moment(assertionInfo.notOnOrAfter).fromNow());

  //conf.log(xmlfmt(delegatableAssertion))

  var delegator = () => {
    var timer = precise().start();
    client.get('wsa', (err, assertion, assertionInfo) => {
      if (err)
        return conf.log('[wsa] error:', err);

      //conf.log(xmlfmt(assertion));
      //conf.log(assertion);

      conf.log('[wsa] rcvd delegated assertion in',
        (timer.stop().diff()/1000000000).toFixed(2) + 's,',
        'expires', moment(assertionInfo.notOnOrAfter).fromNow());

      hdbtest(assertion, () => {
        if(!deleg_test_repeat_ms)
          process.exit(0);
        });
      }, delegatableAssertion);
  };

  if (deleg_test_repeat_ms)
    setInterval(delegator, deleg_test_repeat_ms);
  else
    delegator();
}); 

//:~
```

You should get something like:

```
$ node test.js

[ecp] using tls cca with user key
[ecp] rcvd delegatable assertion, expires in 10 hours
[wsa] using tls cca with SP key
[wsa] rcvd delegated assertion in 0.22s, expires in a minute
[hdb] i am tj_holowaychuk
[wsa] using tls cca with SP key
[wsa] rcvd delegated assertion in 0.14s, expires in a minute
[hdb] i am tj_holowaychuk
[wsa] using tls cca with SP key
[wsa] rcvd delegated assertion in 0.16s, expires in a minute
[hdb] i am tj_holowaychuk
[wsa] using tls cca with SP key
[wsa] rcvd delegated assertion in 0.11s, expires in a minute
[hdb] i am tj_holowaychuk
[wsa] using tls cca with SP key
[wsa] rcvd delegated assertion in 0.14s, expires in a minute
^C

```

## Recommended reading

SAML specs are fun:

* [Overview of SAML assertion delegation scenarios](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-delegation-cs-01.pdf)
* [SAML V2.0 Enhanced Client or Proxy (ECP)](https://wiki.oasis-open.org/security/SAML2EnhancedClientProfile)
* [WS-Security SAML Token](http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0.pdf)
* [SAML Metadata Specification](https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf)
* [IDWSF-SAML Specification](http://www.projectliberty.org/resource_center/specifications/liberty_alliance_id_wsf_2_0_specifications/)
* [Understanding WS-Security](https://msdn.microsoft.com/en-us/library/ms977327.aspx)
* [WSA SOAP binding](https://www.w3.org/TR/2006/REC-ws-addr-soap-20060509/)
* [urn:oasis:names:tc:SAML:2.0:cm:holder-of-key](http://hdknr.github.io/docs/identity/SamlHokProfile.html)

## License

MIT. Use at your own risk. As with all things SAML, always be sure you know what you are doing.
