Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement declarative auth design for upgrade service #216

Merged
merged 8 commits into from
Jun 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ This file contains all the notable changes done to the Ballerina WebSocket packa

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.2.0-beta.2] - 2021-06-24

### Fixed
- [Implement declarative auth design for upgrade service](https://github.com/ballerina-platform/ballerina-standard-library/issues/1405)

## [1.2.0-beta.1] - 2021-05-06

### Fixed
Expand Down
2 changes: 2 additions & 0 deletions websocket-ballerina/annotation.bal
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@
# in the `websocket:Listener` which is applicable only for the initial HTTP upgrade request.
# + maxFrameSize - The maximum payload size of a WebSocket frame in bytes.
# If this is not set or is negative or zero, the default frame size which is 65536 will be used.
# + auth - Listener authenticaton configurations
public type WSServiceConfig record {|
string[] subProtocols = [];
decimal idleTimeout = 0;
int maxFrameSize = 65536;
ListenerAuthConfig[] auth?;
|};

# The annotation which is used to configure a WebSocket service.
Expand Down
119 changes: 119 additions & 0 deletions websocket-ballerina/auth_desugar.bal
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
//
// WSO2 Inc. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import ballerina/auth;
import ballerina/http;
import ballerina/jballerina.java;
import ballerina/jwt;
import ballerina/oauth2;

// This function is used for declarative auth design, where the authentication/authorization decision is taken by
// reading the auth annotations provided in service and the `Authorization` header taken with an interop call.
// This function is injected to the first lines of an websocket resource function. Then the logic will be executed
// during the runtime.
// If this function returns `()`, it will be moved to the execution of business logic, else there will be a 401/403
// response sent. The execution flow will be broken by panic with a distinct error.
# Uses for declarative auth design, where the authentication/authorization decision is taken
# by reading the auth annotations provided in service/resource and the `Authorization` header of request.
#
# + serviceRef - The service reference where the resource locates
public isolated function authenticateResource(Service serviceRef) {
ListenerAuthConfig[]? authConfig = getServiceAuthConfig(serviceRef);
if (authConfig is ()) {
return;
}
string|http:HeaderNotFoundError header = getAuthorizationHeader();
if (header is string) {
http:Unauthorized|http:Forbidden? result = tryAuthenticate(<ListenerAuthConfig[]>authConfig, header);
if (result is http:Unauthorized) {
notifyFailure(result.status.code);
} else if (result is http:Forbidden) {
notifyFailure(result.status.code);
}
} else {
notifyFailure(401);
}
}

isolated function tryAuthenticate(ListenerAuthConfig[] authConfig, string header) returns http:Unauthorized|http:Forbidden? {
foreach ListenerAuthConfig config in authConfig {
if (config is FileUserStoreConfigWithScopes) {
http:ListenerFileUserStoreBasicAuthHandler handler = new(config.fileUserStoreConfig);
auth:UserDetails|http:Unauthorized authn = handler.authenticate(header);
string|string[]? scopes = config?.scopes;
if (authn is auth:UserDetails) {
if (scopes is string|string[]) {
http:Forbidden? authz = handler.authorize(authn, scopes);
return authz;
}
return;
}
} else if (config is LdapUserStoreConfigWithScopes) {
http:ListenerLdapUserStoreBasicAuthProvider handler = new(config.ldapUserStoreConfig);
auth:UserDetails|http:Unauthorized authn = handler->authenticate(header);
string|string[]? scopes = config?.scopes;
if (authn is auth:UserDetails) {
if (scopes is string|string[]) {
http:Forbidden? authz = handler->authorize(authn, scopes);
return authz;
}
return;
}
} else if (config is JwtValidatorConfigWithScopes) {
http:ListenerJwtAuthHandler handler = new(config.jwtValidatorConfig);
jwt:Payload|http:Unauthorized authn = handler.authenticate(header);
string|string[]? scopes = config?.scopes;
if (authn is jwt:Payload) {
if (scopes is string|string[]) {
http:Forbidden? authz = handler.authorize(authn, scopes);
return authz;
}
return;
}
} else {
// Here, config is OAuth2IntrospectionConfigWithScopes
http:ListenerOAuth2Handler handler = new(config.oauth2IntrospectionConfig);
oauth2:IntrospectionResponse|http:Unauthorized|http:Forbidden auth = handler->authorize(header, config?.scopes);
if (auth is oauth2:IntrospectionResponse) {
return;
} else if (auth is http:Forbidden) {
return auth;
}
}
}
http:Unauthorized unauthorized = {};
return unauthorized;
}

isolated function getServiceAuthConfig(Service serviceRef) returns ListenerAuthConfig[]? {
typedesc<any> serviceTypeDesc = typeof serviceRef;
var serviceAnnotation = serviceTypeDesc.@ServiceConfig;
if (serviceAnnotation is ()) {
return;
}
WSServiceConfig serviceConfig = <WSServiceConfig>serviceAnnotation;
return serviceConfig?.auth;
}

isolated function notifyFailure(int responseCode) {
// This panic is added to break the execution of the implementation inside the resource function after there is
// an authn/authz failure and responded with 401/403 internally.
panic error(responseCode.toString() + " received by auth desugar.");
}

isolated function getAuthorizationHeader() returns string|http:HeaderNotFoundError = @java:Method {
'class: "org.ballerinalang.net.websocket.WebSocketUtil"
} external;
68 changes: 68 additions & 0 deletions websocket-ballerina/auth_types.bal
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,71 @@ public type OAuth2RefreshTokenGrantConfig record {|

# Represents OAuth2 grant configurations for OAuth2 authentication.
public type OAuth2GrantConfig OAuth2ClientCredentialsGrantConfig|OAuth2PasswordGrantConfig|OAuth2RefreshTokenGrantConfig;

# Represents file user store configurations for Basic Auth authentication.
public type FileUserStoreConfig record {|
*auth:FileUserStoreConfig;
|};

# Represents LDAP user store configurations for Basic Auth authentication.
public type LdapUserStoreConfig record {|
*auth:LdapUserStoreConfig;
|};

# Represents JWT validator configurations for JWT authentication.
#
# + scopeKey - The key used to fetch the scopes
public type JwtValidatorConfig record {|
*jwt:ValidatorConfig;
string scopeKey = "scope";
|};

# Represents OAuth2 introspection server configurations for OAuth2 authentication.
#
# + scopeKey - The key used to fetch the scopes
public type OAuth2IntrospectionConfig record {|
*oauth2:IntrospectionConfig;
string scopeKey = "scope";
|};

# Represents the auth annotation for file user store configurations with scopes.
#
# + fileUserStoreConfig - File user store configurations for Basic Auth authentication
# + scopes - Scopes allowed for authorization
public type FileUserStoreConfigWithScopes record {|
FileUserStoreConfig fileUserStoreConfig;
string|string[] scopes?;
|};

# Represents the auth annotation for LDAP user store configurations with scopes.
#
# + ldapUserStoreConfig - LDAP user store configurations for Basic Auth authentication
# + scopes - Scopes allowed for authorization
public type LdapUserStoreConfigWithScopes record {|
LdapUserStoreConfig ldapUserStoreConfig;
string|string[] scopes?;
|};

# Represents the auth annotation for JWT validator configurations with scopes.
#
# + jwtValidatorConfig - JWT validator configurations for JWT authentication
# + scopes - Scopes allowed for authorization
public type JwtValidatorConfigWithScopes record {|
JwtValidatorConfig jwtValidatorConfig;
string|string[] scopes?;
|};

# Represents the auth annotation for OAuth2 introspection server configurations with scopes.
#
# + oauth2IntrospectionConfig - OAuth2 introspection server configurations for OAuth2 authentication
# + scopes - Scopes allowed for authorization
public type OAuth2IntrospectionConfigWithScopes record {|
OAuth2IntrospectionConfig oauth2IntrospectionConfig;
string|string[] scopes?;
|};

# Defines the authentication configurations for the WebSocket listener.
public type ListenerAuthConfig FileUserStoreConfigWithScopes|
LdapUserStoreConfigWithScopes|
JwtValidatorConfigWithScopes|
OAuth2IntrospectionConfigWithScopes;
13 changes: 13 additions & 0 deletions websocket-ballerina/tests/Config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[[ballerina.auth.users]]
username="alice"
password="xxx"
scopes=["write", "update"]

[[ballerina.auth.users]]
username="bob"
password="yyy"
scopes=["read"]

[[ballerina.auth.users]]
username="eve"
password="123"
88 changes: 88 additions & 0 deletions websocket-ballerina/tests/auth_declarative_basic_auth_test.bal
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright (c) 2021 WSO2 Inc. (//www.wso2.org) All Rights Reserved.
//
// WSO2 Inc. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// //www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import ballerina/lang.runtime as runtime;
import ballerina/test;

listener Listener l49 = new(21318);
string wsService49Data = "";

@ServiceConfig {
auth: [
{
fileUserStoreConfig: {},
scopes: ["write", "update"]
}
]
}
service /basicAuth on l49 {
resource function get .() returns Service {
return new WsService49();
}
}

service class WsService49 {
*Service;
remote function onTextMessage(string data) {
wsService49Data = data;
}
}

@test:Config {}
public function testBasicAuthServiceAuthSuccess() returns Error? {
Client wsClient = check new("ws://localhost:21318/basicAuth/", {
auth: {
username: "alice",
password: "xxx"
}
});
check wsClient->writeTextMessage("Hello, World!");
runtime:sleep(0.5);
test:assertEquals(wsService49Data, "Hello, World!");
error? result = wsClient->close(statusCode = 1000, reason = "Close the connection", timeout = 0);
}

@test:Config {}
public function testBasicAuthServiceAuthzFailure() {
Client|Error wsClient = new("ws://localhost:21318/basicAuth/", {
auth: {
username: "bob",
password: "yyy"
}
});
if (wsClient is Error) {
test:assertEquals(wsClient.message(), "InvalidHandshakeError: Invalid handshake response getStatus: 403 Forbidden");
} else {
test:assertFail(msg = "Test Failed!");
error? result = wsClient->close(statusCode = 1000, reason = "Close the connection", timeout = 0);
}
}

@test:Config {}
public function testBasicAuthServiceAuthnFailure() {
Client|Error wsClient = new("ws://localhost:21318/basicAuth/", {
auth: {
username: "peter",
password: "123"
}
});
if (wsClient is Error) {
test:assertEquals(wsClient.message(), "InvalidHandshakeError: Invalid handshake response getStatus: 401 Unauthorized");
} else {
test:assertFail(msg = "Test Failed!");
error? result = wsClient->close(statusCode = 1000, reason = "Close the connection", timeout = 0);
}
}
Loading