Recent Posts
Archives

Posts Tagged ‘Security’

PostHeaderIcon [PyConUS 2024] How Python Harnesses Rust through PyO3

David Hewitt, a key contributor to the PyO3 library, delivered a comprehensive session at PyConUS 2024, unraveling the mechanics of integrating Rust with Python. As a Python developer for over a decade and a lead maintainer of PyO3, David provided a detailed exploration of how Rust’s power enhances Python’s ecosystem, focusing on PyO3’s role in bridging the two languages. His talk traced the journey of a Python function call to Rust code, offering insights into performance, security, and concurrency, while remaining accessible to those unfamiliar with Rust.

Why Rust in Python?

David began by outlining the motivations for combining Rust with Python, emphasizing Rust’s reliability, performance, and security. Unlike Python, where exceptions can arise unexpectedly, Rust’s structured error handling via pattern matching ensures predictable behavior, reducing debugging challenges. Performance-wise, Rust’s compiled nature offers significant speedups, as seen in libraries like Pydantic, Polars, and Ruff. David highlighted Rust’s security advantages, noting its memory safety features prevent common vulnerabilities found in C or C++, making it a preferred choice for companies like Microsoft and Google. Additionally, Rust’s concurrency model avoids data races, aligning well with Python’s evolving threading capabilities, such as sub-interpreters and free-threading in Python 3.13.

PyO3: Bridging Python and Rust

Central to David’s talk was PyO3, a Rust library that facilitates seamless integration with Python. PyO3 allows developers to write Rust code that runs within a Python program or vice versa, using procedural macros to generate Python-compatible modules. David explained how tools like Maturin and setup-tools-rust simplify project setup, enabling developers to compile Rust code into native libraries that Python imports like standard modules. He emphasized PyO3’s goal of maintaining a low barrier to entry, with comprehensive documentation and a developer guide to assist Python programmers venturing into Rust, ensuring a smooth transition across languages.

Tracing a Function Call

David took the audience on a technical journey, tracing a Python function call through PyO3 to Rust code. Using a simple word-counting function as an example, he showed how a Rust implementation, marked with PyO3’s @pyfunction attribute, mirrors Python’s structure while offering performance gains of 2–4x. He dissected the Python interpreter’s bytecode, revealing how the CALL instruction invokes PyObject_Vectorcall, which resolves to a Rust function pointer via PyO3’s generated code. This “trampoline” handles critical safety measures, such as preventing Rust panics from crashing the Python interpreter and managing the Global Interpreter Lock (GIL) for safe concurrency. David’s step-by-step breakdown clarified how arguments are passed and converted, ensuring seamless execution.

Future of Rust in Python’s Ecosystem

Concluding, David reflected on Rust’s growing adoption in Python, citing over 350 projects monthly uploading Rust code to PyPI, with downloads exceeding 3 billion annually. He predicted that Rust could rival C/C++ in the Python ecosystem within 2–4 years, driven by its reliability and performance. Addressing concurrency, David discussed how PyO3 could adapt to Python’s sub-interpreters and free-threading, potentially enforcing immutability to simplify multithreaded interactions. His vision for PyO3 is to enhance Python’s strengths without replacing it, fostering a symbiotic relationship that empowers developers to leverage Rust’s precision where needed.

Hashtags: #Rust #PyO3 #Python #Performance #Security #PyConUS2024 #DavidHewitt #Pydantic #Polars #Ruff

PostHeaderIcon [SpringIO2023] Beyond Routing: Spring Cloud Gateway with Style by Abel Salgado & Marta Medio

At Spring I/O 2023, Abel Salgado and Marta Medio, seasoned engineers from VMware, delivered an engaging session on elevating Spring Cloud Gateway beyond basic routing. Through practical, real-world examples and live demos, they showcased how to customize Spring Cloud Gateway with filters to address complex enterprise needs, such as security integrations and response modifications. Their talk demystified the gateway’s reactive stack, offering tips to avoid pitfalls and encouraging developers to harness its flexibility for performant, modular solutions.

Understanding Spring Cloud Gateway’s Power

Abel and Marta began by positioning Spring Cloud Gateway as a reactive, high-performance component that sits between clients and upstream services, enabling request and response manipulation. Unlike a one-to-one gateway tutorial, their session assumed basic familiarity, focusing on advanced customizations. They highlighted the gateway’s filter-based architecture, where filters operate in a chain, processing requests and responses in a defined order. This modularity allows developers to inject cross-cutting concerns like security or logging without altering upstream services. The duo emphasized the gateway’s potential to modernize legacy systems or split monoliths, making it a strategic tool for enterprise architectures.

Custom Filters for Security Integration

A key demo showcased how to implement OAuth security using Spring Cloud Gateway filters, integrating with Okta for token validation. Abel demonstrated two filters: one validating OAuth tokens using Spring Security’s resource server configuration, and another extracting claims (e.g., username) from the token to forward as HTTP headers to an upstream service unaware of OAuth. This approach isolates security logic in the gateway, sparing upstream services from modification. The demo, scripted with HTTPbin as the upstream service, illustrated a real-world scenario where a client authenticates with Okta, sends a token to the gateway, and receives a response with enriched headers. Abel stressed avoiding manual token validation, leveraging Spring Security’s reactive components to ensure performance and maintainability.

Dynamic Configuration and Response Modification

Marta explored the gateway’s configuration flexibility, demonstrating how to parametrize filters dynamically via YAML. A simple filter adding request headers was enhanced to accept multiple header configurations, reducing the need for multiple filter instances and improving performance. In a more complex example, Marta tackled modifying JSON responses from an upstream service, a common requirement when legacy APIs cannot be altered. Using a custom converter and the ModifyResponseBodyFilter, she transformed JSON fields based on YAML-defined key-value pairs, processing the response once to optimize performance. Marta cautioned about the performance risks of response modification, urging developers to carefully design configurations for scalability.

Best Practices and Community Insights

Abel and Marta concluded with practical advice for Spring Cloud Gateway adoption. They advocated for modular filter design to encapsulate features, enabling easy composition via YAML or actuator endpoints for runtime updates. They warned against reinventing solutions, citing cases where developers manually parsed JWTs instead of using Spring Security. The duo recommended reactive Spring libraries to avoid blocking issues and highlighted the gateway’s testing challenges, pointing to their GitHub repository for code examples. A nod to Spencer Gibb’s announcement about exploring MVC support for Spring Cloud Gateway underscored the project’s evolving potential. Their session inspired attendees to experiment with the gateway’s capabilities, leveraging its documentation and community resources.

Links:

PostHeaderIcon [Spring I/O 2023] Managing Spring Boot Application Secrets: Badr Nass Lahsen

In a compelling session at Spring I/O 2023, Badr Nasslahsen, a DevSecOps expert at CyberArk, tackled the critical challenge of securing secrets in Spring Boot applications. With the rise of cloud-native architectures and Kubernetes, secrets like database credentials or API keys have become prime targets for attackers. Badr’s talk, enriched with demos and real-world insights, introduced CyberArk’s Conjur solution and various patterns to eliminate hard-coded credentials, enhance authentication, and streamline secrets management, fostering collaboration between developers and security teams.

The Growing Threat to Application Secrets

Badr opened with alarming statistics: in 2021, software supply chain attacks surged by 650%, with 71% of organizations experiencing such breaches. He cited the 2022 Uber attack, where a PowerShell script with hard-coded credentials enabled attackers to escalate privileges across AWS, Google Suite, and other systems. Using the SALSA threat model, Badr highlighted vulnerabilities like compromised source code (e.g., Okta’s leaked access token) and build processes (e.g., SolarWinds). These examples underscored the need to eliminate hard-coded secrets, which are difficult to rotate, track, or audit, and often exposed inadvertently. Badr advocated for “shifting security left,” integrating security from the design phase to mitigate risks early.

Introducing Application Identity Security

Badr introduced the concept of non-human identities, noting that machine identities (e.g., SSH keys, database credentials) outnumber human identities 45 to 1 in enterprises. These secrets, if compromised, grant attackers access to critical resources. To address this, Badr presented CyberArk’s Conjur, an open-source secrets management solution that authenticates workloads, enforces policies, and rotates credentials. He emphasized the “secret zero problem”—the initial secret needed at application startup—and proposed authenticators like JWT or certificate-based authentication to solve it. Conjur’s attribute-based access control (ABAC) ensures least privilege, enabling scalable, auditable workflows that balance developer autonomy and security requirements.

Patterns for Securing Spring Boot Applications

Through a series of demos using the Spring Pet Clinic application, Badr showcased five patterns for secrets management in Kubernetes. The API pattern integrates Conjur’s SDK, using Spring’s @Value annotations to inject secrets without changing developer workflows. The Secrets Provider pattern updates Kubernetes secrets from Conjur, minimizing code changes but offering less security. The Push-to-File pattern stores secrets in shared memory, updating application YAML files securely. The Summon pattern uses a process wrapper to inject secrets as environment variables, ideal for apps relying on such variables. Finally, the Secretless Broker pattern proxies connections to resources like MySQL, hiding secrets entirely from applications and developers. Badr demonstrated credential rotation with zero downtime using Spring Cloud Kubernetes, ensuring resilience for critical applications.

Enhancing Kubernetes Security and Auditing

Badr cautioned that Kubernetes secrets, being base64-encoded and unencrypted by default, are insecure without etcd encryption. He introduced KubeScan, an open-source tool to identify risky roles and permissions in clusters. His demos highlighted Conjur’s auditing capabilities, logging access to secrets and enabling security teams to track usage. By centralizing secrets management, Conjur eliminates “security islands” created by disparate tools like AWS Secrets Manager or Azure Key Vault, ensuring compliance and visibility. Badr stressed the need for a federated governance model to manage secrets across diverse technologies, empowering developers while maintaining robust security controls.

Links:

Hashtags: #SecretsManagement #SpringIO2023 #SpringBoot #CyberArk #BadrNassLahsen

PostHeaderIcon [PHPForumParis2022] A Rusty PHP Extension – Pierre Tondereau

Pierre Tondereau, a developer with a passion for exploring new technologies, captivated attendees at PHP Forum Paris 2022 with his engaging exploration of creating PHP extensions using Rust. Drawing from his personal journey of discovering Rust in 2021, Pierre shared a compelling narrative about leveraging this modern language to enhance PHP’s capabilities. His presentation, rooted in a practical experiment, highlighted Rust’s potential to improve security and streamline development, offering a fresh perspective on extending PHP’s functionality.

Why Rust for PHP Extensions?

Pierre began by introducing Rust, a language developed by Mozilla in 2015 to refactor their HTML rendering engine, prioritizing performance and memory safety. Unlike traditional PHP extensions written in C, which demand meticulous memory management to avoid security vulnerabilities, Rust offers robust safety guarantees. Pierre explained how Rust’s design eliminates common issues like null pointer dereferences, making it an appealing choice for PHP developers unfamiliar with C’s complexities. He emphasized that his goal was not to rewrite PHP’s virtual machine but to create a secure, efficient extension using the ext-php-rs crate.

Building and Distributing Extensions

Delving into the technical process, Pierre outlined how the ext-php-rs crate simplifies PHP extension development by abstracting the Zend API. He demonstrated wrapping Rust APIs for PHP userland, using tools like cargo-php to streamline building and installation. Pierre highlighted the crate’s comprehensive coverage, which handled his use case effectively, though he encouraged community feedback to expand its capabilities. By automating distribution, Rust enables developers to integrate extensions seamlessly, enhancing PHP’s ecosystem with minimal friction.

Security and Future Potential

Concluding, Pierre underscored Rust’s security benefits, citing its ability to prevent memory-related vulnerabilities that plague C-based extensions, such as those impacting Google Chrome. He referenced Microsoft’s 2019 shift toward prioritizing security over performance, reinforcing Rust’s relevance. Pierre invited developers to explore his GitHub repository and contribute to ext-php-rs, fostering a collaborative push toward safer, more reliable PHP extensions. His talk inspired attendees to consider Rust as a viable tool for modernizing PHP development.

Links:

PostHeaderIcon [Devoxx France 2022] Securing Applications with HTTP Headers: A Survey of Attacks and Defenses

At Devoxx France 2022, Mathieu Humbert, a tech lead at Accenture with over 15 years of development experience, navigates the complex landscape of HTTP security headers. Mathieu demystifies headers like CSP, HSTS, XFO, and CORS, explaining their role in protecting web applications from threats like XSS, CSRF, and SSRF. Through a clear and engaging presentation, he outlines common attacks, their risks, and how specific headers can mitigate them, concluding with practical tools and resources for implementation.

Understanding HTTP Security Headers

Mathieu begins by introducing HTTP security headers as critical tools for safeguarding web applications. He explains headers like Content Security Policy (CSP), which restricts the sources from which content can be loaded, and HTTP Strict Transport Security (HSTS), which enforces HTTPS connections. These headers, though complex, are essential for mitigating risks in an ever-evolving threat landscape. Mathieu’s experience at Accenture informs his approach, emphasizing that understanding the purpose of each header is key to effective implementation.

By mapping headers to specific threats, Mathieu provides clarity on their practical applications. For instance, Cross-Site Scripting (XSS) attacks, where malicious scripts are injected into web pages, can be mitigated with CSP, while Cross-Site Request Forgery (CSRF) risks are reduced through proper header configurations. His accessible explanations make the technical subject approachable, ensuring developers grasp the importance of these defenses.

Mitigating Common Web Attacks

Delving into specific attacks, Mathieu outlines how headers counter vulnerabilities. He discusses XSS, where attackers exploit input fields to inject harmful code, and CSRF, where unauthorized actions are triggered on behalf of users. Headers like X-Frame-Options (XFO) prevent clickjacking by restricting how pages are framed, while CORS configurations ensure safe cross-origin requests. Mathieu also addresses Server-Side Request Forgery (SSRF), highlighting headers that limit unauthorized server requests.

Through real-world examples, Mathieu illustrates the consequences of neglecting these headers, such as data breaches or session hijacking. He stresses that proactive header implementation can significantly reduce these risks, providing a robust first line of defense for web applications. His insights, drawn from years of tackling technical challenges, underscore the necessity of staying vigilant in a dynamic threat environment.

Practical Implementation and Tools

Mathieu offers actionable guidance for integrating security headers into development workflows. He recommends starting with tools like OWASP’s Security Headers Project, which provides comprehensive documentation for configuring headers effectively. For testing, he suggests platforms like WebGoat, designed to simulate vulnerabilities, allowing developers to practice identifying and fixing issues. Mathieu also highlights the importance of automated scanners, such as Burp Suite, to detect missing or misconfigured headers.

His experience with distributed architectures and agile teams at Accenture informs his practical approach. Mathieu advises incremental implementation, starting with critical headers like HSTS and CSP, and regularly reviewing configurations to adapt to new threats. This methodical strategy ensures that security remains a priority without overwhelming development teams.

Hashtags: #WebSecurity #HTTPHeaders #Cybersecurity #DevoxxFR2022 #MathieuHumbert #Accenture #OWASP

PostHeaderIcon [DevoxxFR 2022] Log4Shell: Is It the Apache Foundation’s Fault?

At Devoxx France 2022, Emmanuel Lécharny, Jean-Baptiste Onofré, and Hervé Boutemy, all active contributors to the Apache Software Foundation, tackle the infamous Log4Shell vulnerability that shook the tech world in December 2021. Their collaborative presentation dissects the origins, causes, and responses to the Log4J security flaw, addressing whether the Apache Foundation bears responsibility. By examining the incident’s impact, the trio provides a transparent analysis of open-source security practices, offering insights into preventing future vulnerabilities and fostering community involvement. Their expertise and candid reflections make this a vital discussion for developers and organizations alike.

Unpacking the Log4Shell Incident

Emmanuel, Jean-Baptiste, and Hervé begin by tracing the history of Log4J and the emergence of Log4Shell, a critical vulnerability that allowed remote code execution, impacting countless systems worldwide. They outline the technical root causes, including flaws in Log4J’s message lookup functionality, which enabled attackers to exploit untrusted inputs. The presenters emphasize the rapid response from the Apache community, which released patches and mitigations under intense pressure, highlighting the challenges of maintaining widely-used open-source libraries.

The session provides a sobering look at the incident’s widespread effects, from internal projects to global enterprises. By sharing a detailed post-mortem, the trio illustrates how Log4Shell exposed vulnerabilities in dependency management, urging organizations to prioritize robust software supply chain practices.

Apache’s Security Practices and Challenges

The presenters delve into the Apache Foundation’s approach to managing Common Vulnerabilities and Exposures (CVEs). They explain that the foundation relies on a small, dedicated group of volunteer committers—often fewer than 15 per project—making comprehensive code reviews challenging. Emmanuel, Jean-Baptiste, and Hervé acknowledge that limited resources and the sheer volume of contributions can create gaps, as seen in Log4Shell. However, they defend the open-source model, noting its transparency and community-driven ethos as strengths that enable rapid response to issues.

They highlight systemic challenges, such as the difficulty of auditing complex codebases and the reliance on volunteer efforts. The trio calls for greater community participation, emphasizing that open-source projects like Apache thrive on collective contributions, which can enhance security and resilience.

Solutions and Future Prevention

To prevent future vulnerabilities, Emmanuel, Jean-Baptiste, and Hervé propose several strategies. They advocate for enhanced code review processes, including automated tools and mandatory audits, to catch issues early. They also discuss the potential for increased funding to support open-source maintenance, noting that financial backing could enable more robust security practices. However, they stress that money alone is insufficient; better organizational structures and community engagement are equally critical.

The presenters highlight emerging regulations, such as those in the U.S. and Europe, that hold software vendors accountable for their dependencies. These laws underscore the need for organizations to actively manage their open-source components, fostering a collaborative relationship between developers and users to ensure security.

Engaging the Community

In their closing remarks, the trio urges developers to become active contributors to open-source projects like Apache. They emphasize that even small contributions, such as reporting issues or participating in code reviews, can significantly enhance project security. Jean-Baptiste, Emmanuel, and Hervé invite attendees to engage with the Apache community, noting that projects like Log4J rely on collective effort to thrive. Their call to action underscores the shared responsibility of securing the open-source ecosystem, making it a compelling invitation for developers to get involved.

Hashtags: #Log4Shell #OpenSource #Cybersecurity #DevoxxFR2022 #EmmanuelLécharny #JeanBaptisteOnofré #HervéBoutemy #Apache

PostHeaderIcon [DevoxxFR 2022] Do You Really Know JWT?

Do You Really Know JWT? Insights from Devoxx France 2022

Karim Pinchon, a backend developer at Ornikar, delivered an illuminating talk titled “Do You Really Know JWT?” (watch on YouTube). With a decade of experience across Java, PHP, and Go, Karim dives into JSON Web Tokens (JWT), a standard for secure data transfer in authentication and authorization. This session explores JWT’s structure, cryptographic foundations, vulnerabilities, and best practices, moving beyond common usage in OAuth2 and OpenID Connect.

Understanding JWT Structure and Cryptography

Karim begins by demystifying JWT, a compact, secure token for transferring JSON data, often used in HTTP headers for authentication. A JWT comprises three parts—header, payload, and signature—encoded in Base64 and concatenated with dots. The header specifies the cryptographic algorithm (e.g., HMAC, RSA), the payload contains claims (data), and the signature ensures integrity. Karim demonstrates this using jwt.io, showing how decoding reveals JSON objects.

He distinguishes token types: reference tokens (database-backed) and value tokens (self-contained, like JWT). JWT supports two forms: compact (Base64-encoded) and JSON (with additional features like multiple signatures). Karim introduces related standards under JOSE (JSON Object Signing and Encryption), including JWS (signed tokens), JWE (encrypted tokens), JWK (key management), and JWA (algorithms). Cryptographic operations like signing (for integrity) and encryption (for confidentiality) underpin JWT’s security.

Payload Claims and Use Cases

The payload is JWT’s core, divided into three claim types:

  • Registered Claims: Standard fields like issuer (iss), audience (aud), expiration (exp), and token ID (jti) for validation.
  • Public Claims: Defined by IANA for protocols like OpenID Connect, carrying user data (e.g., name, email) in ID tokens.
  • Private Claims: Custom data agreed upon by parties, kept minimal for compactness.

Karim highlights JWT’s versatility in:

  • API Authentication: Tokens in Authorization headers validate requests without database lookups.
  • OAuth2: Access tokens may be JWTs, carrying authorization data.
  • OpenID Connect: ID tokens propagate user identity.
  • Stateless Sessions: Storing session data (e.g., e-commerce carts) client-side, enhancing scalability.

He cautions that stateless sessions require careful implementation to avoid complexity.

Security Vulnerabilities and Attacks

Karim dedicates significant time to JWT’s security risks, demonstrating attacks via a PHP library on his GitHub. Common vulnerabilities include:

  • Unsecured Tokens: Setting the header’s algorithm to none bypasses signature verification, a flaw exploited in some libraries. Karim shows a test where a modified token passes validation due to this.
  • RSA Public Key as Shared Key: An attacker changes the algorithm from RSA to HMAC, using the public key as a shared secret, tricking servers into validating tampered tokens.
  • Brute Force: Weak secrets (e.g., “azerty”) are vulnerable to brute-force attacks.
  • Encrypted Data Modification: Some encryption algorithms allow payload tampering (e.g., flipping is_admin from false to true) without breaking the cipher.
  • Token Substitution: Using a token from one service (where the user is admin) on another without proper audience validation.

Karim emphasizes the JWT paradox: the header, which specifies validation details, can’t be trusted until the token is validated. He attributes these issues to developers’ reliance on unvetted libraries, not poor coding.

Best Practices for Secure JWT Usage

To mitigate risks, Karim offers practical advice:

  • Protect Secrets: Use strong, rotated keys. Avoid sharing symmetric keys with external partners; prefer asymmetric keys (e.g., RSA).
  • Restrict Algorithms: Servers should only accept predefined algorithms (e.g., one or two), ignoring the header’s alg field.
  • Validate Claims: Check issaud, and exp to ensure the token’s legitimacy. Reject tokens not intended for your service.
  • Use Trusted Libraries: Avoid custom implementations. Modern libraries require explicit algorithm whitelists, reducing none algorithm risks.
  • Short Token Lifespans: Minimize revocation needs with short-lived tokens. Avoid external revocation lists, as they undermine JWT’s autonomy.
  • Ensure Confidentiality: Since JWS payloads are Base64-encoded (readable), avoid sensitive data. Use JWE for encryption if needed, and transmit over HTTPS.

Karim also mentions alternatives like Biscuits (from Clever Cloud), PASETO, and Google’s Macaroons, which address JWT’s flaws, such as untrusted headers.

Hashtags: #DevoxxFrance #KarimPinchon #JWT #Security #Cryptography #Authentication #Authorization #OAuth2 #OpenIDConnect #JWS #JWE #JWK #Ornikar #PHP #Java

PostHeaderIcon [Devoxx Poland 2022] Understanding Zero Trust Security with Service Mesh

At Devoxx Poland 2022, Viktor Gamov, a dynamic developer advocate at Kong, delivered an engaging presentation on zero trust security and its integration with service mesh technologies. With a blend of humor and technical depth, Viktor demystified the complexities of securing modern microservice architectures, emphasizing a philosophy that eliminates implicit trust to bolster system resilience. His talk, rich with practical demonstrations, offered developers and architects actionable insights into implementing zero trust principles using tools like Kong’s Kuma service mesh, making a traditionally daunting topic accessible and compelling.

The Philosophy of Zero Trust

Viktor begins by challenging the conventional notion of trust, using the poignant analogy of The Lion King to illustrate its exploitable nature. Trust, he argues, is a vulnerability when relied upon for system access, as it can be manipulated by malicious actors. Zero trust, conversely, operates on the premise that no entity—human or service—should be inherently trusted. This philosophy, not a product or framework, redefines security by requiring continuous verification of identity and access. Viktor outlines four pillars critical to zero trust in microservices: identity, automation, default denial, and observability. These principles guide the secure communication between services, ensuring robust protection in distributed environments.

Identity in Microservices

In the realm of microservices, identity is paramount. Viktor likens service identification to a passport, issued by a trusted authority, which verifies legitimacy without relying on trust. Traditional security models, akin to fortified castles with IP-based firewalls, are inadequate in dynamic cloud environments where services span multiple platforms. He introduces the concept of embedding identity within cryptographic certificates, specifically using the Subject Alternative Name (SAN) in TLS to encode service identities. This approach, facilitated by service meshes like Kuma, allows for encrypted communication and automatic identity validation, reducing the burden on individual services and enhancing security across heterogeneous systems.

Automation and Service Mesh

Automation is a cornerstone of effective zero trust implementation, particularly in managing the complexity of certificate generation and rotation. Viktor demonstrates how Kuma, a CNCF sandbox project built on Envoy, automates these tasks through its control plane. By acting as a certificate authority, Kuma provisions and rotates certificates seamlessly, ensuring encrypted mutual TLS (mTLS) communication between services. This automation alleviates manual overhead, enabling developers to focus on application logic rather than security configurations. During a live demo, Viktor showcases how Kuma integrates a gateway into the mesh, enabling mTLS from browser to service, highlighting the ease of securing traffic in real-time.

Deny by Default and Observability

The principle of denying all access by default is central to zero trust, ensuring that only explicitly authorized communications occur. Viktor illustrates how Kuma’s traffic permissions allow precise control over service interactions, preventing unauthorized access. For instance, a user service can be restricted to only communicate with an invoice service, eliminating wildcard permissions that expose vulnerabilities. Additionally, observability is critical for detecting and responding to threats. By integrating with tools like Prometheus, Loki, and Grafana, Kuma provides real-time metrics, logs, and traces, enabling developers to monitor service interactions and maintain an up-to-date system overview. Viktor’s demo of a microservices application underscores how observability enhances security and operational efficiency.

Practical Implementation with Kuma

Viktor’s hands-on approach culminates in a demonstration of deploying a containerized application within a Kuma mesh. By injecting sidecar proxies, Kuma ensures encrypted communication and centralized policy management without altering application code. He highlights advanced use cases, such as leveraging Open Policy Agent (OPA) to enforce fine-grained access controls, like restricting a service to read-only HTTP GET requests. This infrastructure-level security decouples policy enforcement from application logic, offering flexibility and scalability. Viktor’s emphasis on developer-friendly tools and real-time feedback loops empowers teams to adopt zero trust practices with minimal friction, fostering a culture of security-first development.

Hashtags: #ZeroTrust #ServiceMesh #Microservices #Security #Kuma #Kong #DevoxxPoland #ViktorGamov

PostHeaderIcon [ScalaDays 2019] Preserving Privacy with Scala

At ScalaDays Lausanne 2019, Manohar Jonnalagedda and Jakob Odersky, researchers turned industry innovators, unveiled a Scala-powered approach to secure multi-party computation (MPC) at EPFL’s 10th anniversary conference. Their talk, moments before lunch, captivated attendees with a protocol to average salaries without revealing individual data, sparking curiosity about privacy-preserving applications. Manohar and Jakob, from Inpher, detailed a compiler transforming high-level code into secure, distributed computations, addressing real-world challenges like GDPR-compliant banking and satellite collision detection, earning applause and probing questions on security and scalability.

A Privacy-Preserving Protocol

Manohar opened with a relatable scenario: wanting to compare salaries with Jakob without disclosing personal figures. Their solution, a privacy-preserving protocol, lets three parties—Manohar, Jakob, and their CTO Dmitar—compute an average securely. Each generates three random numbers summing to zero, sharing them such that each party holds a unique view of partial sums. In Scala, this is modeled with a SecretValue type for private integers and a SharedNumber list, accessible only by the corresponding party. Each sums their shares, publishes the result, and the final sum reveals the average without exposing individual salaries. This protocol, using random shares, ensures no single party can deduce another’s data unless all communications are intercepted, balancing simplicity and security.

Secure Multi-Party Computation

Jakob explained MPC as a cryptographic subfield enabling joint function computation without revealing private inputs. The salary example used addition, but MPC supports multiplication via Beaver triplets, precomputed by a trusted dealer for efficiency. With addition and multiplication, MPC handles polynomials, enabling linear and logistic regression or exponential approximations via Taylor polynomials. Manohar highlighted Scala’s role in modeling these operations, with functions for element-wise addition and revealing sums. The protocol achieves information-theoretic security for integers, where masked values are indistinguishable, but floating-point numbers require computational security due to distribution challenges. This flexibility makes MPC suitable for complex computations, from machine learning to statistical analysis, all while preserving privacy.

Real-World Applications

MPC shines in domains where data sensitivity or legal constraints, like GDPR, restrict sharing. Manohar cited ING, a bank building credit-scoring models across European countries without moving user data across borders, complying with GDPR. Another compelling case involved satellite operators—American, Russian, or Chinese—secretly computing collision risks to avoid incidents like the 2009 Iridium-Cosmos crash, which threatened the International Space Station. Jakob emphasized that Inpher’s XOR platform, legally vetted by Baker McKenzie, ensures GDPR compliance by keeping data at its source. These use cases, from finance to defense, underscore MPC’s value in enabling secure collaboration, with Scala providing a robust, type-safe foundation for protocol implementation.

Building a Compiler for MPC

To scale MPC beyond simple embeddings, Manohar and Jakob’s team developed a compiler at Inpher, targeting a high-level language resembling Python or Scala for data scientists. This compiler transforms linear algebra-style code into low-level primitives for distributed execution across parties’ virtual machines, verified to prevent data leaks. It performs static analysis to optimize memory and communication, inferring masking parameters to minimize computational overhead. For example, multiplying masked floating-point numbers risks format explosion, so the compiler uses fixed-point representations and statistical bounds to maintain efficiency. The output, resembling assembly for MPC engines, manages memory allocation and propagates data dimensions. While currently MPC-focused, the compiler’s design could integrate other privacy techniques, offering a versatile platform for secure computation.

Hashtags: #ScalaDays2019 #Scala #Privacy #MPC

PostHeaderIcon [DevoxxPL2019] GraphQL in the Java Ecosystem: A Comprehensive Exploration

Lecturer

Vladimir Dejanović is a seasoned software professional with over a decade of experience in the IT industry, having contributed to diverse projects since 2006. As Senior Director of B2C Technology at PVH, a fashion technology firm overseeing brands like Tommy Hilfiger and Calvin Klein, he focuses on scalable systems and innovative solutions. Beyond his corporate role, Vladimir founded and leads the Amsterdam Java User Group, fostering community engagement in Java technologies. He is recognized as an Oracle Code One Star and Java Rockstar, frequently delivering presentations at international conferences on topics like GraphQL and Java development.

Abstract

This article delves into the intricacies of GraphQL as applied within Java environments, examining its specification, implementation strategies, and practical applications through code demonstrations. It analyzes the advantages of GraphQL over traditional REST APIs, such as enhanced query flexibility and schema validation, while addressing potential pitfalls like cyclic dependencies and security concerns. Drawing from real-world examples, the discussion highlights methodologies for schema design, resolver integration, and performance optimization, underscoring GraphQL’s role in modern API development and its implications for system architecture.

Understanding GraphQL: Beyond the Basics

GraphQL emerges as a pivotal specification in API design, originating from Facebook in 2015 to address inefficiencies in data fetching encountered during mobile application development. Unlike conventional REST APIs, which often result in over-fetching or under-fetching of data, GraphQL empowers clients to request precisely the information needed, thereby optimizing network usage and enhancing performance. The specification defines a query language that allows for declarative data retrieval, where clients specify the structure of the response, aligning closely with application requirements.

At its core, GraphQL is not a full-fledged framework but a set of guidelines that various languages implement differently. In Java, implementations like GraphQL Java provide the engine for processing queries, while tools such as GraphQL Java Kickstarters facilitate integration with existing infrastructures, such as Spring Boot. This flexibility means developers must be cognizant of implementation-specific nuances, including coverage of the specification and additional features not mandated by the core rules. For instance, while the specification mandates schema validation, implementations may vary in handling extensions like custom scalars or error propagation.

The schema definition language (SDL) stands out as GraphQL’s most potent feature, surpassing alternatives like OpenAPI in expressiveness. It requires a mandatory schema that describes types, fields, and relationships, ensuring both client and server adhere to a contract. Upon connection, the server transmits the schema, enabling clients to validate requests locally before transmission, which reduces invalid traffic and conserves resources. This schema-first approach, preferred for its mockability, allows teams to prototype APIs independently: backend developers define the schema, while frontend teams use mocks to simulate responses.

Consider a practical scenario involving a conference application with entities like attendees, speakers, and talks. The schema might define types as follows:

type Attendee {
  id: ID!
  name: String
}

type Speaker {
  id: ID!
  name: String
  twitter: String
}

type Talk {
  id: ID!
  title: String
  description: String
  speakers: [Speaker]
}

Here, the exclamation mark denotes mandatory fields, and arrays indicate relationships. This structure not only documents the API but also enforces consistency, preventing outdated documentation—a common issue in REST environments.

Implementing Queries and Resolvers in Java

Transitioning to code, integrating GraphQL in Java involves wiring the schema to business logic. Using Spring Boot and GraphQL Java, one initializes a servlet mapped to “/graphql”, parsing the schema and registering resolvers. Resolvers act as the bridge, implementing interfaces like GraphQLQueryResolver for read operations.

For the conference example, a Query class might look like this:

@Component
public class Query implements GraphQLQueryResolver {
  private final TalkService talkService;
  private final SpeakerService speakerService;
  private final AttendeeService attendeeService;

  @RequiredArgsConstructor
  public Query(TalkService talkService, SpeakerService speakerService, AttendeeService attendeeService) {
    this.talkService = talkService;
    this.speakerService = speakerService;
    this.attendeeService = attendeeService;
  }

  public List<Talk> allTalks() {
    return talkService.findAll();
  }

  public List<Speaker> allSpeakers() {
    return speakerService.findAll();
  }

  public List<Attendee> allAttendees() {
    return attendeeService.findAll();
  }
}

This setup enables queries like fetching all talks with specific fields:

query {
  allTalks {
    id
    title
    description
    speakers {
      name
      twitter
    }
  }
}

The response mirrors the query structure in JSON, promoting predictability. Clients can alias fields (e.g., renaming “title” to “myTitle”) or conditionally include them using directives like @include(if: $variable), where variables are passed separately for dynamic behavior.

Resolvers for relationships, such as linking talks to speakers, extend GraphQLResolver:

@Component
public class TalkResolver implements GraphQLResolver<Talk> {
  private final SpeakerService speakerService;

  @RequiredArgsConstructor
  public TalkResolver(SpeakerService speakerService) {
    this.speakerService = speakerService;
  }

  public List<Speaker> speakers(Talk talk) {
    return speakerService.findAllSpeakersForTalk(talk);
  }
}

This modular approach allows for granular control, but it introduces risks like cyclic queries if bidirectional links (e.g., speakers to talks) are added without safeguards. Such cycles can lead to infinite loops, necessitating depth limits during validation.

Mutations: Enabling Data Modification

While queries handle reads, mutations facilitate writes, mirroring CRUD operations but with GraphQL’s precision. Defined similarly in the schema:

type Mutation {
  addTalk(input: TalkInput!): Talk
}

Mutations require explicit input types to encapsulate parameters, ensuring type safety. In Java, a Mutation resolver implements GraphQLMutationResolver:

@Component
public class Mutation implements GraphQLMutationResolver {
  private final TalkService talkService;

  @RequiredArgsConstructor
  public Mutation(TalkService talkService) {
    this.talkService = talkService;
  }

  public Talk addTalk(TalkInput input) {
    // Logic to create and persist talk
    return talkService.save(input.toTalk());
  }
}

This method processes inputs, validates them, and returns the updated entity. Unlike queries, which can execute in parallel for optimization, mutations are sequential to maintain data integrity. Errors in mutations propagate similarly to queries, with customizable handlers to continue processing or halt execution.

The implications are profound: mutations reduce boilerplate compared to REST’s multiple endpoints, centralizing logic while allowing clients to request related data in the same response, such as fetching the newly added talk’s speakers.

Subscriptions: Real-Time Data Streams

Subscriptions introduce reactive capabilities, enabling server-push updates over WebSockets. The schema defines:

type Subscription {
  scores(title: String!): Score
}

type Score {
  title: String
  score: Int
}

In Java, using Reactor for reactivity:

@Component
public class Subscription implements GraphQLSubscriptionResolver {
  public Publisher<Score> scores(String title) {
    return Flux.interval(Duration.ofSeconds(2))
      .map(i -> Score.builder()
        .title(title)
        .score(ThreadLocalRandom.current().nextInt(1, 6))
        .build());
  }
}

This generates scores every two seconds, demonstrating backpressure handling to prevent client overload. Subscriptions transform static APIs into dynamic ones, ideal for live updates like conference feedback, though implementation varies—GraphQL Java uses WebSockets, but the specification leaves transport open.

Security and Performance Considerations

Security in GraphQL demands vigilance, as the schema’s public nature exposes potential attack vectors. Authentication and authorization occur via custom contexts:

public class MyGraphQLContext extends GraphQLContext {
  private final User user;

  public MyGraphQLContext(User user) {
    this.user = user;
  }
}

Resolvers access this context via DataFetchingEnvironment to enforce roles. For schema protection, directives or instrumentation filter visibility, though non-standard approaches risk interoperability.

Performance pitfalls include N+1 queries, mitigated by batching or caching in services. Instrumentation traces execution:

public class TracingInstrumentation extends SimpleInstrumentation {
  @Override
  public InstrumentationContext<ExecutionResult> beginExecution(InstrumentationExecutionParameters parameters) {
    // Start timer, log query
    return super.beginExecution(parameters);
  }
}

Query complexity analysis during validation prevents denial-of-service attacks by capping depth or computational cost.

Schema management in large systems involves stitching or extensions to avoid monolithic files:

extend type Speaker {
  twitter: String
}

This federates schemas across services, though conflicts require governance.

Implications for Modern Development

GraphQL’s client-centric model shifts power from servers, fostering agile development but requiring robust safeguards. In Java, its integration with Spring Boot streamlines adoption, yet demands awareness of implementation variances. By enabling precise data fetching and real-time interactions, it addresses REST’s limitations, promoting efficient, scalable architectures. Future specification enhancements, like improved subscription standards, promise broader applicability.

Links: