ProgrammingPro #48: Safeguarding Web Apps, C++ Safety Debate, HTMX Software Simplicity, Java's JDK 22, & AI Analytics SDK
Bite-sized actionable content, practical tutorials, and resources for programmers
Welcome to this week’s edition of ProgrammingPro!
In today’s Expert Insight, we bring you an excerpt from the recently published book, Security-Driven Software Development, that takes you through methods for safeguarding web applications against CSRF attacks and ensuring secure session management.
News Highlights: Bjarne Stroustrup counters White House C++ safety concerns, Carson Gross discusses reducing software complexity with HTMX, JDK 22 introduces new Java features, and Sisense launches an SDK for AI-powered analytics.
My top 5 picks from today’s learning resources:
Expedia Speeds up Flights Search with Micro Frontends and GraphQL Optimizations✈️
Leading tech people or staying a software engineer - What to choose?🤔
But there’s more, so dive right in.
Stay Awesome!
Divya Anne Selvaraj
Editor-in-Chief
PS: If you have any food for thought, feedback, or would like us to find you a specific Programming learning resource for our next issue, take the survey!
🗞️News and Analysis🔎
C++ creator rebuts White House warning: Bjarne Stroustrup, the creator of C++, has countered the Biden administration's critique by highlighting the language's modern safety features and ongoing development to enhance security. Read to learn about C++'s safety mechanisms and its evolution towards better safety.
Complexity bad - An interview with HTMX creator Carson Gross: In this interview, Gross discusses the impetus behind HTMX and Hyperscript. Read for insights into effective software engineering practices from a seasoned developer and educator.
JDK 22 now available - What’s new?: Java 22 introduces scoped values, structured concurrency, stream gatherers, and enhancements for running multi-file programs, among its 12 features. Read to learn about the latest Java features aimed at simplifying programming tasks.
Sisense releases new SDK to enable developers to build AI-powered analytics experiences into their applications: This SDK facilitates the creation of dynamic queries, charts, and filters, aiming to streamline the development process. Read for insights into how the SDK improves the development cycle and user experience.
Microsoft defends .NET 9’s fresh feature against accusations of disrupting open source ecosystem: Microsoft's introduction of an Eventing Framework in .NET 9 has stirred concerns among open source developers. Read to listen in on the ongoing dialogue between Microsoft and the developer community.
AWS Introduces A New JavaScript Runtime For Lambda: Designed specifically for Lambda, Low Latency Runtime (LLRT) is optimized for minimal cold start times due to its tiny size, significantly smaller than existing runtimes like Node.js, Deno, and Bun. Read to learn more.
🎓Tutorials and Learning Resources💡
Python
🎓Tutorial | How to use uv - A superfast Python package installer: uv simplifies Python project management by integrating functionalities of existing tools and enhancing workflows. Read to learn how to install uv, create virtual environments, and manage dependencies.
🎓Tutorial | Work with Python in Visual Studio: This six-part tutorial on using Python in Visual Studio, covers project creation, coding with IntelliSense, interactive REPL usage, debugging, package management, and Git integration. Read to gain insights into efficiently organizing projects and leveraging Visual Studio's features.
Python Function Pipelines - Streamlining Data Processing: Function pipelines enhance code modularity, readability, and maintainability by allowing the output of one function to serve as the input for the next. Read to learn the principles and benefits of using function pipelines in Python for data processing.
For more Python resources go to PythonPro
C# and .NET
🎓Tutorial | How to use the REPR design pattern in ASP.NET Core: This design pattern simplifies API development in ASP.NET Core by promoting code maintainability, reusability, and separation of concerns. Read to learn how you can overcome common challenges such as controller bloat.
Why reaching 100% Code Coverage must NOT be your testing goal (with examples in C#): This article emphasizes that while code coverage is a useful metric in testing, aiming for 100% coverage can be misleading and does not guarantee bug-free software. Read to learn why balance matters through examples.
R3 — A New Modern Reimplementation of Reactive Extensions for C#: This article introduces R3 designed as the third generation after Rx for .NET and UniRx. Read for insights into modernizing reactive programming practices within the C# ecosystem.
C and C++
C++ exit-time destructors: This article discusses the mechanisms and implications of C++ exit-time destructors, detailing strategies for managing or avoiding them to enhance program efficiency and safety. Read to learn about the mechanisms and implications of exit-time destructors.
On the costs of asynchronous abstractions: This article discusses the performance implications of asynchronous abstractions in C++, particularly within the context of using Boost.Asio for networking tasks like multiplexing Redis commands. Read to discover strategies to mitigate performance issues.
A comparison of C compilers targeting the STM8: This article provides a detailed comparison of C compilers targeting the STM8 microcontroller as of early 2024, covering aspects such as standard compliance, code quality, operating system support, and licensing. Read to be able to select the most suitable C compiler for your STM8 microcontroller projects.
Java
Getting cozy with Java's new, softer side: Java's introduction of var, auto-compile, text blocks, and record classes, has enhanced the language’s flexibility and ease of use. Read for code examples demonstrating each feature and the new switch expression syntax.
Billions of Messages Per Minute Over TCP/IP: Chronicle Software's open source Wire library, now supports TCP/IP, and can efficiently process billions of messages per minute, ensuring data consistency and low-latency in Java-based distributed applications. Read for detailed code examples and walkthroughs.
🎓Tutorial | Mastering Exception Handling in Java Lambda Expressions: This tutorial addresses the challenges of handling checked exceptions due to the nature of functional interfaces not declaring them. Read to enhance the resilience and reliability of your Java applications.
JavaScript and TypeScript
🎓Tutorial | Creating Your First JavaScript Game - A Step-by-Step Guide: This tutorial takes you through creating a JavaScript game using HTML canvas, where a player jumps over obstacles to score points. Read to learn the foundational elements of creating an interactive game.
A Javascript Nightmare: In this article, the author recounts a troubleshooting saga involving JavaScript and AWS, where PDF exports failed unpredictably, leading to a late-night debugging session. Read for insights into debugging in complex, interconnected systems and the importance of understanding library dependencies.
🎓Tutorial | Angular Components and Display: Understanding the Non-Block Default: This tutorial explains Angular components and their default non-block display, emphasizing the intentional design choice to encourage developers to explicitly define component display styles. Read to discover strategies for effectively styling component displays for responsive web applications.
Tutorial | Building a RESTful API with TypeScript, Fastify, TypeORM, and PostgreSQL: This tutorial covers setup, database creation, and route configuration. Read for a step-by-step guide for setting up a RESTful API using modern tools and practices.
Go
More powerful Go execution traces: Recent improvements address previous limitations, reducing runtime CPU overhead to 1-2% and introducing scalable traces that require less memory for analysis. Read to learn how the updates can aid in diagnosing and resolving performance issues and concurrency bottlenecks.
Measuring your system’s performance using software (Go edition): This comprehensive guide outlines the use of software, specifically in Go, to measure system performance. Read to learn various techniques and tools available in Go for measuring and optimizing software performance.
Rust
Rust for C#/.NET Developers: This guide is for C#/.NET developers new to Rust and offers comparisons and mappings of concepts with examples. Read for an easier transition into Rust programming while recognizing key differences and similarities.
How I Improved My Rust Compile Times by 75%: The author of this article improved Rust compile times by exploring optimizations like Mold linker, Cranelift code generator, and adjusting optimization levels. Read to learn how to implement these optimizations.
📖Open Book | The Rust Programming Language, 2nd Ed: This book covers a comprehensive range of topics including I/O projects, iterators, smart pointers, concurrency, and macros. Read to learn more.
PHP
🎓Tutorial | Unlocking PHP Generators: Revolutionizing Memory Efficiency: Introduced in PHP 5.5, Generators facilitate iterating over data sets without the memory burden of storing arrays, by generating values on demand with yield. Read to learn how to adopt Generators and more memory-efficient coding practices.
SQL
We built a new SQL Engine on Arrow and DataFusion: Arroyo 0.10 is introducing a new SQL engine leveraging Apache Arrow and DataFusion, offering significantly improved performance, reduced complexity, and enhanced community integration. Read to learn more.
Ruby
🎓Tutorial | Practical Railway-Oriented Pipelines in Ruby: This article presents a Railway-oriented design pattern for building composable processing pipelines in Ruby, demonstrating its practical application for complex data workflows. Read to learn a structured method to build data processing workflows in Ruby.
Swift
🎓Tutorial | Introducing the Benchmark Package - Complementing Unit Tests with Performance Checks: This article introduces a tool for complementing unit tests with performance checks in Swift applications. Read to learn how to integrate and utilize the Benchmark package for systematic performance testing.
Kotlin
Top 10 Kotlin Code Snippets to Keep Handy: This curated list higlights features like delegated properties, smart casts, the Elvis operator, and more, aimed at improving productivity and code quality in Kotlin projects. Read for more.
Scala
Caching in Spark | What? How? Why?: This article discusses caching in Apache Spark, explaining its importance in enhancing program efficiency through persistent storage to avoid recomputation of RDDs. Read to learn about caching strategies and storage levels available in Spark.
🌟Best Practices, Advice, and Case Studies🚀
2024 Cheat Sheet Collection: This collection provides you with essential resources across general programming and specialized areas. Read to gain quick access to information across various programming languages and technologies.
Expedia Speeds up Flights Search with Micro Frontends and GraphQL Optimizations: Expedia enhanced its flight search speed by up to 52% by implementing Micro Frontend Architecture and GraphQL optimizations. Read for insights into the importance of structured architectural approaches and efficient data handling.
eBay’s Lessons Learned about Generative AI in Software Development Productivity: eBay has enhanced its software development productivity by applying generative AI through integrating commercial solutions like GitHub Copilot, fine-tuning LLMs such as Code Lllama, and utilizing an internal knowledge network. Read for insights into the benefits of generative AI in software development.
Leading tech people or staying a software engineer - What to choose?: In a panel discussion, tech leaders shared insights on choosing between leadership and staying technical. Read to learn about the challenges and rewards of transitioning into tech leadership roles.
Data Flow Diagrams (DFDs) for Software Engineering: This article covers the basics of DFDs, including their components and creation process, and uses an inventory management system as an example to illustrate how DFDs can be applied to design test cases. Read to learn how to create and leverage DFDs for better system understanding and design.
Take the Survey, Request a Resource
🧠 Expert Insight 📚
Here’s an exclusive excerpt from “Chapter 9, Standard Web Application Vulnerabilities” in the book, Security-Driven Software Development by Aspen Olmsted.
Example of enterprise web defenses
Throughout this book, we will build a secure design for an event ticketing system. Envision a software system that allows a box office or a website to sell tickets to a famous musical concert or theatre event. In the previous chapter, we covered code that will properly validate and sanitize input, which is the best defense against XSS.
The next chapter will look at code to defend against SQL injection. (Before that, let us look at an example).
To defend against CSRF attacks in PHP, you can use anti-CSRF tokens. Here’s a simple example of how to implement CSRF protection using tokens:
Generate a CSRF token on the server side and include it in the form.
Verify the token when processing the form submission.
Here’s the example PHP code:
<?php
session_start();
session_regenerate_id();
function generateCSRFToken() {
$token = bin2hex(random_bytes(32)); // Generate a random token
$_SESSION['csrf_token'] = $token; // Store it in the session
return $token;
}
function validateCSRFToken($token) {
return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
// Generate token when rendering the form
$csrfToken = generateCSRFToken();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>CSRF Protected Form</title>
</head>
<body>
<form action="process_form.php" method="post">
<!-- Include the CSRF token in the form -->
<input type="hidden" name="csrf_token" value="<?php echo
$csrfToken; ?>">
<!-- Your other form fields go here -->
<button type="submit">Submit</button>
</form>
</body>
</html>
In the process_form.php file that is located on the server processed when the above client HTML form is submitted:
<?php
session_start();
// Validate CSRF token before processing the form data
if ($_SERVER['REQUEST_METHOD'] === 'POST' && validateCSRFToken($_POST['csrf_token'])) {
// Process the form data
// ...
// After processing, regenerate a new CSRF token for the next form
//submission
$newCSRFToken = generateCSRFToken();
} else {
// CSRF token validation failed
// Handle the error or redirect as needed
}
?>
This example uses the random_bytes function to generate a random token and the hash_equals function to compare the stored token with the one submitted in the form. Additionally, the token is regenerated after each successful form submission to mitigate the risk of token reuse. The code requires PHP7 or greater for the random_bytes function. It is important to ensure your PHP environment has a supported version with all the latest patches.
We also want to have secure session management in our enterprise ticketing management. Secure session management is crucial for the security of web applications. Here are some best practices for secure session management in PHP:
Use session cookies securely: Set the session.cookie_secure option to true in your PHP configuration to ensure that cookies are only sent over HTTPS. Set the session.cookie_httponly option to true to prevent JavaScript from accessing the session cookie:
ini_set('session.cookie_secure', true);
ini_set('session.cookie_httponly', true);
Use a strong session ID generator: PHP uses a random number generator by default, but you can enhance it by setting session.entropy_length and session.entropy_file. Ensure that these values are configured appropriately for your environment:
ini_set('session.entropy_length', 32);
ini_set('session.entropy_file', '/dev/urandom');
Regenerate session ID: Regenerate the session ID periodically to mitigate session fixation attacks. Use session_regenerate_id():
session_regenerate_id(true);
Set session timeout: Set a reasonable session timeout to expire sessions automatically after a certain period of inactivity:
ini_set('session.gc_maxlifetime', 1800); // 30 minutes
Store sessions securely: Choose a secure session storage mechanism. PHP sessions can be stored in files, databases, or custom handlers. Ensure proper access controls for the session storage directory:
// Example using a custom session save path
session_save_path('/path/to/secure/session/directory');
Use session hashing: If you store sessions in a database, hash the session data to add an extra layer of security.
Implement session expiry: Implement your session expiry mechanism to ensure that sessions are correctly cleaned up when they expire.
Handle session data carefully: Avoid storing sensitive information directly in the session. If necessary, encrypt sensitive data before storing it.
Regularly review and audit: Review and audit your session management implementation for security vulnerabilities.
By following these best practices, you can enhance the security of session management in your PHP applications and reduce the risk of session-related attacks. Remember that security is an ongoing process; staying informed about the latest best practices and vulnerabilities is essential.
Packt library subscribers can continue reading for free here. Security-Driven Software Development by Aspen Olmsted was published in March 2024. You can buy the book here!
🛠️ Useful Tools ⚒️
Guac: Graph for Understanding Artifact Composition (GUAC), an incubating project under the Open Source Security Foundation, aims to enhance software supply chain security through dependency management and security insights, supported by key tech and financial entities.
gritql: a declarative query language for code search and modification, supporting multiple languages and offering scalability, pattern reuse, and easy learning without AST knowledge.
gpt-pilot: a revolutionary addition to the Pythagora VS Code extension, GPT Pilot transforms AI from a basic autocomplete tool into a full-fledged developer companion capable of crafting features, debugging, and collaborating on projects.
That’s all for today.
We have an entire range of newsletters with focused content for tech pros. Subscribe to the ones you find the most useful here. Complete ProgrammingPro archives can be found here. Complete PythonPro archives are here.
📢 If your company is interested in reaching an audience of developers, software engineers, and tech decision makers, you may want to advertise with us.
If you have any feedback, leave a comment below.