September 20th, 2008SOA Way of Writing PHP

Traditional way of Writing PHP
Let me draw a component diagram of a typical traditional(conventional) PHP web application.MVC Architecture Model

With this design you get the advantages of the client-server architecture and the MVC design pattern.

Advantages of the Traditional Approach

  • You can connect to the server from anywhere that has the connectivity to the centralized server. Say you process purchase orders in your application. Sails agents, customers around the world can connect to the application from their computers and do purchase orders. (Because of the Client-Server Architecture)client-server architecture
  • Doing Changes to the inside of the components (Model, View and Controller) are relatively easy , because of the separation of the logics. But if changes affect to inter-communication of each component then it become harder because of the low granularity. (check disadvantages)

Are their any disadvantages of this approach?
Yes. There are plenty of them. Actually it is lot more than the advantages list.

Disadvantages of the Traditional Approach

  • More Server load: The only server is responsible for maintenance of all the components. And there is no straight forward way to distribute these components in a network.
  • No Interoperability: Can I replace the PHP Presentation layer with a .NET, C, Java Desktop Application with this design? No. PHP components (Model, View, Controller) are communicated in PHP code level through php function calls or may be through PHP object interactions, If you want to integrate .NET/Java to replace one component, you have to change all these function calls, object passings with each components.
    non-interoperability
  • Fine Grained Interfaces: Even when I want to replace some component with another PHP implementation, it is still very difficult to integrate to the running system because of the fine-grained interfaces (Lot of small operations) used in the inter-component communication.
    Mostly this issue comes when integrating new business component to existing business logic within the controller logic. The below is just a figure to demonstrate what is meant by fine-grained interface.
    fine-grained-services
    This causes the application to be slow (more message exchange => more time on the wire =&t; lesser speed), more traffic to the server and most importantly very hard to make interfaces consistent. (There can be many additions and removals of small operations over the time). Check this to learn more about granularity.
  • Business Process Automation (BPA) is impossible: Your partner companies can not purchase your products through their systems. Because they are only given a browser interface, which need human interaction. You should provide some remote interface to allow their computers to talk to your systems.
    bpa-impossibility
    For BPA, interoperability is really important. Because your partner company may run on completely different platform and use completely different languages. I already proved traditional design will not suit to situation where interoperability is need.
  • Lack of security: With the above approach you have to depend on the transport level security, which is handled by your OS. There can be applications (malicious codes) run top of your OS which have back doors to these information. So for business critical messages you need to have message level security (application to application security) which secure the messages by application itself .
  • Lack of reliability: In any case if the connection is lost, will my messages completely lost?. Here too you depend on the transport level reliability which you don’t have much control of.

So now lets turn to our main topic.

SOA Way of Writing PHP

SOA Model

With SOA, you application is no longer presenting the ‘View’ component directly. Instead it provides your business operations as a Web Service. You may implement a View with PHP using this web service. This approach allows you to implement View not only in PHP but also in other languages like .NET, Java or C as web application or desktop applications.

The business logic access the Data Layer through a Data Service. Simmilarly It can use third party Data services, Web Services to extract out the Data needed in the business process.

Let’s see how it helps you to solve the problems arouse in the traditional approach.

  • Less Server load: The SOA components are natively distributed. You don’t need to process the View and the Data in the same server you process the Buisness Logic.
  • High Interoperability: SOA communication happens through Web Services which is a standard protocol. There are implementations for web services in many languages and for many platforms. You can replace any components with any implementation you prefer. For an example you may first write your business logic in PHP, And as the server load goes high, you can write the buisness module in native language (‘C’) and easily intergreate to the system, without being bother of changing other components.
  • Coarse grained Interfaces: The latest web services standards (e.g. WSDL 2.0) enforce the use of documents for messaging rather than invoking remote procedures. This causes the system to be consistent, maintainable and more responsive.
  • Business Process Automation: Web service provide a platform to machine to machine communication. With the availability of interoperability two companies who use different implementations can communicate easily
  • Security: With a WS-Security implementation you can get message level security in your application. For PHP developers there were no implementation or library that can provide  WS-Security sometime ago. But as WSF/PHP is launched with many implementations for WS-* stack, that gap was closed.
  • Reliability: With the WS-Reliable Messaging you can make sure a reliable communication at the application layer. You can use WSF/PHP to do reliable messaging in PHP

As your business get more complicated you can divide the logic too in to several service components as you do with data and view components. This allows you to extend your application very easily. Here is a rough design of an enterprise SOA application that you may have seen in Java and .NET paradigms. And it is time to see more of these in PHP space as well.

SOA design

Earlier I wrote a blog about how to make your wordpress blog a web service using the WSF/PHP Data Services library. I will expand that post to demonstrate the use of WS-Security features with WSF/PHP.

This time it is a Tag Search service for my wordpress blog. Check the ‘Tag Search’ Data Services Demo from http://ws.dimuthu.org/. The only difference is here you are authenticated before accessing the service using the username tokens as specified in WS-Security.

Just look at the WSSecurity constructor in the Data Service Demo Code. You can observe 4 new parameters passed in to it. (In addition to the “config” and “operations” options)

  • policy – This is where you specify the policy governed by the service.  Here you can either use the WS-Policy compliant policy file or just a simple PHP array that contain the required security token informations.
    $sec_array = array("useUsernameToken" => TRUE);
    $policy = new WSPolicy(array("security"=>$sec_array));
  • securityToken: You specify the user parameters like how you handle the authentication and the encoding type in this option.
    $security_token = new WSSecurityToken(array("passwordCallback" => "password_callback_function",
                                           "passwordType" => "Digest"));
    
    /* callback function
     * @param string $username username of the client request
     * @return string $password password for that username
     */
    function password_callback_function($username) {
        // In the real word I should authenticate users from database.
        // for this demo I have a simple if-else block
    
        if($username == "visitor") {
            return "visitor123";
        }
    
        return "notavistor";
    }

    Note that here you specify a callback function to the security token parameter. Inside this function you retrieve the password for the user (mostly from the database) and return. WSF/PHP will authenticate the user from these information.

  • useWSA : You need to set this option in order to generate the WS-Addressing parameters (like action) for your WSDL. WS-Addressing is required to run web services with WS-Security in WSF/PHP.
  • actions: You should provide a map of action to service operations in order to get the WS Addressing information generated with your WSDL.
    $actions = array("http://ws.dimuthu.org/blog/getPosts" => "getPosts");

    Just have a look at how these information are rendered in the generated WSDL, http://ws.dimuthu.org/blog/WordpressTagSearchService.php?wsdl. (Note the wsaw:action attribute in the messages inside the portType element.

After you deploy the service, it is very easy to generate a client with the WSDL. If you write clients in PHP you can use the wsdl2php tool shipping with WSF/PHP.  The code for my demo client can be found in http://ws.dimuthu.org/source.php?src=tag.search.client. (There I have hard coded the username and password just for the demo purpose)

With WSF/PHP 1.3.2 you can use following basic features in WS-Security.

Feature Purpose Array based Security Policy Options ($sec_policies) Security Token Options ($sec_token_options)
UsernameToken Authentication array(“useUsernameToken” => TRUE) array(“user” => “your_username”,
“password” => “your_password”,
“passwordType” => “Digest”); //Digest/Plain
Timestamp Avoid Interception,Replay Attack (use with signing) array(“includeTimeStamp” => TRUE); array(“ttl” => 100)
Signing Non-Repudiation, Verify Server/Clients identity array(“sign” => TRUE,
“algorithmSuite” => “Basic256Rsa15″,
“securityTokenReference” => “KeyIdentifier”)
array(“privateKey” => $pvt_key,
certificate” => $cert)
Encryption privacy array(“encrypt” => TRUE,
“algorithmSuite” => “Basic256Rsa15″,
“securityTokenReference” => “IssuerSerial”);
array(“privateKey” => $pvt_key,
“receiverCertificate” => $pub_key))

You can build the WSPolicy and WSSecurityToken with an any mix of above features. For some scenarios you may only need timestamp with signing where as some other critical scenarios you want signing, encryption, username token and timestamp.

Here is how you build the WSSPolicy and WSSecurityToken classes using the above mentioned $sec_policies and $sec_token_options.

$policy = new WSPolicy(array("security"=> $sec_policies));

$sec_token = new WSSecurityToken($sec_token_options);

$svr = new WSService(array("policy" => $policy,
                           "securityToken" => $sec_token,
                            "actions" => $your_actions,
                           "operations" => $your_operations));

$svr->reply();

Similarly you can use the WSPolicy and WSSecurity with WSClient for the client side security. See the samples WS-Security demos and WS-Security sources.

This blog is about some of the security features shipped with WSF/PHP 1.3.2. With the next release of WSF/PHP you will have more features related to WS-Security like WS-SecureConversations, WS-Trust and use of KeyStores for encryption and signing.

When you are developing a Web Service, you have to think about the security aspects of your service seriously. When it comes to security in web services you have two basic choices.

  1. Transport level security – Just SOAP over HTTPS
  2. Message level security – WS-Security

See my previous blog comparing Transport level and Message level security.

If you are satisfied with the security provided by using just ‘SOAP over HTTPS’, you can get the work done by configuring your server (Apache or IIS) to enable ssl. See http://www.onlamp.com/pub/a/onlamp/2008/03/04/step-by-step-configuring-ssl-under-apache.html for an step by step guide for configure SSL in your Apache server.

If you want message level security for your application, just use WS-Security. With WSF/PHP it is even easier to implement than SOAP over HTTPS method, because you can provide the certificates programatically in PHP and no need to do further configuration.

WSF/PHP provides you two classes in line with WSService to implement an API to provide WS-Security.

  1. WSPolicy -Let you provide rules that the engine need to follow in securing the message. E.g.
    $policy = new WSPolicy(array("security"=> array("encrypt" => TRUE,
                        "algorithmSuite" => "Basic256Rsa15",
                        "securityTokenReference" => "IssuerSerial")));

    In fact you can load policies from an xml which adheres to the WS-SecurityPolicy specification.

  2. WSSecurityToken – Keeps the security tokens like certificates, keys, username, passwords which would be used when applying the rules specified in the policy. E.g.
    $sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
                                           "receiverCertificate" => $pub_key));

You can see the WS-Security in action on live from http://labs.wso2.org/wsf/php/samples/security/ and security demo ource codes.

Transport Level Security Message Level Security
Secures point to point communication.

E.g: Your browser to Apache server

Secures end to end to end communication.

E.g. Sales Order Request application to Database updating application

Not transparent thorough multiple transport protocols, Transparent through any number of transports since it is handled at an above layer
Cannot specify different part of the message to secured idifferently Can specify which part to sign, which part to encrypt in the message, Specially useful when you have a large message and you really want to secure a small portion.
Relatively easy to attack. Relatively difficult to attack. Since the unsecured path in the message flow is minimum,
In Web Services we found this is followed by transmitting SOAP over HTTPS. In Web Services you can follow message level security by adhering to WS-Security specification.

You can find a descriptive post about the Transport Level security vs Message Level Security on http://www.xyzws.com/scdjws.do?cat=scdjws&smenu=WSGEN&article=4.


© 2007 Dimuthu’s Blog | iKon Wordpress Theme by Windows Vista Administration | Powered by Wordpress