499 research outputs found

    Types to the rescue: verification of REST APIs Consumer Code

    Get PDF
    Tese de mestrado, Engenharia Informática (Engenharia de Software) Universidade de Lisboa, Faculdade de Ciências, 2019As arquiteturas de software são fundamentais para o desenvolvimento de um software fiável, escalável e com uma fácil manutenção. Com a criação e crescimento da internet, surgiu a necessidade de criar padrões de software que permitam trocar informação neste novo ambiente. O protocolo SOAP e a arquitetura REST são, dos padrões que emergiram, os que mais se destacaram ao nível da utilização. Durante as últimas décadas, e devido ao grande crescimento daWorld WideWeb, a arquitetura REST tem se destacado como a mais importante e utilizada pela comunidade. REST (Representational State Transfer) retira partido das características do protocolo HTTP para descrever as mensagens trocadas entre clientes e servidores. Os dados na arquitectura REST são representados por recursos, que são identificados por um identificador único (p.e. URI) e que podem ter várias representações (em vários formatos), que são os dados concretos de um recurso. A interação com os recursos é feita usando os métodos HTTP: get para obter um recurso, post para adicionar um novo recurso, put para fazer uma atualização de um recurso, delete para remover um recurso; entre outros, sendo estes os principais para aplicações CRUD. As aplicações RESTful, isto é, aplicações que fornecem os seus serviços através da arquitetura REST, devem ser claras na especificação dos seus serviços de forma a que os seus clientes possam utilizá-las sem erros. Para tal, existem várias linguagens de especificação de APIs REST, como a Open API Specification ou a API Blueprint, no qual é possível descrever formalmente as várias operações fornecidas pelo serviço, como o formato dos pedidos de cada operação e as respetivas respostas. No entanto, estas linguagens apresentam uma limitação nas condições formais que se pode colocar nos parâmetros dos pedidos e no impacto que estes têm no formato e conteúdo da resposta. Deste modo, foi introduzida uma nova linguagem de especificação de aplicações REST, HeadREST, onde é adicionada a expressividade necessária para cobrir as lacunas das outras linguagens. Esta expressividade é introduzida com a utilização de tipos refinados, que permitem restringir os valores de um determinado tipo. Adicionalmente, é introduzida também uma operação que permite verificar se uma determinada expressão pertence a um determinado tipo. Em HeadREST, cada operação é especificada usando uma ou mais asserções. Cada asserção é composta por um método HTTP, um URI template da operação, uma pré-condição que define as condições onde esta operação é aceite, e uma pós-condição que estabelece os resultados da operação se a pré-condição for comprida. Deste modo, estas condições permitem expressar os dados enviados nos pedidos e a receber na resposta, assim como expressar o estado do conjunto de recursos antes e depois do pedido REST. Devido à utilização de tipos refinados não é possível resolver sintaticamente a relação de subtipos na validação de uma especificação HeadREST. Deste modo, é necessária uma abordagem semântica: a relação de subtipos é transformada em fórmulas de lógica de primeira ordem, e depois é utilizado um SMT solver para resolver a formula e, consecutivamente, resolver a relação de subtipos. Por outro lado, é também importante garantir que as chamadas às APIs REST cumprem as especificações das mesmas. As linguagens de programação comuns não conseguem garantir que as chamadas a um serviço REST estão de acordo com a especificação do serviço, nomeadamente se o URL da chamada é válido e se o pedido e resposta estão bem formados ao nível dos valores enviados. Assim, um cliente só percebe se as chamadas estão bem feitas em tempo de execução. Existem poucas soluções para análise estática deste tipo de chamadas (RESType é um raro exemplo) e tendem a ser limitadas e a depender de um único tipo de linguagem de especificação. Para além disso, os clientes de serviços REST tendem a ser maioritariamente desenvolvidos em JavaScript, que possui uma fraca análise estática, o que potencializa ainda mais o problema identificado.Numa primeiro passo para tentar resolver este problema desenvolveu-se a linguagem SafeScript, que se caracteriza por ser um subconjunto do JavaScript equipado com um forte sistema de tipos. O sistema de tipos é muito expressivo graças à adição de tipos refinados e também de um operador que verifica se uma expressão pertence a um tipo. SafeScript apresenta flow typing, isto é, o tipo de uma expressão depende da sua localização no fluxo de controlo do programa. Tal como no HeadREST, não é possível realizar uma simples análise sintática para a validação de tipos. No entanto, neste caso trata-se de uma linguagem imperativa com flow typing, logo uma abordagem igual de tradução direta para um SMT solver não é trivial. Deste modo, a validação de tipos é feita traduzido o código SafeScript para a linguagem intermédia Boogie, onde as necessárias validações são traduzidas como asserções, sendo que o Boogie utiliza internamente o Z3 SMT solver para resolver semanticamente as asserções. Devido à validação semântica, o compilador de SafeScript consegue detetar estaticamente diversos erros de execução comuns, como divisão por zero ou acesso a um array fora dos seus limites, e que não conseguem ser detetados por linguagens similares, como o TypeScript. SafeScript compila para JavaScript, com o intuito de poder ser utilizado em conjunto com este. Graças ao seu expressivo sistema de tipos, o validador de programas SafeScript é também um verificador estático. A partir deste é possível provar que um programa cumpre uma determinada especificação, que pode ser descrita usando os tipos refinados. Neste trabalho destacou-se a capacidade de prova do validador de SafeScript, concretamente resolvendo alguns desafios propostos pelo Verification Benchmarks Challange. A partir do SafeScript desenvolveu-se a extensão SafeRESTScript, que adiciona pedidos REST à sintaxe do SafeScript e valida-os estaticamente de encontro a uma especificação HeadREST. Para cada chamada REST são feitas principalmente duas validações. Em primeiro lugar, é verificado se o URL é um endereço válido do serviço para o método HTTP do pedido, isto é, se existe algum triplo na especificação com o par método e URL do pedido. De seguida, e com a tradução da especificação HeadREST importada para Boogie, é verificado se as chamadas REST cumprem os triplos da especificação, nomeadamente, se as pré-condições são cumpridas então as pós-condições também se devem verificar. Por exemplo, se uma pós-condição, cuja respetiva pré-condição é verdadeira para uma determinada chamada, asserta que no corpo da resposta existe um objeto com o campo id, então um acesso a este campo no corpo da resposta é validado. Neste trabalho, como exemplo ilustrativo das capacidades da linguagem, desenvolveu-se um cliente SafeRESTScript da API REST do conhecido repositório GitHub. Ambas as linguagens possuem um compilador e editor que estão disponíveis como plug-in para o IDE Eclipse, para além de uma versão terminal. As duas linguagens possuem várias limitações, e por isso muito trabalho ainda existe pela frente. No entanto, SafeScript e SafeRESTScript não têm ambição de ser linguagens de produção, mas sim contribuir para um melhoramento da análise estática de programas e mostrar que é possível auxiliar o desenvolvimento fiável de código cliente de serviços REST.REST is the architectural sytle most used in the web to exchange data. RESTful applications must be well documented so clients can use its services without doubts and errors. There are several specification languages for describing REST APIs, e.g. Open API Specification, but they lack on expressiveness to describe the exchanged data. Head- REST specification language was introduced to address this gap, containing an expressive type system that allows to describe rigorously the request and response formats of a service endpoint. On the other hand, it is also important to ensure that REST calls in client code meet the service specification. This challenge is even more important taking in account that most REST clients are made in JavaScript, a weakly typed language. To aim this problem, we firstly developed SafeScript, a subset of JavaScript equipped with a strong type system. SafeScript has a expressive type system thanks to refinement types and to an operator that checks if an expression belongs to a type. A semantic subtyping analysis is necessary; the typing validation in done by translating the code to Boogie intermediate language which uses the Z3 SMT solver for the semantic evaluation. SafeScript compiles directly to JavaScript. SafeRESTScript is an extension of SafeScript that adds REST calls, being a client-side language for consuming REST services. It uses HeadREST specifications to verify REST calls: whether the URL of the call is a valid endpoint and whether the data exchanged match the pre and post-conditions declared in the specification. With the creation of this new languages, we dot not intend in having them as production languages, but to show that it is possible to contribute with a better verification and correction in area where software reliability is weak

    Winter Leaf Yellowing in 'Hass' Avocado

    Get PDF
    The New Zealand avocado industry is worth $39.7 million in exports of 'Hass' avocados. Crop yields grew steadily from 1996 to 2001 to reach an average of 8.86 tonnes/ha. Since then however, crop yields have remained steady. To increase returns to growers, crop yields must increase. Avocado leaves in New Zealand become yellow in winter and it is hypothesised that chilling, followed by photoinhibition, is leading to photooxidation. Leaf yellowing leads to reduced photosynthetic capacity and early leaf abscission, at a time when carbon fixation and carbohydrate reserves are needed to support developing flowers, subsequent fruit set and vegetative flush, in addition to the existing mature crop. The focus of this research was to determine the underlying causes of yellowing in 'Hass' avocado leaves during winter. It is suspected that it is a result of the creation of free-radical oxygen that causes photooxidation of leaf components under excess light during low temperature conditions, such as experienced on clear winter mornings in the Bay of Plenty. An orchard in Katikati, in the Bay of Plenty, New Zealand was selected has it had a history of leaf yellowing. Two open flow, differential gas exchange measurement systems, The CIRAS-1 and the CMS-400 were used to monitor leaf photosynthetic performance over the course of the 2006 winter, with particular focus on the month of August. Chlorophyll a fluorescence was measured with a Walz Mini-PAM, leaf colour with a Minolta Chroma meter CR-200b and chlorophyll content with Minolta SPAD chlorophyll meter (in addition to traditional extraction techniques). There was conclusive evidence that the cold nights resulted in decreased net photosynthesis over the winter, with the depression starting in May and ending around the middle of August, dates that coincide closely with the period when days with mean temperatures less than 10 C occurred. The decrease in photosynthesis appears to be due to a direct effect on the carbon reduction pathway and in unusual in that full recovery seems to occur at the same time during the day. No photodamage of significance was found and the avocado seems to be highly protected against high light when photosynthesis is inhibited. This investigation found that leaf yellowing is not caused by photodamage following depressed photosynthesis. A new hypothesis is proposed which suggests that leaf yellowing is produced by the re-allocation of nitrogen from leaves during cold weather during flowering. It is suggested that the chilled leaves are seen as unproductive, old or shaded leaves by the plant and nutrient resources are re-allocated away from these leaves. A foliar application of 1% low biuret urea and 0.5% magnesium sulphate is currently used by avocado growers to restore leaf colour in leaves that have become yellow over winter. An experiment was carried out on yellowed leaves on 23rd August 2006 to determine the effectiveness of the treatment. This study concluded that the treatment was able to restore some leaf colour, but had no effect on leaf photosynthetic function

    DEVELOPING RAPID MOLECULAR TECHNIQUES FOR DIAGNOSIS OF NEISSERIA GONORRHOEAE AND CHARACTERIZATION OF ANTIMICROBIAL RESISTANCE

    Get PDF
    Multidrug-resistant Neisseria gonorrhoeae (Ng) is a global health emergency. To stop the spread of untreatable gonorrhea, improved molecular diagnostics and characterization of antimicrobial resistance (AMR) determinants are crucial. For this research, I developed an RT-PCR based molecular diagnostic test to identify Ng as well as a second test, utilizing novel multiplex primers for gyrA, to simultaneously identify Ng and predict ciprofloxacin susceptibility. Although ciprofloxacin is no longer recommended for the treatment of gonorrhea, susceptible isolates can be prevalent in some regions. Thus, if the ciprofloxacin susceptibility of an isolate is known, this antibiotic could be used for treatment. Both the Ng diagnostic test and the test for ciprofloxacin susceptibility performed with high sensitivity and specificity with DNA from cultures and gave more variable results with clinical specimens (i.e. urines and remnant Aptima urine specimens). These tests were modified for the incorporation of the primers into a hydrogel-based diagnostic platform, for eventual point-of-care applications. The hydrogel platform performed with high sensitivity and specificity for Ng diagnosis, depending on the specimen type. Additionally, to identify emerging AMR genotypes, various genes implicated in Ng AMR resistance were amplified and sequenced from Ng positive remnant Aptima urine specimens (for which AMR testing is not possible). Phenotype predictions based on DNA sequence analysis indicated emerging azithromycin resistance in Saskatchewan and highlighted the importance of molecular AMR surveillance to prevent Ng outbreaks. Finally, the properties of a β-lactamase produced by an uncharacterized Ng plasmid was investigated. A novel 6bp deletion in the start codon of blaTEM was identified. Due to this deletion, the β-lactamase was truncated and resulted in slow ampicillin hydrolysis coupled with a low penicillin MIC (0.125 mg/L). Overall, my research produced molecular diagnostic tests for Ng and ciprofloxacin susceptibility prediction and characterized and predicted emerging AMR resistance by molecular analysis

    Trends in antimicrobial resistance patterns in Neisseria gonorrhoeae in Australia and New Zealand : a meta-analysis and systematic review

    Get PDF
    (1) Background: The widespread development of resistance among Neisseria gonorrhoeae (NG) clinical isolates has been reported by surveillance systems around the world. This meta-analysis estimated the changes in susceptibility patterns among antibiotics under surveillance in Australia and New Zealand. (2) Methods: Articles published in English from 1980–2018, from Australia or New Zealand, that met the selection criteria were included. The meta-analysis was carried out using the R statistical software. (3) Results: In Australia, there has been decreasing susceptibility of gonococcal isolates to selected antimicrobials over time. Azithromycin (Odds Ratio (OR): 0.73; 95% Confidence Interval (CI) 0.64–0.82) and ceftriaxone (OR: 0.69; 95% CI 0.59–0.80) showed decreasing levels of susceptibility each year. Western Australia (OR: 0.76; 95% CI 0.60–0.96) and Victoria (OR: 0.74; 95% CI 0.60–0.90) also had decreasing levels of susceptibility to ceftriaxone over time compared with other states and territories. (4) Conclusions: The results highlight the need for the development of new approaches for managing cases of gonorrhoea. Improved antimicrobial stewardship, enhanced surveillance and contact tracing are needed to identify and respond to changes in antibiotic resistance in a timely manner. Increasing awareness and public health follow-up of cases can help to interrupt the cycle of infection and limit transmission

    Flexible Correct-by-Construction Programming

    Full text link
    Correctness-by-Construction (CbC) is an incremental program construction process to construct functionally correct programs. The programs are constructed stepwise along with a specification that is inherently guaranteed to be satisfied. CbC is complex to use without specialized tool support, since it needs a set of predefined refinement rules of fixed granularity which are additional rules on top of the programming language. Each refinement rule introduces a specific programming statement and developers cannot depart from these rules to construct programs. CbC allows to develop software in a structured and incremental way to ensure correctness, but the limited flexibility is a disadvantage of CbC. In this work, we compare classic CbC with CbC-Block and TraitCbC. Both approaches CbC-Block and TraitCbC, are related to CbC, but they have new language constructs that enable a more flexible software construction approach. We provide for both approaches a programming guideline, which similar to CbC, leads to well-structured programs. CbC-Block extends CbC by adding a refinement rule to insert any block of statements. Therefore, we introduce CbC-Block as an extension of CbC. TraitCbC implements correctness-by-construction on the basis of traits with specified methods. We formally introduce TraitCbC and prove soundness of the construction strategy. All three development approaches are qualitatively compared regarding their programming constructs, tool support, and usability to assess which is best suited for certain tasks and developers.Comment: arXiv admin note: substantial text overlap with arXiv:2204.0564

    Efficient compilation of a verification-friendly programming language

    Get PDF
    This thesis develops a compiler to convert a program written in the verification friendly programming language Whiley into an efficient implementation in C. Our compiler uses a mixture of static analysis, run-time monitoring and a code generator to and faster integer types, eliminate unnecessary array copies and de-allocate unused memory without garbage collection, so that Whiley programs can be translated into C code to run fast and for long periods on general operating systems as well as limited-resource embedded devices. We also present manual and automatic proofs to verify memory safety of our implementations, and benchmark on a variety of test cases for practical use. Our benchmark results show that, in our test suite, our compiler effectively reduces the time complexity to the lowest possible level and stops all memory leaks without causing double-freeing problems. The performance of implementations can be further improved by choosing proper integer types within the ranges and exploiting parallelism in the programs
    corecore