Recent Posts
Archives

Archive for the ‘General’ Category

PostHeaderIcon [NodeCongress2021] Safely Handling Dynamic Data with TypeScript – Ethan Arrowood

In the realm of full-stack development, where APIs shuttle payloads across boundaries, ensuring type fidelity amid flux poses a perennial puzzle. Ethan Arrowood, a software engineer at Microsoft, navigates this terrain adeptly, advocating schemas as sentinels against runtime surprises. His discourse spotlights TypeScript’s prowess in taming erratic inputs—from form submissions to auth tokens—via symbiotic validation frameworks.

Ethan posits data as the lifeblood of modern apps: JSON’s ubiquity powers endpoints, yet its pliancy invites mismatches. Consider an employee dossier: id, name, employed boolean, company, age, projects array. Static typings guard assignments, but external fetches evade compile-time checks, risking undefined accesses or coerced primitives. Ethan’s remedy? Leverage JSON Schema for declarative constraints, transmuting fluid objects into rigid molds.

Bridging Schemas and Static Guarantees

Enter @sinclair/typebox, a runtime validator that births schemas from TypeScript generics, yielding dual benefits: enforcement and inference. Ethan illustrates with Fastify routes: define bodySchema as TypeBox’s TObject, embedding TString for id/name, TOptional(TBoolean) for employed, mirroring anticipated shapes. This artifact doubles as validator—Fastify’s schema prop ingests it for payload scrutiny—and type oracle, infusing handlers with precise annotations.

In practice, a POST endpoint parses body as TInfer, affording intellisense: body.name yields string, body.age number|undefined. Ethan live-codes this synergy, hovering reveals nested generics—TArray(TString) for projects—ensuring downstream ops like array iterations sidestep guards. Should validation falter, Fastify aborts with 400s, averting tainted flows.

This fusion extends to broader ecosystems: io-ts for branded types, Zod for ergonomic chaining. Ethan cautions reliance on validation logic; a flawed schema propagates peril, echoing JavaScript’s untyped underbelly. Yet, when aligned, it forges ironclad pipelines, where dynamic ingress aligns seamlessly with static egress.

Real-World Integrations and Ecosystem Synergies

Ethan’s Fastify demo crystallizes the workflow: register plugins, await readiness, log addresses— all scaffolded atop schema-derived types. VS Code’s hover unveils the schema’s blueprint, from optional fields to array innards, streamlining refactoring. For authentication, schemas vet JWT claims; forms, user inputs—universal applicability.

Gratitude flows to undraw for visuals, highlight.js for syntax, and tmcw/big for slides, underscoring open-source’s scaffolding role. Ethan’s ethos—connect via GitHub/Twitter—invites dialogue, amplifying Node.js and TypeScript’s communal momentum. By entwining validation with typing, developers reclaim assurance, rendering volatile data a predictable ally in resilient architectures.

Links:

PostHeaderIcon [PHPForumParis2021] Design Patterns Explained to Children – Vincent Laurier

Vincent Laurier, a former mathematics teacher turned PHP developer, enchanted the Forum PHP 2021 audience with a unique approach to explaining design patterns through storytelling. Drawing on his recently published book, Vincent used a narrative style to make complex concepts accessible, likening design patterns to characters in a children’s tale. His talk blended pedagogy with practical advice, offering insights into both coding and project realization. This post covers three themes: simplifying design patterns, the circle of realization, and sharing knowledge through storytelling.

Simplifying Design Patterns

Vincent Laurier began by demystifying design patterns, presenting them as intuitive solutions to common coding challenges. Using analogies from his book, he likened patterns like Singleton and Factory to characters with distinct roles, making them relatable for developers of all levels. Vincent’s pedagogical background shone through as he avoided technical jargon, ensuring that even complex concepts like dependency injection were accessible. His approach, rooted in his passion for teaching, encouraged developers to view patterns as tools for clearer, more maintainable code.

The Circle of Realization

A key concept in Vincent’s talk was the “circle of realization,” a framework for turning ideas into completed projects. He described this as a cyclical process with five entry points—representing stages like ideation, planning, and execution—that developers must navigate to bring projects to fruition. Vincent emphasized maintaining momentum by addressing challenges at each stage, ensuring projects don’t stall in the “world of ideas.” This metaphor, drawn from his book, resonated with attendees seeking to complete personal or professional projects.

Sharing Knowledge Through Storytelling

Vincent concluded by highlighting the power of storytelling in knowledge transfer. His book, available in both French and English on platforms like Amazon, uses narratives to teach design patterns, reflecting his belief that stories engage and educate effectively. By sharing his journey of writing and publishing, Vincent inspired developers to communicate complex ideas simply, fostering collaboration and learning within the PHP community. His talk underscored the value of creative pedagogy in technical education.

Links:

PostHeaderIcon [DevoxxFR 2022] Père Castor 🐻, raconte-nous une histoire (d’OPS)

Lors de Devoxx France 2022, David Aparicio, Data Ops chez OVHcloud, a partagé une conférence de 44 minutes sur l’apprentissage à partir des échecs en opérations informatiques. David a analysé les post-mortems d’incidents majeurs survenus chez des géants comme GitHub, Amazon, Google, OVHcloud, Apple, Fastly, Microsoft, GitLab et Facebook. En explorant les causes racines, les remédiations et les bonnes pratiques, il a montré comment tirer des leçons des erreurs pour renforcer la résilience des systèmes. Suivez OVHcloud sur ovhcloud.com et twitter.com/OVHcloud.

Comprendre les post-mortems

David a commencé par expliquer ce qu’est un post-mortem : un document rédigé après un incident pour comprendre ce qui s’est passé, identifier les causes et prévenir les récurrences. Il inclut l’historique de l’incident, les flux d’information, l’organisation (qui a agi, avec quelle équipe), les canaux de communication avec les clients, l’utilisation des ressources et les processus suivis. David a souligné l’importance de la transparence, citant des initiatives comme les meetups de développeurs où les échecs sont partagés pour démystifier les incidents.

Il a illustré son propos avec une histoire fictive d’Elliot, un junior qui, par erreur, supprime une base de données de production en suivant une documentation mal structurée. Cet incident, inspiré de cas réels chez AWS (2017), GitLab et DigitalOcean, montre les dangers d’un accès non contrôlé à la production. David a recommandé des garde-fous comme des approbations manuelles pour les commandes critiques (par exemple, DROP TABLE), des rôles RBAC stricts, et des tests réguliers des backups pour garantir leur fiabilité.

Les incidents personnels : le legacy à l’épreuve

David a partagé une expérience personnelle chez OVHcloud, où il gère le data lake pour répliquer les données internes. Lors d’une astreinte, un week-end d’été, il a été alerté d’un problème sur une infrastructure legacy sans documentation claire. Un service saturait sa file de connexions (1024 clients maximum), provoquant des refus. Sans réponse des développeurs, David a opté pour une solution KISS (Keep It Simple, Stupid) : une sonde vérifiant la connectivité toutes les cinq minutes, redémarrant le service si nécessaire. Ce script, en place depuis un an et demi, a redémarré le service 70 fois, évitant de nouveaux incidents.

Un autre incident concernait une application Java legacy, tombant après 20 à 40 minutes malgré des redémarrages. Les logs montraient des déconnexions ZooKeeper et des crashs JVM. Plutôt que d’ajuster la mémoire (heap tuning), David a découvert un script de nettoyage propriétaire dans l’historique. Appliqué deux fois par semaine, ce script a résolu le problème durablement. Ces cas illustrent l’importance de comprendre le legacy, d’éviter les solutions complexes et de documenter les correctifs.

Les pannes majeures : CDN et réseaux

David a analysé l’incident Fastly de juin 2021, où une erreur 503 a touché des sites comme The Guardian, The New York Times, Amazon, Twitter et la Maison Blanche. La cause : une configuration client déployée sans test le 8 juin, activée par une demande du 12 mai, révélant un point de défaillance unique (SPoF) dans le CDN. Résolu en 45 minutes, cet incident souligne l’importance de tester les changements en pré-production (par exemple, via blue-green deployments ou shadow traffic) et de personnaliser les messages d’erreur pour améliorer l’expérience utilisateur.

Un autre cas marquant est la panne Facebook de septembre 2021, causée par une mise à jour du protocole BGP (Border Gateway Protocol). Les serveurs DNS, incapables d’accéder aux datacenters, se sont mis en mode protection, coupant l’accès à Facebook, Instagram, WhatsApp et même aux outils internes (Messenger, LDAP). Les employés ne pouvaient ni badger ni consulter la documentation, obligeant une intervention physique avec des disqueuses pour accéder aux racks. David a recommandé des TTL (Time To Live) plus longs pour les DNS, des canaux de communication séparés et des routes de secours via d’autres cloud providers.

Bonnes pratiques et culture de l’échec

David a conclu en insistant sur la nécessité de ne pas blâmer les individus, comme dans le cas d’Elliot, mais de renforcer les processus. Il a proposé des tests réguliers de backups, des exercices de chaos engineering (par exemple, simuler une erreur 500 un vendredi après-midi), et l’adoption de pratiques DevSecOps pour intégrer la sécurité dès les tests unitaires. Il a également suggéré de consulter les post-mortems publics (comme ceux de GitLab ou ElasticSearch) pour s’inspirer et d’utiliser des outils comme Terraform pour automatiser les déploiements sécurisés. Enfin, il a encouragé à rejoindre OVHcloud pour expérimenter et apprendre des incidents dans un environnement transparent.

PostHeaderIcon [NodeCongress2021] Instrumenting Node.js Internals – Alejandro Oviedo

Delving into the intricacies of runtime diagnostics reveals a persistent challenge for Node.js developers: unraveling opaque behaviors in live applications without invasive alterations. Alejandro Oviedo, a backend specialist from Buenos Aires, confronts this head-on by unveiling “instrument,” an open-source utility he crafted to illuminate network flows, filesystem interactions, and module loadings. This innovation stems from his encounters with elusive glitches, where conventional logging falls short, compelling a quest for non-disruptive observability.

Alejandro’s journey underscores a universal frustration—debugging sans exceptions or traces leaves one adrift, akin to navigating fog-shrouded waters. Even in controlled dev setups, grasping async invocations or dependency chains demands more than intuition. His tool intervenes subtly, wrapping native modules like HTTP, HTTPS, or FS to log invocations without reshaping source code, thus preserving original outputs while appending diagnostic summaries.

Enhancing Visibility Through Modular Wrappers

At the heart of instrument lies a configuration-driven approach, where users specify modules in an instrument.config.js file—HTTP for endpoint reconnaissance, REQUIRE for dynamic imports. Alejandro demonstrates with npm’s version query: invoking via instrument yields the anticipated 8.2.1 for Mocha, trailed by a concise report on GET requests to registry.npmjs.org, complete with user-agent headers and CI flags. This granularity exposes externalities, from URL patterns to payload details, sans performance penalties in non-prod realms.

Extending to refactoring scenarios, imagine auditing dynamic loads in an HTTP server; static analyzers falter against runtime evaluations, but instrument excels, flagging module_a.js imports across probes. Alejandro stresses its dev-centric ethos: add as a devDependency, execute with npx instrument node app.js, and harvest insights effortlessly. Caveats abound—overhead precludes prod use, and nascent bugs invite community scrutiny via GitHub.

Yet, this simplicity belies profound utility. By demystifying internals, developers sidestep trial-and-error marathons, accelerating triage from hours to moments. Alejandro’s creation not only empowers solo coders but fosters collaborative ecosystems, where shared configs standardize diagnostics across teams. In an era of sprawling Node.js deployments, such tools bridge the observability chasm, ensuring applications hum reliably under scrutiny.

Fostering Community-Driven Refinements

Alejandro invites scrutiny, urging PRs and issues on the repository, while teasing a Q&A for deeper dives. His Buenos Aires roots and international contributions—local meetups to global forums—infuse the project with grassroots vigor, mirroring Node.js’s collaborative spirit. As environments evolve, instrument’s extensibility promises adaptations, perhaps integrating with APMs for holistic tracing.

Through this lens, troubleshooting morphs from art to science, equipping practitioners to dissect and mend with precision. Alejandro’s endeavor reminds us: true resilience blooms from visibility, not obscurity.

Links:

PostHeaderIcon Kafka Streams @ Carrefour : Traitement big data à la vitesse de l’éclair

Lors de Devoxx France 2022, François Sarradin et Jérémy Sebayhi, membres des équipes data de Carrefour, ont partagé un retour d’expérience de 45 minutes sur l’utilisation de Kafka Streams pour des pipelines big data en temps réel. François, technical lead chez Moshi, et Jérémy, ingénieur senior chez Carrefour, ont détaillé leur transition des systèmes batch Spark et Hadoop vers un traitement stream réactif sur Google Cloud Platform (GCP). Leur talk a couvert l’adoption de Kafka Streams pour le calcul des stocks et des prix, les défis rencontrés et les solutions créatives mises en œuvre. Découvrez Carrefour sur carrefour.com et Moshi sur moshi.fr.

Du batch au stream processing

François et Jérémy ont débuté en comparant le traitement batch et stream. La plateforme legacy de Carrefour, datant de 2014, reposait sur Spark et Hadoop pour des jobs batch, traitant les données comme des fichiers avec des entrées et sorties claires. Les erreurs étaient gérables en corrigeant les fichiers d’entrée et en relançant les pipelines. Le streaming, en revanche, implique des flux d’événements continus via des topics Kafka, où les erreurs nécessitent une gestion en temps réel sans perturber le pipeline. Un événement corrompu ne peut être simplement supprimé, car les données historiques peuvent couvrir des années, rendant le reprocessing impraticable.

Kafka Streams, un framework réactif basé sur Apache Kafka, a permis à Carrefour de passer au stream processing. Il exploite Kafka pour un transit de données scalable et RocksDB pour un stockage d’état colocalisé à faible latence. François a expliqué que les développeurs définissent des topologies—graphes acycliques dirigés (DAG) similaires à ceux de Spark—avec des opérations comme map, flatMap, reduce et join. Kafka Streams gère automatiquement la création des topics, les stores d’état et la résilience, simplifiant le développement. L’intégration avec les services GCP (GCS, GKE, BigTable) et les systèmes internes de Carrefour a permis des calculs de stocks et de prix en temps réel à l’échelle nationale.

Surmonter les défis d’adoption

Adopter Kafka Streams chez Carrefour n’a pas été sans obstacles. Jérémy a noté que beaucoup d’équipes manquaient d’expérience avec Kafka, mais la familiarité avec Spark a facilité la transition, les deux utilisant des paradigmes de transformation similaires. Les équipes ont développé indépendamment des pratiques pour le monitoring, la configuration et le déploiement, consolidées ensuite en best practices partagées. Cette approche pragmatique a créé une base commune pour les nouveaux projets, accélérant l’adoption.

Le changement nécessitait une adaptation culturelle au-delà des compétences techniques. La plateforme data de Carrefour, gérant des volumes massifs et des données à haute vélocité (stocks, prix, commandes), exigeait un changement de mindset du batch vers le réactif. Le stream processing implique des jointures continues avec des bases externes, contrairement aux datasets statiques des batchs. François et Jérémy ont souligné l’importance d’une documentation précoce et d’un accompagnement expert pour naviguer dans les complexités de Kafka Streams, surtout lors des déploiements en production.

Bonnes pratiques et architectures

François et Jérémy ont partagé les pratiques clés émergées sur deux ans. Pour les schémas des topics, ils utilisaient Schema Registry pour typer les données, préférant des clés obligatoires pour assurer la stabilité des partitions et évitant les champs optionnels pour prévenir les ruptures de contrat. Les valeurs des messages incluaient des champs optionnels pour la flexibilité, avec des champs obligatoires comme les IDs et timestamps pour le débogage et l’ordonnancement des événements.

Maintenir des topologies stateful posait des défis. Ajouter de nouvelles transformations (par exemple, une nouvelle source de données) nécessitait de retraiter les données historiques, risquant des émissions dupliquées. Ils ont proposé des solutions comme les déploiements blue-green, où la nouvelle version construit son état sans produire de sortie jusqu’à ce qu’elle soit prête, ou l’utilisation de topics compactés comme snapshots pour stocker uniquement le dernier état par clé. Ces approches minimisaient les perturbations mais exigeaient une planification rigoureuse, les déploiements blue-green doublant temporairement les besoins en ressources.

Métriques et monitoring

Le monitoring des applications Kafka Streams était crucial. François a mis en avant des métriques clés : lag (messages en attente par topic/consumer group), indiquant les points de contention ; end-to-end latency, mesurant le temps de traitement par nœud de topologie ; et rebalance events, déclenchés par des changements de consumer group, pouvant perturber les performances. Carrefour utilisait Prometheus pour collecter les métriques et Grafana pour des dashboards, assurant une détection proactive des problèmes. Jérémy a insisté sur l’importance des métriques custom via une couche web pour les health checks, les métriques JMX de Kafka Streams n’étant pas toujours suffisantes.

Ils ont aussi abordé les défis de déploiement, utilisant Kubernetes (GKE) avec des readiness probes pour surveiller les états des applications. Une surallocation de CPU pouvait retarder les réponses aux health checks, causant des évictions de consumer groups, d’où l’importance d’un tuning précis des ressources. François et Jérémy ont conclu en vantant l’écosystème robuste de Kafka Streams—connecteurs, bibliothèques de test, documentation—tout en notant que sa nature événementielle exige un mindset distinct du batch. Leur expérience chez Carrefour a démontré la puissance de Kafka Streams pour des données en temps réel à grande échelle, incitant le public à partager ses propres retours.

PostHeaderIcon [PHPForumParis2021] Saving the Planet by Doing Less – Hélène Maitre-Marchois

Hélène Maitre-Marchois, a Scrum Master and co-founder of Fairness, delivered a thought-provoking presentation at Forum PHP 2021, urging developers to embrace digital sobriety to reduce the environmental impact of technology. Drawing on her work at Fairness, a cooperative focused on responsible digital solutions, Hélène challenged the audience to rethink feature development and prioritize sustainability. Her talk, blending ecological awareness with practical strategies, inspired developers to make impactful choices. This post explores four key themes: the environmental cost of digital technology, questioning feature necessity, optimizing user experience, and fostering sustainable practices.

The Environmental Cost of Digital Technology

Hélène Maitre-Marchois opened by highlighting the significant environmental footprint of digital technology, noting that it accounts for 3–4% of global greenhouse gas emissions, a figure growing by 8% annually. She emphasized that the internet is not intangible—data centers, networks, and user devices consume vast resources. Hélène referenced studies from GreenIT and The Shift Project, underscoring that user devices, with low recycling rates, contribute heavily to this impact. By framing coding as an energy-intensive activity, she urged developers to consider the ecological consequences of their work, from CPU usage to disk operations.

Questioning Feature Necessity

A core message of Hélène’s talk was the importance of challenging the need for every feature. She advocated for a “why” mindset, questioning whether functionalities truly serve users or merely satisfy client assumptions. Hélène shared examples where client-driven features, like flashy designs, were less valuable than anticipated when tested with users. By prioritizing minimal, purposeful development, developers can reduce resource consumption, aligning with the principles of eco-design that Fairness champions, ensuring applications are both functional and environmentally responsible.

Optimizing User Experience

Hélène stressed that sustainable design enhances user experience without sacrificing aesthetics. She suggested practical measures, such as using dark backgrounds to reduce screen energy consumption, as black pixels require less power than white ones on many displays. By optimizing user journeys and focusing on essential information, developers can create efficient, user-friendly applications. Hélène’s approach, rooted in her Scrum Master experience, emphasizes collaboration with designers and stakeholders to balance usability and sustainability, ensuring applications meet real user needs.

Fostering Sustainable Practices

Concluding her presentation, Hélène encouraged developers to adopt sustainable coding practices, such as optimizing database queries and choosing energy-efficient data formats. She highlighted the role of ethical designers and community initiatives like La Fresque du Numérique in promoting digital sobriety. By integrating these practices, developers can contribute to a cleaner internet, aligning with Fairness’ mission to build a responsible digital ecosystem. Hélène’s call to action inspired attendees to rethink their workflows and prioritize ecological responsibility in their projects.

Links:

PostHeaderIcon [DevoxFR 2022] Cracking Enigma: A Tale of Espionage and Mathematics

In his captivating 45-minute talk at Devoxx France 2022, Jean-Christophe Sirot, a cloud telephony expert from Sherweb, takes the audience on a historical journey through the cryptanalysis of the Enigma machine, used by German forces during World War II. Jean-Christophe weaves a narrative that blends espionage, mathematics, and technological innovation, highlighting the lesser-known contributions of Polish cryptanalysts like Marian Rejewski alongside Alan Turing’s famed efforts. His presentation, recorded in April 2022 in Paris, reveals how Enigma’s secrets were unraveled through a combination of human ingenuity and mathematical rigor, ushering cryptography into the modern era. This post summarizes the key themes, from early Polish breakthroughs to Turing’s machines, and reflects on their lasting impact.

The Polish Prelude: Cryptography in a Time of War

Jean-Christophe sets the stage in post-World War I Poland, a nation caught between Soviet Russia and a resurgent Germany. In 1919, during the Polish-Soviet War, Polish radio interception units, staffed by former German army officers, cracked Soviet codes, securing a decisive victory at the Battle of Warsaw. This success underscored the strategic importance of cryptography, prompting Poland to invest in codebreaking. By 1929, a curious incident at Warsaw’s central station revealed Germany’s use of Enigma machines. A German embassy official’s attempt to retrieve a misrouted “radio equipment” package—later identified as a commercial Enigma—alerted Polish intelligence.

Recognizing the complexity of Enigma, a machine with rotors, a reflector, and a plugboard generating billions of possible configurations, Poland innovated. Instead of relying on puzzle-solvers, as was common, they recruited mathematicians. At a new cryptography chair in western Poland, young talents like Marian Rejewski, Henryk Zygalski, and Jerzy Różycki began applying group theory and permutation mathematics to Enigma’s ciphers. Their work marked a shift from intuitive codebreaking to a systematic, mathematical approach, laying the groundwork for future successes.

Espionage and Secrets: The German Defector

The narrative shifts to 1931 Berlin, where Hans-Thilo Schmidt, a disgruntled former German officer, offered to sell Enigma’s secrets to the French. Schmidt, driven by financial troubles and resentment after being demobilized post-World War I, had access to Enigma key tables and technical manuals through his brother, an officer in Germany’s cipher bureau. Meeting French intelligence in Verviers, Belgium, Schmidt handed over critical documents. However, the French, lacking advanced cryptanalysis expertise, passed the materials to their Polish allies.

The Poles, already studying Enigma, seized the opportunity. Rejewski and his team exploited a flaw in the German protocol: operators sent a three-letter message key twice at the start of each transmission. Using permutation theory, they analyzed these repeated letters to deduce rotor settings. By cataloging cycle structures for all possible rotor configurations—a year-long effort—they cracked 70–80% of Enigma messages by the late 1930s. Jean-Christophe emphasizes the audacity of this mathematical feat, achieved with minimal computational resources, and the espionage that made it possible.

Turing and Bletchley Park: Scaling the Attack

As Germany invaded Poland in 1939, the Polish cryptanalysts shared their findings with the Allies, providing documentation and a reconstructed Enigma machine. This transfer was pivotal, as Germany had upgraded Enigma, increasing rotors from three to five and plugboard connections from six to ten, exponentially raising the number of possible keys. The Polish method, reliant on the repeated message key, became obsolete when Germany reduced repetitions to once.

Enter Alan Turing and the team at Bletchley Park, Britain’s codebreaking hub. Turing devised a new approach: the “known plaintext attack.” By assuming certain messages contained predictable phrases, like weather forecasts for the Bay of Biscay, cryptanalysts could test rotor settings. Turing’s genius lay in automating this process with the “Bombe,” an electromechanical device that tested rotor and plugboard configurations in parallel. Jean-Christophe explains how the Bombe used electrical circuits to detect inconsistencies in assumed settings, drastically reducing the time needed to crack a message. By running multiple Bombes, Bletchley Park decrypted messages within hours, providing critical intelligence that shortened the war by an estimated one to two years.

The Legacy of Enigma: Modern Cryptography’s Dawn

Jean-Christophe concludes by reflecting on Enigma’s broader impact. The machine, despite its complexity, was riddled with flaws, such as the inability to map a letter to itself and the exploitable key repetition protocol. These vulnerabilities, exposed by Polish and British cryptanalysts, highlighted the need for robust algorithms and secure protocols. Enigma’s cryptanalysis marked a turning point, transforming cryptography from a craft of puzzle enthusiasts to a rigorous discipline grounded in mathematics and, later, computer science.

He draws parallels to modern cryptographic failures, like the flawed WEP protocol for early Wi-Fi, which used secure algorithms but a weak protocol, and the PlayStation 3’s disk encryption, undone by poor key management. Jean-Christophe’s key takeaway for developers: avoid custom cryptography, use industry standards, and prioritize protocol design. The Enigma story, blending human drama and technical innovation, underscores the enduring importance of secure communication in today’s digital world.

Resources:

  • Enigma by Dermot Turing

  • Our Spy in Hitler’s Office by Paul Paillole

  • The Code Book by Simon Singh

  • The Codebreakers by David Kahn

PostHeaderIcon [DevoxxFR 2022] Exploiter facilement des fonctions natives avec le Projet Panama depuis Java

Lors de Devoxx France 2022, Brice Dutheil a présenté une conférence de 28 minutes sur le Projet Panama, une initiative visant à simplifier l’appel de fonctions natives depuis Java sans les complexités de JNI ou de bibliothèques tierces. Brice, contributeur actif à l’écosystème Java, a introduit l’API Foreign Function & Memory (JEP-419), montrant comment elle relie le monde géré de Java au code natif en C, Swift ou Rust. À travers des démonstrations de codage en direct, Brice a illustré le potentiel de Panama pour des intégrations natives fluides. Suivez Brice sur Twitter à twitter.com/Brice_Dutheil pour plus d’insights Java.

Simplifier l’intégration de code natif

Brice a débuté en expliquant la mission du Projet Panama : connecter l’environnement géré de Java, avec son garbage collector, au monde natif de C, Swift ou Rust, plus proche de la machine. Traditionnellement, JNI imposait des étapes laborieuses : écrire des classes wrapper, charger des bibliothèques et générer des headers lors des builds. Ces processus étaient sujets aux erreurs et chronophages. Des alternatives comme JNA et JNR amélioraient l’expérience développeur en générant des bindings au runtime, mais elles étaient plus lentes et moins sécurisées.

Lancé en 2014, le Projet Panama répond à ces défis avec trois composantes : les API vectorielles (non couvertes ici), les appels de fonctions étrangères et la gestion de la mémoire. Brice s’est concentré sur l’API Foreign Function & Memory (JEP-419), disponible en incubation dans JDK 18. Contrairement à JNI, Panama élimine les complexités du build et offre des performances proches du natif sur toutes les plateformes. Il introduit un modèle de sécurité robuste, limitant les opérations dangereuses et envisageant de restreindre JNI dans les futures versions de Java (par exemple, Java 25 pourrait exiger un flag pour activer JNI). Brice a souligné l’utilisation des method handles et des instructions d’invocation dynamique, inspirées des avancées du bytecode JVM, pour générer efficacement des instructions assembleur pour les appels natifs.

Démonstrations pratiques avec Panama

Brice a démontré les capacités de Panama via du codage en direct, commençant par un exemple simple appelant la fonction getpid de la bibliothèque standard C. À l’aide du SystemLinker, il a effectué une recherche de symbole pour localiser getpid, créé un method handle avec un descripteur de fonction définissant la signature (retournant un long Java), et l’a invoqué pour récupérer l’ID du processus. Ce processus a contourné les lourdeurs de JNI, nécessitant seulement quelques lignes de code Java. Brice a insisté sur l’activation de l’accès natif avec le flag –enable-native-access dans JDK 18, renforçant le modèle de sécurité de Panama en limitant l’accès à des modules spécifiques.

Il a ensuite présenté un exemple plus complexe avec la fonction crypto_box de la bibliothèque cryptographique Libsodium, portable sur des plateformes comme Android. Brice a alloué des segments de mémoire avec un ResourceScope et un NativeAllocator, garantissant la sécurité mémoire en libérant automatiquement les ressources après usage, contrairement à JNI qui dépend du garbage collector. Le ResourceScope prévient les fuites mémoire, une amélioration significative par rapport aux buffers natifs traditionnels. Brice a également abordé l’appel de code Swift via des interfaces compatibles C, démontrant la polyvalence de Panama.

Outils et potentiel futur

Brice a introduit jextract, un outil de Panama qui génère des mappings Java à partir de headers C/C++, simplifiant l’intégration de bibliothèques comme Blake3, une fonction de hachage performante écrite en Rust. Dans une démo, il a montré comment jextract créait des bindings compatibles Panama pour les structures de données et fonctions de Blake3, permettant aux développeurs Java de tirer parti des performances natives sans bindings manuels. Malgré quelques accrocs, la démo a souligné le potentiel de Panama pour des intégrations natives transparentes.

Brice a conclu en soulignant les avantages de Panama : simplicité, rapidité, compatibilité multiplateforme et sécurité mémoire renforcée. Il a noté son évolution continue, avec JEP-419 en incubation dans JDK 18 et une deuxième preview prévue pour JDK 19. Pour les développeurs d’applications desktop ou de systèmes critiques, Panama offre une solution puissante pour exploiter des fonctions spécifiques aux OS ou des bibliothèques optimisées comme Libsodium. Brice a encouragé le public à expérimenter Panama et à poser des questions, renforçant son engagement via Twitter.

PostHeaderIcon [NodeCongress2021] Security Testing for JS Apps, Node Congress – Ryan Severns

Application security need not impede developer agility; instead, it can integrate seamlessly into workflows. Ryan Severns, co-founder of StackHawk, presents a streamlined approach to vulnerability detection in JavaScript ecosystems, leveraging automation to unearth issues pre-production.

StackHawk automates dynamic analysis against JS apps and APIs—REST, GraphQL—flagging SQL injections or data leaks via CI/CD scans. On pull requests, scans mimic attacks, surfacing flaws with request/response evidence, expediting triages.

Automating Scans with ZAP Foundations

Built atop OWASP ZAP, StackHawk configures effortlessly for Node.js stacks, scanning SPAs or backends sans code mods. Post-scan, dashboards highlight exploits, with remediation docs and Jira integrations deferring low-risks, respecting only novel threats.

Integrating into DevSecOps Pipelines

Ryan emphasizes workflow harmony: GitHub Actions triggers validate endpoints, blocking merges on criticals while queuing fixes. Free tiers invite experimentation, blending security into Node.js velocity without friction.

Links:

PostHeaderIcon [PHPForumParis2021] Fiber: The Gateway to Asynchronous PHP – Benoit Viguier

Benoit Viguier, a developer at Bedrock, enthralled the Forum PHP 2021 audience with an exploration of PHP 8.1’s Fiber feature, a groundbreaking step toward asynchronous programming. With a history of discussing async development at AFUP events, Benoit shared early experiments with Fibers, positioning them as a future cornerstone of PHP. His talk blended technical insight with forward-thinking optimism, urging developers to embrace this new paradigm. This post covers three themes: understanding Fibers, practical applications, and the need for standards.

Understanding Fibers

Benoit Viguier introduced Fibers as a low-level feature in PHP 8.1, enabling lightweight, cooperative concurrency. Unlike traditional threading, Fibers allow developers to pause and resume execution without blocking the main thread, ideal for I/O-heavy tasks. Drawing on his work at Bedrock, Benoit explained how Fibers extend PHP’s async capabilities, building on libraries like Amphp and ReactPHP. His clear explanation demystified this cutting-edge feature for the audience.

Practical Applications

Delving into practical use cases, Benoit showcased how Fibers enhance performance in applications like Bedrock’s streaming platforms, such as 6play and Salto. By enabling non-blocking HTTP requests and database queries, Fibers reduce latency and improve user experience. Benoit shared early experiments, noting that while Fibers are not yet production-ready, their potential to streamline async workflows is immense, particularly for high-traffic systems requiring real-time responsiveness.

The Need for Standards

Benoit concluded by advocating for a standardized async ecosystem in PHP. He highlighted recent collaborations between Amphp and ReactPHP teams to propose a PSR standard for Fibers, fostering interoperability. By making libraries “Fiber-ready,” developers can create reusable, non-blocking APIs. Benoit’s vision for a unified async framework, inspired by his work at Bedrock, positions Fibers as a potential “killer feature” for PHP, encouraging community contributions to shape its future.

Links: