Repository: nats-io/nats-server (go)

Issue:
 Connection type in scoped signing keys is not limited to MQTT
### Observed behavior

We have an account called "test". There we have a  user called mqtt and it works as expected.
```
+-------------------------------------------------------------------------------------+
|                                        User                                         |
+--------------------------+----------------------------------------------------------+
| Name                     | mqtt                                                     |
| User ID                  | xxxxxxxxxxxxxxxX |
| Issuer ID                | xxxxxxxxxxxxxxxxx|
| Issued                   | 2022-01-31 19:02:48 UTC                                  |
| Expires                  |                                                          |
| Bearer Token             | Yes                                                      |
| Response Permissions     | Not Set                                                  |
+--------------------------+----------------------------------------------------------+
| Max Msg Payload          | Unlimited                                                |
| Max Data                 | Unlimited                                                |
| Max Subs                 | Unlimited                                                |
| Network Src              | Any                                                      |
| Time                     | Any                                                      |
+--------------------------+----------------------------------------------------------+
| Allowed Connection Types | MQTT                                                     |
+--------------------------+----------------------------------------------------------+
```
Then we created SK and another user signed by this SK, here it is:
```
+---------------------------------------------------------------------------+
|                                   User                                    |
+----------------+----------------------------------------------------------+
| Name           | sk                                                  |
| User ID        | Xxxxxxxxxxxxxxx
| Issuer ID      | xxxxxxxxxxxxxxx |
| Issuer Account | xxxxxxxxxxxx |
| Issued         | 2024-08-06 11:12:23 UTC                                  |
| Expires        |                                                          |
| Issuer Scoped  | Yes                                                      |
+----------------+----------------------------------------------------------+

+-------------------------------------------------------------------------------------+
|                            Scoped Signing Key - Details                             |
+--------------------------+----------------------------------------------------------+
| Key                      | XXXXXXXXXXXXXX|
| role                     | test                                                |
| Max Responses            | 1                                                        |
| Response Permission TTL  | 0s                                                       |
| Max Msg Payload          | Unlimited                                                |
| Max Data                 | Unlimited                                                |
| Max Subs                 | Unlimited                                                |
| Network Src              | Any                                                      |
| Time                     | Any                                                      |
| Bearer Token             | Yes                                                      |
+--------------------------+----------------------------------------------------------+
| Allowed Connection Types | MQTT                                                     |
+--------------------------+----------------------------------------------------------+
```

### Expected behavior

Our expectation is that we can only use MQTT connection type there.
But reality both nats and mqtt connections work:
```
❯ nats sub 'foo' --creds test
09:31:55 Subscribing on foo

[#1] Received on "foo"
hello
```

### Server and client version

2.10.18

### Host environment

_No response_

### Steps to reproduce

Provided above

Pull request description:
[FIXED] Connection type in scoped signing keys not honored
The check of the allowed connection types must be maded after the user's permissions limits are possibly "swapped" with the scoped signer's.

Resolves #5786

Signed-off-by: Ivan Kozlovic <ivan@synadia.com>


Patch:
diff --git a/server/auth.go b/server/auth.go
index 415367b1..f4e362f3 100644
--- a/server/auth.go
+++ b/server/auth.go
@@ -883,33 +883,6 @@ func (s *Server) processClientOrLeafAuthentication(c *client, opts *Options) (au
 	// If we have a jwt and a userClaim, make sure we have the Account, etc associated.
 	// We need to look up the account. This will use an account resolver if one is present.
 	if juc != nil {
-		allowedConnTypes, err := convertAllowedConnectionTypes(juc.AllowedConnectionTypes)
-		if err != nil {
-			// We got an error, which means some connection types were unknown. As long as
-			// a valid one is returned, we proceed with auth. If not, we have to reject.
-			// In other words, suppose that JWT allows "WEBSOCKET" in the array. No error
-			// is returned and allowedConnTypes will contain "WEBSOCKET" only.
-			// Client will be rejected if not a websocket client, or proceed with rest of
-			// auth if it is.
-			// Now suppose JWT allows "WEBSOCKET, MQTT" and say MQTT is not known by this
-			// server. In this case, allowedConnTypes would contain "WEBSOCKET" and we
-			// would get `err` indicating that "MQTT" is an unknown connection type.
-			// If a websocket client connects, it should still be allowed, since after all
-			// the admin wanted to allow websocket and mqtt connection types.
-			// However, say that the JWT only allows "MQTT" (and again suppose this server
-			// does not know about MQTT connection type), then since the allowedConnTypes
-			// map would be empty (no valid types found), and since empty means allow-all,
-			// then we should reject because the intent was to allow connections for this
-			// user only as an MQTT client.
-			c.Debugf("%v", err)
-			if len(allowedConnTypes) == 0 {
-				return false
-			}
-		}
-		if !c.connectionTypeAllowed(allowedConnTypes) {
-			c.Debugf("Connection type not allowed")
-			return false
-		}
 		issuer := juc.Issuer
 		if juc.IssuerAccount != _EMPTY_ {
 			issuer = juc.IssuerAccount
@@ -952,6 +925,36 @@ func (s *Server) processClientOrLeafAuthentication(c *client, opts *Options) (au
 			c.Debugf("Account does not allow bearer tokens")
 			return false
 		}
+		// We check the allowed connection types, but only after processing
+		// of scoped signer (so that it updates `juc` with what is defined
+		// in the account.
+		allowedConnTypes, err := convertAllowedConnectionTypes(juc.AllowedConnectionTypes)
+		if err != nil {
+			// We got an error, which means some connection types were unknown. As long as
+			// a valid one is returned, we proceed with auth. If not, we have to reject.
+			// In other words, suppose that JWT allows "WEBSOCKET" in the array. No error
+			// is returned and allowedConnTypes will contain "WEBSOCKET" only.
+			// Client will be rejected if not a websocket client, or proceed with rest of
+			// auth if it is.
+			// Now suppose JWT allows "WEBSOCKET, MQTT" and say MQTT is not known by this
+			// server. In this case, allowedConnTypes would contain "WEBSOCKET" and we
+			// would get `err` indicating that "MQTT" is an unknown connection type.
+			// If a websocket client connects, it should still be allowed, since after all
+			// the admin wanted to allow websocket and mqtt connection types.
+			// However, say that the JWT only allows "MQTT" (and again suppose this server
+			// does not know about MQTT connection type), then since the allowedConnTypes
+			// map would be empty (no valid types found), and since empty means allow-all,
+			// then we should reject because the intent was to allow connections for this
+			// user only as an MQTT client.
+			c.Debugf("%v", err)
+			if len(allowedConnTypes) == 0 {
+				return false
+			}
+		}
+		if !c.connectionTypeAllowed(allowedConnTypes) {
+			c.Debugf("Connection type not allowed")
+			return false
+		}
 		// skip validation of nonce when presented with a bearer token
 		// FIXME: if BearerToken is only for WSS, need check for server with that port enabled
 		if !juc.BearerToken {


Test patch:
diff --git a/server/jwt_test.go b/server/jwt_test.go
index cb3a3391..d45b1dd5 100644
--- a/server/jwt_test.go
+++ b/server/jwt_test.go
@@ -5779,6 +5779,7 @@ func TestJWScopedSigningKeys(t *testing.T) {
 	signer.Key = aSignScopedPub
 	signer.Template.Pub.Deny.Add("denied")
 	signer.Template.Payload = 5
+	signer.Template.AllowedConnectionTypes.Add(jwt.ConnectionTypeStandard)
 	accClaim.SigningKeys.AddScopedSigner(signer)
 	accJwt := encodeClaim(t, accClaim, aExpPub)
 
@@ -5795,11 +5796,16 @@ func TestJWScopedSigningKeys(t *testing.T) {
 			type: full
 			dir: '%s'
 		}
+		websocket {
+			listen: 127.0.0.1:-1
+			no_tls: true
+		}
     `, ojwt, syspub, dirSrv)))
 	s, opts := RunServerWithConfig(cf)
 	defer s.Shutdown()
 
 	url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
+	wsUrl := fmt.Sprintf("ws://%s:%d", opts.Websocket.Host, opts.Websocket.Port)
 	errChan := make(chan error, 1)
 	defer close(errChan)
 	awaitError := func(expected bool) {
@@ -5853,6 +5859,10 @@ func TestJWScopedSigningKeys(t *testing.T) {
 		nc.Flush()
 		awaitError(true)
 	})
+	t.Run("scoped-signing-key-allowed-conn-types", func(t *testing.T) {
+		_, err := nats.Connect(wsUrl, nats.UserCredentials(aScopedCreds))
+		require_Error(t, err)
+	})
 	t.Run("scoped-signing-key-reload", func(t *testing.T) {
 		reconChan := make(chan struct{}, 1)
 		defer close(reconChan)
@@ -5867,6 +5877,7 @@ func TestJWScopedSigningKeys(t *testing.T) {
 			nats.ReconnectHandler(func(conn *nats.Conn) {
 				reconChan <- struct{}{}
 			}),
+			nats.ReconnectWait(100*time.Millisecond),
 		)
 		defer nc.Close()
 		_, err := nc.ChanSubscribe("denied", msgChan)
@@ -5879,6 +5890,7 @@ func TestJWScopedSigningKeys(t *testing.T) {
 		// Alter scoped permissions and update
 		signer.Template.Payload = -1
 		signer.Template.Pub.Deny.Remove("denied")
+		signer.Template.AllowedConnectionTypes.Add(jwt.ConnectionTypeWebsocket)
 		accClaim.SigningKeys.AddScopedSigner(signer)
 		accUpdatedJwt := encodeClaim(t, accClaim, aExpPub)
 		if updateJwt(t, url, sysCreds, accUpdatedJwt, 1) != 1 {
@@ -5894,6 +5906,11 @@ func TestJWScopedSigningKeys(t *testing.T) {
 		msg := <-msgChan
 		require_Equal(t, string(msg.Data), "way.too.long.for.old.payload.limit")
 		require_Len(t, len(msgChan), 0)
+		nc.Close()
+		nc, err = nats.Connect(wsUrl, nats.UserCredentials(aScopedCreds))
+		require_NoError(t, err)
+		nc.Flush()
+		defer nc.Close()
 	})
 	require_Len(t, len(errChan), 0)
 }