<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by PJ Fanning on Medium]]></title>
        <description><![CDATA[Stories by PJ Fanning on Medium]]></description>
        <link>https://medium.com/@pjfanning?source=rss-c43097c6c565------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*djejDy0otwUms942pwJ51g.jpeg</url>
            <title>Stories by PJ Fanning on Medium</title>
            <link>https://medium.com/@pjfanning?source=rss-c43097c6c565------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:32:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pjfanning/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Excel Formula Evaluation in Apache POI]]></title>
            <link>https://medium.com/@pjfanning/excel-formula-evaluation-in-apache-poi-92d9c81891ea?source=rss-c43097c6c565------2</link>
            <guid isPermaLink="false">https://medium.com/p/92d9c81891ea</guid>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[poi]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[apache-poi]]></category>
            <category><![CDATA[spreadsheets]]></category>
            <dc:creator><![CDATA[PJ Fanning]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 18:41:18 GMT</pubDate>
            <atom:updated>2025-06-18T18:41:18.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fo3M64cwQqku6jfO" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=medium&amp;utm_medium=referral">Lukas Blazek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://poi.apache.org/">Apache POI</a> is an open source library for reading and writing Microsoft format files, including Excel files.</p><p>The project is about 20 years old and unfortunately, the community is no longer very active. The Excel support is pretty good. Other document formats like Word and Powerpoint are supported but the support is not as strong.</p><h3>Formula Evaluation</h3><p>One area in Excel support that is underdeveloped is <a href="https://poi.apache.org/components/spreadsheet/eval.html">Formula Evaluation</a> (this link provides good examples of how to use this feature). POI has some support but not every function is supported. The newer the function, the less likely that it is supported. It is also possible that for some functions that we support some use cases but not all of them.</p><p>The thing is that many users don’t really need POI Formula Evaluation.</p><ul><li>If you are reading an existing file, Excel stores the evaluated values for each cell. POI can read these values as well as allowing access to the formula.</li><li>If you are using POI to write a new file or edit one, there is a method on the Workbook class (and all subclasses) to force Excel to re-evaluate the formulas at load time. Hopefully other Spreadsheet apps that support Excel files will obey this too.</li></ul><pre>wb.setForceFormulaRecalculation(true);</pre><p>If you do need to use POI’s FormulaEvaluator and you find that a function is missing or incorrect, you can <a href="https://poi.apache.org/components/spreadsheet/user-defined-functions.html">register</a> your own implementation.</p><p>The <a href="https://javadoc.io/static/org.apache.poi/poi/5.4.0/org/apache/poi/ss/formula/atp/AnalysisToolPak.html#registerFunction-java.lang.String-org.apache.poi.ss.formula.functions.FreeRefFunction-">registerFunction</a> method can reject function implementations if POI already has an implementation — but unfortunately this might have a bug or missing feature. In POI 5.4.2 (which is not yet released), an overloaded version of this method adds a boolean force parameter that allows you to replace the built-in implementation.</p><h3>Raising Issues</h3><p>If you find an issue, feel free to raise it. We currently use <a href="https://bz.apache.org/bugzilla/buglist.cgi?product=POI">Bugzilla</a>. I hope that we will soon also support GitHub issues at our mirrored <a href="https://github.com/apache/poi">repo</a>.</p><p>Unfortunately, we will probably ask you to consider adding the fix yourself. You can start by looking at existing functions implemented in the POI code and related test cases. One thing to watch out for is that we expect test cases for code changes and ideally, you would help add missing coverage. At a minimum, we should test the examples provided in the Microsoft documentation. The Excel <a href="https://support.microsoft.com/en-us/office/normdist-function-126db625-c53e-4591-9a22-c9ff422d6d58">NORMDIST</a> function page is one where you can see some basic worked examples.</p><p>There are some <a href="https://poi.apache.org/devel/index.html">docs</a> about building POI on our web site. There is a dedicated dev <a href="https://poi.apache.org/components/spreadsheet/eval-devguide.html">guide</a> for adding extra functions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92d9c81891ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pekko Akka Compatibility]]></title>
            <link>https://medium.com/@pjfanning/pekko-akka-compatibility-31c14217888a?source=rss-c43097c6c565------2</link>
            <guid isPermaLink="false">https://medium.com/p/31c14217888a</guid>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[cluster]]></category>
            <category><![CDATA[pekko]]></category>
            <dc:creator><![CDATA[PJ Fanning]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 20:24:36 GMT</pubDate>
            <atom:updated>2024-03-04T16:38:25.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*RKf7kPHlpkeWdyq7" /><figcaption>Statue of the Seto fertility god Peko, <a href="https://commons.wikimedia.org/wiki/User:Ohpuu">Ott Heinapuu</a> (<a href="https://creativecommons.org/publicdomain/zero/1.0/deed.en">CC0 1.0 Universal Public Domain Dedication</a>)</figcaption></figure><p><a href="https://pekko.apache.org/">Apache Pekko</a> is an Open Source fork of Akka that came about as a result of the Lightbend’s decision to <a href="https://www.lightbend.com/blog/why-we-are-changing-the-license-for-akka">switch</a> to a Business Software License.</p><p>We decided early on to remove as many references as possible to Akka (branding, package names, config names, etc.). We also changed the default ports (<a href="https://pekko.apache.org/docs/pekko/current/project/migration-guides.html">migration guide</a>). One of the results of this is that you should be able to use Akka and Pekko libs in the same JVM.</p><p>This came at the cost that you could not access Akka remote actors from Pekko and vice versa. You could not add Pekko nodes to an Akka cluster (and vice versa).</p><p>We have added features to <a href="https://pekko.apache.org/docs/pekko/current/release-notes/index.html#1-0-3-m1">Pekko 1.0.3-M1</a> to try to address these issues. This release is a milestone release and should not be used in production.</p><p>We were also recently made aware of an issue where Akka Persistence snapshots could not be read by <a href="https://pekko.apache.org/docs/pekko/current/typed/index-persistence.html">Pekko Persistence</a> (<a href="https://github.com/apache/incubator-pekko/pull/837">Pull Request</a>). There is a <a href="https://github.com/scullxbones/pekko-persistence-mongo/pull/14#issuecomment-1847223850">workaround</a> that has been described by Łukasz Krenski.</p><p>We would appreciate if users who are migrating from Akka Persistence to Pekko Persistence could test with the new release and notify us of the results.</p><p>A more complicated scenario that we would also like users to try out is trying to join <a href="https://pekko.apache.org/docs/pekko/current/typed/index-cluster.html">Pekko nodes</a> to a test environment Akka cluster — with an aim to replace the existing Akka nodes with Pekko nodes. The support in Pekko 1.0.3-M1 is described in our <a href="https://cwiki.apache.org/confluence/display/PEKKO/Pekko+Akka+Compatibility">wiki</a>.</p><p>I wrote some basic tests and put them in a GitHub <a href="https://github.com/pjfanning/pekko-akka-compat">project</a>. What we would appreciate is more real world test scenarios. You can contact the Apache Pekko team using the usual <a href="https://github.com/apache/incubator-pekko?tab=readme-ov-file#community">channels</a>.</p><p>Akka has recently <a href="https://www.lightbend.com/technical-support-for-apache-pekko">announced</a> some commercial technical support for Apache Pekko. I am not aware of what they are claiming to be the breaking changes in forthcoming Pekko 1.1.0-M1 release. We expect that this upgrade will be straightforward for users. If anyone has any ideas what we might have missed, please get in touch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31c14217888a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Number Parsing can be susceptible to DoS attacks]]></title>
            <link>https://systemweakness.com/number-parsing-can-be-susceptible-to-dos-attacks-a433fa83c640?source=rss-c43097c6c565------2</link>
            <guid isPermaLink="false">https://medium.com/p/a433fa83c640</guid>
            <category><![CDATA[denial-of-service-attack]]></category>
            <category><![CDATA[jackson]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[yaml]]></category>
            <category><![CDATA[parsing]]></category>
            <dc:creator><![CDATA[PJ Fanning]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 20:51:30 GMT</pubDate>
            <atom:updated>2023-04-25T10:01:08.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIyRBG7jVtQJxzCzLJrr_Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mika Baumeister</a> on <a href="https://unsplash.com/photos/Wpnoqo2plFA?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Any application that takes inputs from potentially untrusted sources should be investigated in case they are susceptible to Denial of Service attacks.</p><p>I’m writing this based on some work I’ve been doing on Java based applications. The built-in code in Java for parsing numbers has <a href="https://en.wiktionary.org/wiki/subquadratic">subquadratic</a> performance. Trying to parse a number with hundreds or thousands of digits can take a lot longer than you might expect. Your trusted users might be sending you numbers with up to 20 digits but a malicious user could send you thousands of digits.</p><p>Jackson now optionally supports <a href="https://github.com/wrandelshofer/FastDoubleParser">FastDoubleParser</a> and the readme on this project has some interesting analyses. Using this number parser improves performance but does not get rid of the DoS risks.</p><p>There are also some edge cases where a number with a small number of digits can take a surprisingly long time to process. Your application might support numbers with <a href="https://en.wikipedia.org/wiki/Scientific_notation">E Notation</a> (JSON allows this number format). A number like 1e200000000can take a large amount of time to convert to standard notation (and this might happen automatically in the libs you use to parse your API inputs).</p><p>You should not assume that the Java built-in methods or that any libraries that you use have automatic protection against malicious inputs. I think is safe to assume that not only Java based applications are susceptible to these attacks.</p><h3>Safe Number Parser</h3><p>I have released a Java library called <a href="https://github.com/pjfanning/safe-number-parser">safe-number-parser</a>. This lib has its own drop in replacements for some of the more problematic number types. The limits that are applied are customizable.</p><ul><li>SafeDouble</li><li>SafeFloat</li><li>SafeBigDecimal</li><li>SafeBigInteger</li></ul><p>If you use a lib to serialize/deserialize data, then you can use the number types from safe-number-parser instead of the standard Java ones. Because the classes extend java.lang.Number, many frameworks should handle serialization/deserialization of these classes automatically. You may find that you need to register custom serializers/deserializers though.</p><p>I had to write a module for Jackson to provide custom serializers/deserializers, for instance (<a href="https://github.com/pjfanning/jackson-datatype-safe-number">jackson-datatype-safe-number</a>). This lib works with versions of Jackson going back to Jackson 2.12.</p><h3>Jackson 2.15</h3><p>I contributed a lot of the number parsing and writing changes in the recent Jackson 2.15.0 release. Some of the improvements also appear in Jackson 2.14. There are a few other fixes related to lazy parsing of numbers which are useful for performance. Some of the numbers that appear in the input file may not need to be parsed.</p><p>Before upgrading to Jackson 2.15, you should consider the implications of its new <a href="https://javadoc.io/static/com.fasterxml.jackson.core/jackson-core/2.15.0/com/fasterxml/jackson/core/StreamReadConstraints.html">StreamReadConstraints</a>. Maybe, the defaults are too low for your needs and you might need to change your code to set your own StreamReadConstraints.</p><h3>Recommendations</h3><ul><li>Use the latest Java runtime. The JDK team have been fixing number parsing issues over the years. If, for instance, you must use Java 8 then you should use the latest version of Java 8 available. I would recommend using Java 17, the most recent <a href="https://en.wikipedia.org/wiki/Java_version_history">LTS</a> release.</li><li>Validate the total length of the input. The framework that you are using may have built-in support for limiting the input size. If not, you may still be able to work out the input size before parsing. If you are dealing with streaming input, you might be able to wrap the stream class. I have some sample code at <a href="https://github.com/pjfanning/json-size-limiter/tree/main/src/main/java/com/github/pjfanning/json/util">json-size-limiter</a>.</li><li>APIs that are not protected by Authentication and Authorization should apply lower limits to the input size.</li><li>Test your code with numbers with thousands of digits and with formats like 1e200000000.</li><li>Consider using String type to represent numbers in your externally facing API. This allows you to validate the size and format of the text before parsing the number yourself.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a433fa83c640" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/number-parsing-can-be-susceptible-to-dos-attacks-a433fa83c640">Number Parsing can be susceptible to DoS attacks</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plan for Cyber Attacks]]></title>
            <link>https://medium.com/@pjfanning/plan-for-cyber-attacks-8aa5d2f120a4?source=rss-c43097c6c565------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aa5d2f120a4</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[russian-hacking]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[ukraine-crisis]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[PJ Fanning]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 21:05:40 GMT</pubDate>
            <atom:updated>2022-03-24T19:38:45.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_GWnRTvKoVl5V_VNAdhmA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@flyd2069?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">FLY:D</a> on <a href="https://unsplash.com/s/photos/cyber-security?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>2021 is regarded as the worst (full) year yet for cyber crime. The issues associated with the ongoing Russian invasion of Ukraine could lead to a big increase in attacks. Companies should be hardening their IT systems in anticipation of this. Even if the attacks don’t materialise, the investments in improving IT security will pay off in the longer term.</p><p>The <a href="https://en.wikipedia.org/wiki/Wikipedia:Too_long;_didn%27t_read">TL;DR</a> summary of this article is that things are relatively quiet now but it appears that <a href="https://www.theguardian.com/technology/2022/mar/09/catastrophic-cyber-war-ukraine-russia-hasnt-happened-yet-experts-say">Russia may be holding back</a> from launching extra cyber attacks so as not to attract retaliatory attacks. This could change very quickly.</p><p>This <a href="https://www.csis.org/programs/strategic-technologies-program/significant-cyber-incidents">CSIS article</a> has a good list of recent attacks.</p><h3>2021</h3><p>Examples of attacks in 2021 include:</p><ul><li><a href="https://en.wikipedia.org/wiki/Health_Service_Executive_ransomware_attack">Irish HSE ransomware attack</a></li><li><a href="https://en.wikipedia.org/wiki/Colonial_Pipeline_ransomware_attack">Colonial Pipeline ransomware attack</a></li><li><a href="https://apnews.com/article/microsoft-exchange-hack-biden-china-d533f5361cbc3374fdea58d3fb059f35">Microsoft Exchange Server email hack</a></li><li><a href="https://www.bbc.com/news/technology-58652249#:~:text=Consumers%20should%20throw%20away%20their,Huawei%20model%20had%20security%20flaws.">Chinese manufactured 5G phones</a></li></ul><p><a href="https://fortune.com/2022/02/17/ransomware-attacks-surge-2021-report/">Some estimates</a> suggest that overall ransomware activity more than doubled, with government and health sectors facing even greater increases in attacks.</p><p>A disproportionate number of these attacks have been traced to Russian gangs with as much as <a href="https://www.bbc.com/news/technology-60378009">71% of the ransomware revenues in 2021</a> going to Russian groups.</p><p>To add to this, the <a href="https://en.wikipedia.org/wiki/Log4Shell">Log4Shell</a> vulnerability highlighted how even basic open source tooling used by many companies can expose them to unexpected vectors of attack.</p><p>The issues were so pervasive that the <a href="https://www.whitehouse.gov/briefing-room/statements-releases/2021/08/25/fact-sheet-biden-administration-and-private-sector-leaders-announce-ambitious-initiatives-to-bolster-the-nations-cybersecurity/">White House is putting pressure</a> on US companies to improve their cybersecurity.</p><h3><strong>Russian Invasion of Ukraine</strong></h3><p>There have been <a href="https://www.theguardian.com/world/2022/feb/24/russia-unleashed-data-wiper-virus-on-ukraine-say-cyber-experts">some cyber attacks</a> on Ukraine and a <a href="https://www.cpomagazine.com/cyber-security/ukraine-satellite-internet-service-hit-by-cyber-attack-intelligence-agencies-investigating/">large one</a> on Viasat. The cyber attacks on Ukraine have been happening for years and one of the initiatives taken by Ukraine has been to create the <a href="https://www.theguardian.com/world/2022/mar/18/amateur-hackers-warned-against-joining-ukraines-it-army">IT Army of Ukraine</a>. This group operates using <a href="https://telegram.org/">Telegram</a> and other channels. Along with <a href="https://en.wikipedia.org/wiki/Anonymous_(hacker_group)">Anonymous hacker group</a> and other such groups, they have had some success in bringing down services of Russian and Belarusian web sites and extracting data in some cases.</p><p>The simplest set of attacks for novices has been on the <a href="https://en.wikipedia.org/wiki/Denial-of-service_attack">Denial of Service</a> side. In some cases, volunteers can simply load a web page that has Javascript that causes a high volume of requests to go to targeted web sites. It is now being recommended that users use VPNs to hide their activity and it is highlighted that these attacks are against the law in most countries.</p><p>One commonly used open source library (<a href="https://arstechnica.com/information-technology/2022/03/sabotage-code-added-to-popular-npm-package-wiped-files-in-russia-and-belarus/">node-ipc</a>) was deliberately hacked to target users who used it in Russia and Belarus.</p><h3>Great Firewall</h3><p>China already has the <a href="https://en.wikipedia.org/wiki/Great_Firewall">Great Firewall</a> and it appears that Russia and Belarus are in the process of implementing <a href="https://www.politico.com/newsletters/morning-tech/2022/03/15/can-russia-build-its-own-great-firewall-00017244">something similar</a>. These firewalls allow for censorship but can also be used to protect IT infrastructure from attacks from outside the firewalls. It may also be possible to use them to hide attacks on infrastructure outside the firewalls.</p><p>It’s quite possible that a large part of the Russian cybercrime activity is being redirected to fight the current attacks on Russian sites. Malicious hackers can often be the best people at protecting their own sites from the attack vectors that they already have experience with using themselves.</p><h3>Protect yourself</h3><ul><li>Protect the majority of your online infrastructure using <a href="https://en.wikipedia.org/wiki/Virtual_private_network">VPNs</a> and <a href="https://en.wikipedia.org/wiki/Virtual_private_cloud">VPCs</a>.</li><li>Install anti-virus and threat detection software on all machines (including <a href="https://en.wikipedia.org/wiki/Virtual_machine">Virual Machines</a>)</li><li>Install all security patches as they become available.</li><li>The static resources you need run your web sites should be hosted by Content Delivery Networks (<a href="https://en.wikipedia.org/wiki/Content_delivery_network">CDNs</a>) that have Denial of Service protection (<a href="https://www.cloudflare.com/">Cloudflare</a>, <a href="https://www.akamai.com/">Akamai</a>, <a href="https://aws.amazon.com/cloudfront/">Amazon Cloudfront</a>, <a href="https://cloud.google.com/cdn">Google Cloud CDN</a>, etc).</li><li>The Backend web services that your web sites need to deal with can often be the weak point in your infrastructure. One solution is to have an <a href="https://microservices.io/patterns/apigateway.html">API Gateway</a> pattern and to be able to monitor and restrict traffic. Read <a href="https://geekflare.com/api-gateway/">this summary</a> for a good list of options.</li><li>Frequent backups of your data and code. It might seem obvious but the backups should be kept separate so that a malicious actor does not have easy access to the live copy and the backup.</li><li>Encrypt sensitive data.</li><li>Don’t email around sensitive data files. Keep the data in secure applications and only allow users access to the data they need to access. You would be shocked by the amount of sensitive data can be found on people’s phones and laptops (<a href="https://www.healthcareitnews.com/news/data-43000-patients-breached-after-theft-unencrypted-laptop">one example</a>)— data that usually shouldn’t be on those easily stolen devices in the first place. The world will be a better place when Microsoft Excel is no longer installed on people’s laptops (read <a href="https://www.sigmacomputing.com/blog/the-biggest-data-security-risk-downloading-data-to-a-spreadsheet/">this</a> if you don’t agree).</li><li>Ask any partners who you depend on for 24/7 availability what their Denial of Service protection is</li><li>Plan for how to conduct your operations without the internet or IT infrastructure generally. It’s great while the infrastructure is in place and running 24/7 but there is no guarantee that it will always be available to you. In 2021, the Irish health service had to struggle through with partial IT support in the middle of the Covid crisis due to a malicious attack, likely originating in Russia.</li></ul><p>Many large companies have specialist teams to design and do full time policing of web traffic. Unfortunately, many smaller companies or organisations who use IT but who don’t specialise in it may not dedicate enough resources to protect their applications until it’s too late. It is not uncommon for companies to rely on the fact that they are below the radar for cyber attacks.</p><p>Keep an eye on the price of cryptocurrencies because much of the mining hardware can be redirected to run malware bots when <a href="https://www.investopedia.com/tech/how-does-bitcoin-mining-work/">cryptocurrency mining</a> is <a href="https://www.darkreading.com/attacks-breaches/ddos-attacks-jumped-by-52-in-q4-2021">not profitable</a>.</p><h3>Summary</h3><p>Please comment on the article if you have corrections or questions related to this article. I hope I’ve covered most of the most important points and the reasons why it is more important than ever to start thinking about them.</p><p>I would just like to finish by highlighting my revulsion of the unprovoked attack on Ukraine and the suffering of so many millions brought about by it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aa5d2f120a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overview of jackson-module-scala and New Scala 3 Reflection Helper]]></title>
            <link>https://selectfrom.dev/jackson-module-scala-overview-and-new-scala-3-reflection-helper-b824be8221f7?source=rss-c43097c6c565------2</link>
            <guid isPermaLink="false">https://medium.com/p/b824be8221f7</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[jackson]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[PJ Fanning]]></dc:creator>
            <pubDate>Tue, 15 Mar 2022 18:52:04 GMT</pubDate>
            <atom:updated>2022-06-23T07:37:48.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7hxhbfOSVLske2JONQYrAA.jpeg" /><figcaption><a href="https://unsplash.com/photos/HfFoo4d061A">Photo</a> by <a href="https://unsplash.com/@flowforfrank?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ferenc Almasi</a> on Unsplash</figcaption></figure><p>One widely used way of converting Scala class instances to JSON or vice versa is <a href="https://github.com/FasterXML/jackson-module-scala">jackson-module-scala</a>.</p><p>There are lots of other Scala libraries that support <a href="https://en.wikipedia.org/wiki/JSON">JSON</a> and there are many good reasons to choose libraries like <a href="https://circe.github.io/circe/">Circe</a>, j<a href="https://github.com/plokhotnyuk/jsoniter-scala">soniter</a>, <a href="https://github.com/zio/zio-json">zio-json</a> and <a href="https://www.playframework.com/documentation/2.8.x/ScalaJson">play-json</a>. A <a href="http://Scala class instances to JSON or vice versa">comparison</a> of the various libraries and their strengths and weaknesses is worth an article in its own right. My aim in this article is to provide a quick overview and to link to other information sources where readers can get more information.</p><p>Despite being the main maintainer of jackson-module-scala in the last couple of years, I typically use one of the other libraries. However, there are some scenarios in which jackson-module-scala is the best choice, particularly for Java developers moving to Scala who are very comfortable with it.</p><p>Another potential advantage of Jackson is that it has data format libraries, so you can use the same code to support JSON and formats like <a href="https://github.com/FasterXML/jackson-dataformats-binary">binary JSON</a> (CBOR and Smile), <a href="https://github.com/FasterXML/jackson-dataformat-xml">XML</a>, <a href="https://github.com/FasterXML/jackson-dataformats-text/tree/2.14/yaml">YAML</a>, <a href="https://github.com/FasterXML/jackson-dataformats-text/tree/2.14/csv">CSV</a>, and many more.</p><p>jackson-module-scala is an important library in these ecosystems:</p><ul><li><a href="https://akka.io/">Akka</a> (default object serialization in akka-remote)</li><li><a href="https://kafka.apache.org/">Kafka</a></li><li><a href="https://spark.apache.org/">Spark</a></li><li><a href="https://github.com/twitter/finagle">Finagle</a>/<a href="https://github.com/twitter/finatra">Finatra</a></li><li>Swagger</li><li><a href="http://scalameter.github.io/">Scalameter</a></li></ul><h3>Introduction</h3><p>Jackson is one of the most widely used Java libraries for working with JSON.</p><pre>ObjectMapper mapper = JsonMapper.builder().build();<br>MyClass instance1 = mapper.readValue(jsonText, myClass.class);<br>String newText = mapper.writeValueAsString(instance1);</pre><p>jackson-module-scala adds support for Scala classes.</p><pre>val mapper = JsonMapper.builder()<br>  .addModule(DefaultScalaModule)<br>  .build()<br>val instance1 = mapper.readValue(jsonText, classOf[MyClass])<br>val newText = mapper.writeValueAsString(instance1)</pre><p>There are some other modules that support Scala classes not supported directly by <a href="https://github.com/FasterXML/jackson-module-scala/blob/2.14/src/main/scala/com/fasterxml/jackson/module/scala/DefaultScalaModule.scala">DefaultScalaModule</a>. These include:</p><ul><li><a href="https://github.com/pjfanning/jackson-module-enumeratum">jackson-module-enumeratum</a></li><li><a href="https://github.com/pjfanning/jackson-module-scala3-enum">jackson-module-scala3-enum</a></li><li><a href="https://github.com/pjfanning/jackson-module-scala-duration">jackson-module-scala-duration</a></li></ul><p>If you use a lot of classes, you may face issues with the built-in type cache in Jackson. <a href="https://github.com/pjfanning/jackson-caffeine-cache">jackson-caffeine-cache</a> documents how to use a larger cache or to replace the default cache with a <a href="https://github.com/ben-manes/caffeine">Caffeine</a>-based cache.</p><h3>Java Reflection</h3><p>Jackson uses Java reflection to derive how to best handle JSON support for your classes. This support can be tweaked using Java annotations (<a href="https://www.baeldung.com/jackson-annotations">examples</a>). Using annotations to override the default behaviors can often be done with less code than the alternate approaches in other libraries.</p><p>In some instances, you can preserve some type information that would otherwise not be available by using Jackson’s <a href="https://fasterxml.github.io/jackson-core/javadoc/2.2.0/com/fasterxml/jackson/core/type/TypeReference.html">TypeReference</a> class.</p><pre>import com.fasterxml.jackson.core.`type`.TypeReference<br>val instance = mapper.readValue(<br>    jsonText, new TypeReference[MyClass]{})</pre><h3>Scala Reflection</h3><p>You can mix in <a href="https://github.com/FasterXML/jackson-module-scala/blob/2.14/README.md#classtagextensions">ClassTagExtensions</a> to avoid the classOf syntax in readValue.</p><p>ClassTagExtensions replaces ScalaObjectMapper, which is now deprecated because the latter relies on scala-reflection Manifest and Scala 3 does not support Manifests.</p><pre>val mapper = JsonMapper.builder()<br>    .addModule(DefaultScalaModule).build() :: ClassTagExtensions<br>val myMap = mapper.readValue[Map[String, Tuple2[Int,Int]]](src)</pre><h3>jackson-scala3-reflection-extensions</h3><p><a href="https://github.com/pjfanning/jackson-scala3-reflection-extensions">jackson-scala3-reflection-extensions</a> is a new library for Scala 3 that uses Greg Zoller’s excellent <a href="https://github.com/gzoller/scala-reflection">scala-reflection</a> library. This library uses a few approaches to get the type information, chief among them being <a href="https://dotty.epfl.ch/docs/reference/metaprogramming/tasty-inspect.html">Tasty Inspection</a>. The tasty files that Scala 3 compiler adds to jars give access to class information that is normally lost due to type erasure.</p><p>ScalaReflectionExtensions can be mixed in a similar way to ClassTagExtensions<em>.</em></p><p>One of the main reasons to develop this library is the problem that has long existed with jackson-module-scala: handling of Options or Collections that wrap Scala primitives, eg Option[Long]. There are a number of <a href="https://github.com/FasterXML/jackson-module-scala/wiki/FAQ#deserializing-optionint-seqint-and-other-primitive-challenges">other ways</a> to work around the issue.</p><h3>Performance</h3><p>Jackson and the Scala module do pretty well in performance comparisons despite the fact that the code is based on Reflection. This is largely due to the fact the inferred type information is cached so it isn’t recalculated on every call.</p><ul><li><a href="https://github.com/yanns/scala-json-parsers-performance">Performance Comparison</a></li></ul><h3>Ongoing Development</h3><p>jackson-module-scala is a pretty stable library. In recent years, work has focused on Scala 3 support and supporting the future Jackson 3 release.</p><p><a href="https://github.com/FasterXML/jackson/wiki/Jackson-Release-3.0">Jackson 3</a> is not yet scheduled for release but the only major change on the Scala side is that the module support switches from Object to Class level so that different ObjectMappers can have modules that are configured independently.</p><p>And that’s a wrap! I hope this quick overview proves useful. Please get in touch by commenting on this article if you would like more information.</p><h4>The world’s fastest cloud data warehouse:</h4><p>When designing analytics experiences which are consumed by customers in production, even the smallest delays in query response times become critical. Learn how to achieve <strong>sub-second</strong> performance over TBs of data with <a href="https://www.firebolt.io/?v=m"><strong>Firebolt</strong>.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b824be8221f7" width="1" height="1" alt=""><hr><p><a href="https://selectfrom.dev/jackson-module-scala-overview-and-new-scala-3-reflection-helper-b824be8221f7">Overview of jackson-module-scala and New Scala 3 Reflection Helper</a> was originally published in <a href="https://selectfrom.dev/">SelectFrom</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CWE-248: Uncaught Exception in Java]]></title>
            <link>https://systemweakness.com/cwe-248-uncaught-exception-in-java-b6f4ee8daf14?source=rss-c43097c6c565------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6f4ee8daf14</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[security-vulnerabilities]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[apache-poi]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[PJ Fanning]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 21:23:23 GMT</pubDate>
            <atom:updated>2022-02-09T20:36:29.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pa1kI5WGoTSfZL-GB--XcA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mr_vero?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Irvan Smith</a> on <a href="https://unsplash.com/s/photos/exception-programming?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://cwe.mitre.org/data/definitions/248.html">CWE-248</a> is a common weakness that affects many software applications. I see many issues being raised against open source projects about perceived weaknesses in those projects’ exception handling. I have no problem with this but in the end of the day, it is the responsibility of the team delivering the end product to ensure that they test for such issues and to explicitly handle all the exception flows. They must be aware of the possibility that not all the possible exceptions will be declared as <a href="https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/">checked exceptions</a> in the library APIs.</p><p>The reason that I choose to write this article is because of some internal discussion in the <a href="https://poi.apache.org/">Apache POI</a> team. This project is around 20 years old and makes more use of unchecked exceptions than would be ideal. Some analysis was done about the impact of marking more of the exceptions as checked exceptions and the impact was massive (too many API changes that would annoy many existing users and too much work for a small team of unpaid volunteers). So for the time being, you should assume that all Apache POI code can throw unchecked exceptions and that users will need to ensure that such exceptions will not cause their applications to crash or that they have a way of recovering from such crashes.</p><h3>Java Exceptions</h3><p>All exception classes in Java inherit from java.lang.Throwable but they can be grouped into 3 categories depending on which of these classes they inherit from:</p><ul><li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Error.html">java.lang.Error</a> — serious issues and you don’t need to explicitly declare that methods can throw these (OutOfMemoryError is an example)</li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/RuntimeException.html">java.lang.RuntimeException</a> — these are unchecked exceptions and methods don’t need to explicitly declare that the exceptions can be thrown (<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html">IllegalStateException</a> is an example)</li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html">java.lang.Exception</a> — any class that inherits from this (but not via RuntimeException) needs to be explicitly handled by either allowing the method to throw the exception or by having a try-catch inside the method that handles the exception</li></ul><p>From a <a href="https://cwe.mitre.org/data/definitions/248.html">CWE-248</a> perspective, it is the first 2 types that are the biggest concern.</p><pre>public void runMethod(...) throws IOException</pre><p>It is important that users of Java libraries do not rely on just handling the checked exceptions. In the runMethod example above, IOException is not the only possible exception. This call could also result in an OutOfMemoryError or an IllegalStateException (a RuntimeException).</p><p>One possible approach is to set an Uncaught Exception <a href="https://medium.com/@yosimizrachi/advanced-exception-handling-thread-uncaughtexceptionhandler-c72e013da092">handler</a>.</p><p>Alternatively, adding a check to your try-catch for RuntimeException can often be a sensible way to allow for the fact that these can also occur even if the API does not declare that they can. Catching all throwables may not be a good idea and that is why I will look at a construct in Scala that can help.</p><h3>Scala Exceptions</h3><p>I want to make a brief diversion into <a href="https://en.wikipedia.org/wiki/Scala_(programming_language)">Scala</a>. Many Scala developers try to avoid exceptions altogether and try to encapsulate the possible results in the return type but this is much too large a diversion to go into here.</p><p>The exceptions in Scala are basically the same as in Java but with one major change: you don’t need to explicitly handle any exceptions. Nor do you have to declare that a function can throw a particular exception type (Scala has a throws annotation that you can optionally add to a function). Part of the reasoning is that the artificial differentiation in Java between checked and unchecked exceptions gives users a false sense of security. In the end, all exceptions should be handled at some stage.</p><p>One useful control pattern in Scala is <a href="https://www.scala-lang.org/api/2.13.8/scala/util/control/NonFatal$.html">NonFatal</a>.</p><pre><strong>try</strong> {<br>  // dangerous stuff<br>} <strong>catch</strong> {<br>  <strong>case</strong> NonFatal(e) <strong>=&gt;</strong> log.error(e, &quot;Something not that bad.&quot;)<br>}</pre><p>The NonFatal(e) catch will handle all throwables except a small number that shouldn’t be caught.</p><ul><li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/VirtualMachineError.html">VirtualMachineError</a> (for example, OutOfMemoryError and StackOverflowError, subclasses of VirtualMachineError),</li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadDeath.html">ThreadDeath</a></li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/LinkageError.html">LinkageError</a></li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/InterruptedException.html">InterruptedException</a></li><li><a href="https://www.scala-lang.org/api/2.13.8/scala/util/control/ControlThrowable.html">ControlThrowable</a> (a Scala exception that doesn’t affect Java users)</li></ul><p>I have written some <a href="https://github.com/pjfanning/java-non-fatal">sample code</a> that implements something similar in pure Java.</p><pre>public class ExceptionUtil {<br>    private ExceptionUtil() {}</pre><pre>    public static boolean isNonFatal(Throwable t) {<br>        return !(isFatal(t));<br>    }</pre><pre>    public static boolean isFatal(Throwable t) {<br>        //similar to <a href="https://www.scala-lang.org/api/2.13.8/scala/util/control/NonFatal$.html">https://www.scala-lang.org/api/2.13.8/scala/util/control/NonFatal$.html</a><br>        return (t instanceof VirtualMachineError<br>                || t instanceof ThreadDeath<br>                || t instanceof InterruptedException<br>                || t instanceof  LinkageError);<br>    }<br>}</pre><p>This utility code can be used in Java like this:</p><pre><strong>try</strong> {<br>  // dangerous stuff<br>} <strong>catch(Throwable t)</strong> {<br>  <strong>if (ExceptionUtil.</strong>isNonFatal(t)) {<br>    //log non-fatal exception<br>  } else {<br>    throw t;<br>  }<br>}</pre><h3>Summary</h3><p>Ensuring that uncaught exceptions do not cause applications to crash is ultimately the responsibility of the team delivering the product and they should not make too many assumptions about how libraries that they use behave. Feel free to engage with the library owners if you think the libraries could behave better. They may require that you assist them if the required changes are large.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6f4ee8daf14" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/cwe-248-uncaught-exception-in-java-b6f4ee8daf14">CWE-248: Uncaught Exception in Java</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caveats with accepting Microsoft Office File Formats in Uploads]]></title>
            <link>https://systemweakness.com/caveats-with-accepting-microsoft-office-file-formats-in-uploads-26be3673c330?source=rss-c43097c6c565------2</link>
            <guid isPermaLink="false">https://medium.com/p/26be3673c330</guid>
            <category><![CDATA[apache-poi]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[security-vulnerabilities]]></category>
            <category><![CDATA[microsoft-excel]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[PJ Fanning]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 12:41:25 GMT</pubDate>
            <atom:updated>2022-01-18T21:17:14.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVPRxqz2VUuY7NGXSXzmtw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kmuza?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Carlos Muza</a> on <a href="https://unsplash.com/s/photos/spreadsheet?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I’d like to share some of my experiences and thoughts about having web services or UI applications that allow users to upload files in Microsoft Office formats (like Excel, Word and Powerpoint).</p><p>I am a <a href="https://www.apache.org/dev/pmc.html">PMC</a> member of the <a href="https://poi.apache.org/">Apache POI</a> project and have worked on web services that accept Excel files. We regularly had production issues with Excel files that were submitted by trusted partners and had to come up with a new service architecture to handle this. It worries me to think that organisations might be unexpectedly opening up a vector of attack that malicious users could exploit when they choose to accept files in Excel or similar formats.</p><p>The following article is based on my own opinions and does not reflect the position of the Apache POI team or of any of my previous employers.</p><p>I’d like to also point out that this is not a criticism of Microsoft. I just think that some people are underestimating what it takes to properly support these formats in their applications.</p><h3>Potential Issues</h3><ul><li>Files that consume a lot of memory and/or CPU time when they are parsed</li><li>Excel can generate files in many different formats and different versions of Excel can have subtle differences in how they save files in each of these formats. Many other spreadsheet applications can also save in Excel formats (Google Sheets, Mac Numbers, Libre Office, Open Office, etc.).</li><li>This diverse ecosystem also affects other Microsoft products and their related file formats.</li><li>There are a lot of features that exist in these products and depending on whether or not a user chooses to use these features can have a big impact on what is saved and how the data is encoded in the file.</li><li>There might be malicious macros and you might want to configure your application to not run the macros by default. Microsoft Excel has this configuration (<a href="https://support.microsoft.com/en-us/office/change-macro-security-settings-in-excel-a97c09d2-c082-46b8-b19f-e8621e8fe373">link</a>).</li><li>The binary file formats make it difficult for your Network Security tools to weed out malicious files.</li></ul><h3>Microsoft Office File Formats</h3><ul><li><a href="https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-oleds/fdc5e702-d09e-4344-a77f-eb079d41f23f">OLE</a> format and the related <a href="https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/cd03cb5f-ca02-4934-a391-bb674cb8aa06">BIFF</a> format was the main format used up until 2007</li><li><a href="https://en.wikipedia.org/wiki/Office_Open_XML">OOXML</a> has been the main format since 2007</li></ul><p>The OLE and BIFF formats are custom to Microsoft but are well documented online. It is possible to create fuzzing tools that generate files that would cause memory issues or cause general processing exceptions.</p><p>I will focus on the OOXML formats. They are built on top of Microsoft specific XML schemas but the format is basically a <a href="https://en.wikipedia.org/wiki/ZIP_(file_format)">zip</a> file with <a href="https://en.wikipedia.org/wiki/XML">XML</a> files. The file can also contain embedded files like images, video clips and other Microsoft format files.</p><p>A number of these standards have well known attack vectors. To highlight a few:</p><ul><li>XML: <a href="https://en.wikipedia.org/wiki/Billion_laughs_attack">XML Entity Expansion</a> and other entity expansion <a href="https://en.wikipedia.org/wiki/XML_external_entity_attack">attacks</a></li><li>Zip: <a href="https://en.wikipedia.org/wiki/Zip_bomb">Zip Bomb</a></li><li><a href="https://www.fortinet.com/blog/threat-research/scalable-vector-graphics-attack-surface-anatomy">SVG image attacks</a></li></ul><h3>Alternative Formats</h3><p>Microsoft, Google and many others provide hosted services where you can collaborate on reading and editing spreadsheets, word processing documents, etc. These services allow you to control who has access to the files. Many of these services (including <a href="https://developers.google.com/sheets/api">Google</a>) have APIs that let you access the files from your own software applications.</p><p>If your users like to use Excel to build up data to send to you, you could consider getting them to save the file in <a href="https://en.wikipedia.org/wiki/Comma-separated_values">CSV</a> format before posting it to your online service (or similar delimited formats). Note that you will need to agree with the users what <a href="https://en.wikipedia.org/wiki/Character_encoding">character encodings</a> you support. I would suggest supporting only <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a>.</p><h3>Recommendations</h3><ul><li>Do not allow unauthenticated users to post Microsoft format files to your services</li><li>Even with authenticated users, ideally they (or their company) should have gone through a <a href="https://en.wikipedia.org/wiki/Know_your_customer">KYC</a> process before they have rights to post such files.</li><li>The code that parses the files should run in a <a href="https://en.wikipedia.org/wiki/Sandbox_(computer_security)">sandboxed</a> environment.</li><li>You should assume that parsing such files can cause application crashes, like Out of Memory exceptions — so having redundant instances of the parsing service is ideal. For example, if you use <a href="https://kubernetes.io/">Kubernetes</a> to deploy your service, you should have more than 1 instance of the parsing <a href="https://kubernetes.io/docs/concepts/workloads/pods/">pod</a> running behind the parsing service (a Kubernetes <a href="https://kubernetes.io/docs/concepts/services-networking/service/">service</a> acts like a load balancer).</li><li>You need a strategy for files that fail to parse. It may not be a good idea to retry the parse if it fails the first time.</li></ul><p>If you are an Apache POI user, I strongly recommend using the latest release available. Over time, we are adding limits to the amount of resources that a file can request when it is being a parsed. These are configurable because there are edge cases where legitimate files will fail to parse when you use the default POI configuration and you might need to tweak the POI setup (some options documented <a href="https://poi.apache.org/components/configuration.html">here</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26be3673c330" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/caveats-with-accepting-microsoft-office-file-formats-in-uploads-26be3673c330">Caveats with accepting Microsoft Office File Formats in Uploads</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Java Security Manager to Protect Your Apps]]></title>
            <link>https://systemweakness.com/use-java-security-manager-to-protect-your-apps-3914768201be?source=rss-c43097c6c565------2</link>
            <guid isPermaLink="false">https://medium.com/p/3914768201be</guid>
            <category><![CDATA[java-security]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[zero-day-vulnerability]]></category>
            <category><![CDATA[security-manager]]></category>
            <dc:creator><![CDATA[PJ Fanning]]></dc:creator>
            <pubDate>Sun, 12 Dec 2021 12:59:58 GMT</pubDate>
            <atom:updated>2022-01-13T10:27:53.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xImNR5VWRBR6jVYsBC-QfA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Michael Dziedzic</a> on <a href="https://unsplash.com/s/photos/malware?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>By default, Java has a lot of powerful features enabled. You may not want them all enabled if you want to protect your applications and users from malicious users.</p><p>The <a href="https://www.lunasec.io/docs/blog/log4j-zero-day/">Log4Shell</a> vulnerability has been keeping IT professionals up at nights in recent weeks. If you suspect that any of your applications uses log4j logging, then you should be looking to upgrade to log4j v2 jars to log4j v2.17.1 or to apply the temporary mitigations documented in the <a href="https://logging.apache.org/log4j/2.x/security.html">security announcement</a>. This Crowdstrike <a href="https://www.crowdstrike.com/blog/log4j2-vulnerability-analysis-and-mitigation-recommendations/">blog</a> adds to this by describing some JNDI controls.</p><p>It has also increased awareness of the general need for secure applications. Ideally, organisations should be monitoring the web traffic entering and leaving their managed services. In the Log4Shell scenario, you have to wonder why so many big companies did not block their services from making external TCP/IP calls to untrusted servers.</p><p>They should also be looking at how they deploy those applications. I would like to highlight some features of the JVM that anyone who uses Java or other JVM languages like Scala and Kotlin should be aware of.</p><h3>Java Runtime</h3><p>2 features of the default Java Runtime that I would like to highlight are:</p><ul><li><a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Runtime.html">Runtime</a> class</li><li><a href="http://www.jtech.ua.es/j2ee/restringido/documents/jdk-6u21/technotes/guides/scripting/programmer_guide/index.html">Script Engine</a> Support</li></ul><p>The Runtime class has many very powerful methods that you probably want to disable if you don’t need them.</p><ul><li>exec: runs a command or commands on your OS; these commands could be virtually anything and this gives you great power and great responsibility</li><li>exit: shuts down your JVM runtime</li><li>halt: also shuts down your JVM runtime</li><li>load/loadLibrary: load a native library into your JVM runtime</li></ul><p>The Script Engine allows you to run scripts, including Javascript and Python. With a Javascript script, you can run commands that use the Runtime features listed above — including executing OS commands or shutting down the JVM.</p><p>This is a basic sample of what can be done. You can replace the COMMAND static variable with something that works from your command line. This one works on my Macbook and causes the web page to load in my browser.</p><pre>public static String <em>COMMAND </em>= &quot;open https://www.google.com&quot;;<br>public static String <em>SCRIPT </em>= &quot;java.lang.Runtime.getRuntime().exec(&#39;&quot; + <em>COMMAND </em>+ &quot;&#39;)&quot;;<br><br>public static ScriptEngine createScriptEngine(String engineName) {<br>    final ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(engineName);<br>    if (scriptEngine == null) {<br>        throw new IllegalArgumentException(&quot;No script engine named &quot; + engineName);<br>    }<br>    return scriptEngine;<br>}</pre><pre>ScriptEngine scriptEngine = <em>createScriptEngine</em>(&quot;javascript&quot;);<br>System.<em>out</em>.println(Objects.<em>toString</em>(scriptEngine.eval(Utilities.<em>SCRIPT</em>), null));</pre><p>If you take user input and run it through the script engine, your application could be vulnerable. Most people will agree that you should at least validate the user input before processing it but it can be difficult to ensure that all your code and all the libraries that you use are entirely safe.</p><p>This code comes from the demo described below.</p><p>If you want to just support Javascript, you can create the script engine using this <a href="https://docs.oracle.com/javase/9/docs/api/jdk/nashorn/api/scripting/NashornScriptEngineFactory.html#getScriptEngine-java.lang.String:A-java.lang.ClassLoader-jdk.nashorn.api.scripting.ClassFilter-">method</a>, that allows you to specify a Class filter so you block access to more dangerous classes.</p><h3>Demo</h3><p>I have written a <a href="https://github.com/pjfanning/java-script-engine-sample">small demo</a> on Github to demonstrate using the Java <a href="https://www.baeldung.com/java-security-manager">Security Manager</a>. This feature is deprecated as of the <a href="https://openjdk.java.net/projects/jdk/17">Java 17 release</a> but it is still supported (see Java 17 section below).</p><p>The demo was written after I was made aware of the scripting support in a widely used open source library. I do not want to disclose the details of the library to avoid making a potential exploit public.</p><p>The demo does not set up a customised security <a href="https://docs.oracle.com/javase/6/docs/technotes/guides/security/PolicyFiles.html">policy file</a> but I would encourage users to experiment with them. It can be trial and error getting the right policies in place.</p><p>If you enable the Security Manager with the default settings, it will prevent the vulnerability demonstrated in the demo.</p><pre>System.<em>setSecurityManager</em>(new SecurityManager());</pre><p>The <a href="https://github.com/pjfanning/java-script-engine-sample/blob/main/build.gradle">build.gradle</a> runs ExecWithoutSecurityManager by default but can be modified to run ExecWithSecurityManager.</p><p>You can also load the project into your IDE and run the demos inside the IDE.</p><p>Remember to modify the COMMAND variable to something that works on your machine (<a href="https://github.com/pjfanning/java-script-engine-sample/blob/main/src/main/java/com/github/pjfanning/scriptengine/Utilities.java">Utilities.java</a>).</p><p>When I run ExecWithoutSecurityManager, I get this output:</p><pre>Warning: Nashorn engine is planned to be removed from a future JDK release</pre><pre>Process[pid=98283, exitValue=&quot;not exited&quot;]</pre><pre>script has been run</pre><p>When I run ExecWithSecurityManager, I get the output below. Runtime.exec requires the execute FilePermission on the target command file (when SystemManager is enabled).</p><pre>Warning: Nashorn engine is planned to be removed from a future JDK release</pre><pre>java.security.AccessControlException: access denied (&quot;java.io.FilePermission&quot; &quot;&lt;&lt;ALL FILES&gt;&gt;&quot; &quot;execute&quot;)</pre><pre>at java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)</pre><pre>at java.base/java.security.AccessController.checkPermission(AccessController.java:897)</pre><pre>at java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:322)</pre><pre>at java.base/java.lang.SecurityManager.checkExec(SecurityManager.java:572)</pre><pre>at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1096)</pre><pre>at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)</pre><pre>at java.base/java.lang.Runtime.exec(Runtime.java:592)</pre><pre>at java.base/java.lang.Runtime.exec(Runtime.java:416)</pre><pre>at java.base/java.lang.Runtime.exec(Runtime.java:313)</pre><pre>at jdk.scripting.nashorn.scripts/jdk.nashorn.internal.scripts.Script$Recompilation$1$\^eval\_/0x00000008001d5c40.:program(&lt;eval&gt;:1)</pre><pre>at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:655)</pre><pre>at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:513)</pre><pre>at jdk.scripting.nashorn/jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:527)</pre><pre>at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:456)</pre><pre>at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:413)</pre><pre>at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:409)</pre><pre>at jdk.scripting.nashorn/jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:162)</pre><pre>at java.scripting/javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)</pre><pre>at com.github.pjfanning.scriptengine.ExecWithSecurityManager.main(ExecWithSecurityManager.java:30)</pre><h3>Java 17</h3><p>The javascript engine has been removed since Java 15 (but GraalVM have a <a href="https://golb.hplar.ch/2020/04/java-javascript-engine.html">javascript engine</a> if you need one, available as standalone jars).</p><p>Java SecurityManager has been deprecated and no replacement is scheduled (<a href="https://openjdk.java.net/jeps/411">JEP-411</a>). There isn’t a great deal online about the alternative approaches but this article about <a href="https://inside.java/2021/04/23/security-and-sandboxing-post-securitymanager/">sandboxing</a> is worth a read. This <a href="https://tersesystems.com/blog/2016/01/19/redefining-java-dot-lang-dot-system/">blog</a> from Terse Systems describes how to use <a href="https://github.com/raphw/byte-buddy">byte-buddy</a> to change the behaviour of a dangerous method (System.setSecurityManager).</p><h3>Summary</h3><p>IT professionals should be looking at using every tool in their arsenal to make their applications as secure as possible. This article focuses on just one area but I hope people will find it helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3914768201be" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/use-java-security-manager-to-protect-your-apps-3914768201be">Use Java Security Manager to Protect Your Apps</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using GitHub Actions to Automatically Publish Gradle Build Artifacts]]></title>
            <link>https://selectfrom.dev/using-github-actions-to-automatically-publish-gradle-build-artifacts-d71c915cfa4?source=rss-c43097c6c565------2</link>
            <guid isPermaLink="false">https://medium.com/p/d71c915cfa4</guid>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[maven-central]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[PJ Fanning]]></dc:creator>
            <pubDate>Mon, 29 Nov 2021 20:00:30 GMT</pubDate>
            <atom:updated>2022-06-23T07:27:13.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsNzeg1fvHQ7DAg0QvhKZQ.jpeg" /><figcaption><a href="https://unsplash.com/photos/8Jccz5IN7ZM">Photo</a> by <a href="https://unsplash.com/@tim_arterbury?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tim Arterbury</a> on Unsplash</figcaption></figure><p>GitHub Actions is a CI/CD platform provided by GitHub that is free for running open source project builds.</p><p>This article is a follow up to an earlier <a href="https://selectfrom.dev/publishing-your-first-open-source-library-with-gradle-50bd0b1cd3af">one</a> about using Gradle to publish open source libaries. We will be using a clone of publish-java project — <a href="https://github.com/open-source-release-demo/publish-java-github-actions">open-source-release-demo/publish-java-github-actions</a>. It is very similar, with just a few changes.</p><h3>Gradle Changes</h3><p>The only difference in the <a href="https://github.com/open-source-release-demo/publish-java-github-actions/blob/main/build.gradle">build.gradle</a> (from <a href="https://github.com/open-source-release-demo/publish-java">publish-java</a>) is that the signing block has been changed to:</p><pre>signing {<br>    def signingKey = findProperty(&quot;signingKey&quot;)<br>    def signingPassword = findProperty(&quot;signingPassword&quot;)<br>    useInMemoryPgpKeys(signingKey, signingPassword)<br>    sign publishing.publications.mavenJava<br>}</pre><p>This signing plugin is documented in the Gradle <a href="https://docs.gradle.org/current/userguide/signing_plugin.html">docs</a>. The publish-java project pulls the signing key and password from gradle.properties on your laptop. This modified form takes the signing key and password from environment variables added by the GitHub Actions build (this is described in more detail below).</p><h3>GitHub Actions ci.yml</h3><p>The <a href="https://github.com/open-source-release-demo/publish-java-github-actions/blob/main/.github/workflows/ci.yml">ci.yml</a> file describes the build. All the GitHub Actions <a href="https://en.wikipedia.org/wiki/YAML">yml</a> files that control the build go into a ‘.github’ directory in your project repo. The build runs for every pull request commit and for all commits on the ‘main’ branch.</p><pre>on:<br>  pull_request:<br>    branches: [&#39;**&#39;]<br>  push:<br>    branches: [&#39;main&#39;]</pre><p>There are some steps to setup the build environment and run the build. The main ones are:</p><pre>jobs:<br>  build:<br>    name: Compile and Test code<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: Set up JDK 8<br>        uses: actions/setup-java@v3<br>          with:<br>            java-version: &#39;8&#39;<br>            distribution: &#39;temurin&#39;<br>            cache: &#39;gradle&#39;</pre><pre>      - name: Build with Gradle<br>        run: ./gradlew build --no-daemon</pre><p>These check out the code from Git and set up Temurin <a href="https://adoptium.net/">Adoptium</a> JDK 8. The example above skips a few caching steps that can be omitted. The `run: ./gradlew build` step is what actually compiles and tests the code.</p><p>There is a 2nd ‘publish’ job that runs after the ‘build’ job (only if that passes — see ‘needs’ section).</p><pre>publish:<br>    name: Publish Artifacts<br>    needs: [build]<br>    if: github.event_name != &#39;pull_request&#39; &amp;&amp; github.ref == &#39;refs/heads/main&#39;<br>    runs-on: ubuntu-latest<br>      steps:<br>        - uses: actions/checkout@v3<br>        - name: Set up JDK 8<br>          uses: actions/setup-java@v3<br>          with:<br>            java-version: &#39;8&#39;<br>            distribution: &#39;temurin&#39;<br>            cache: &#39;gradle&#39;</pre><pre>        - name: Publish with Gradle<br>          env:<br>            ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }}<br>            ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.SONATYPE_USERNAME }}<br>            ORG_GRADLE_PROJECT_signingKey: ${{ secrets.PGP_SECRET }}<br>            ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.PGP_PASSPHRASE }}<br>          run: ./gradlew publishToSonatype --no-daemon</pre><p>The publish job does not run for pull request builds. The ‘Publish with Gradle’ step sets 4 environment variables based on 4 secrets saved for the GitHub account. The ‘signing’ variables are needed by the Gradle script (highlighted in the previous section). I will cover how to set up the secrets in the next section.</p><p>This ci.yml file was copied from <a href="https://github.com/pjfanning/excel-streaming-reader">excel-streaming-reader</a> with no modifications — just to highlight how portable the scripts can be.</p><h3>GitHub Secrets</h3><p><a href="https://docs.github.com/en/actions/security-guides/encrypted-secrets">Secrets</a> for your build can be added at the repository or organization level. The build for public-java-github-actions needs these 4 secrets.</p><ul><li>SONATYPE_USERNAME</li><li>SONATYPE_PASSWORD</li><li>PGP_SECRET</li><li>PGP_PASSPHRASE</li></ul><p>For the Sonatype username and password, you can add the username and password you used on OSSRH JIRA or on the s01.oss.sonatype.org (or oss.sonatype.org) website. I recommend logging onto the Sonatype website and creating a user token.</p><p>Choose the drop down menu beside your username. And click on ‘profile’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*C5hvqEf4LVRBLGYhG9HD-Q.png" /></figure><p>Then, choose the ‘User Token’ option in the drop-down menu of the ‘Profile’ tab. Then, click on the ‘Access User Token’ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XdHpn5zDjWxabLfISzMQIw.png" /></figure><p>Use the username and password for the user token as your SONATYPE_USERNAME and SONATYPE_PASSWORD secrets.</p><p>The PGP_PASSPHRASE is the password of the GPG/PGP secret key you created for the ‘publish-java’ demo.</p><p>You need to use the following to get the value for the PGP_SECRET. The id is the LONG_ID of the GPG/PGP secret key. When setting up the secret, paste in the whole private key block including the BEGIN and END lines.</p><pre>LONG_ID=4F99EE30B6804AC7516E3EA3DB7CF378BD5A1A0B<br>gpg --armor --export-secret-keys $LONG_ID</pre><pre>-----BEGIN PGP PRIVATE KEY BLOCK-----</pre><pre>redacted</pre><pre>-----END PGP PRIVATE KEY BLOCK-----</pre><h3>Running the Builds</h3><p>Once you have the GitHub secrets set up and the ci.yml committed, any commit to the ‘main’ branch will cause a new build.</p><p>The <a href="https://github.com/open-source-release-demo/publish-java-github-actions/actions">Actions</a> tab in GitHub will let you see the build results. You will be emailed if the build fails.</p><p>When the version value in build.gradle ends with ‘-SNAPSHOT’, the artifacts are published to the Sonatype snapshots repository.</p><p>If you want to do a full release, remove the ‘-SNAPSHOT’ suffix from the build version and add a git tag to the commit. If the version is ‘0.2.0’, then tag with ‘v0.2.0’. It is the tagging that causes the publish action but you need the version in the build.gradle to match. You will need to use the Sonatype UI to complete the release (<a href="https://central.sonatype.org/publish/release/">Sonatype docs</a>).</p><p>In a later iteration, I might get the ci.yml job to also call the ‘closeAndReleaseSonatypeStagingRepository’ gradle task so that the Sonatype UI release step can be skipped.</p><h3>Additional GitHub Actions Jobs</h3><p><a href="https://github.com/open-source-release-demo/publish-java-github-actions/blob/main/.github/dependabot.yml">dependabot.yml</a> — GitHub can add this for you (<a href="https://github.blog/2020-06-01-keep-all-your-packages-up-to-date-with-dependabot/">GitHub docs</a>). It runs daily and raises pull requests when new dependency versions are available.</p><p><a href="https://github.com/open-source-release-demo/publish-java-github-actions/blob/main/.github/workflows/codeql-analysis.yml">codeql-analysis.yml</a> — Can be added using GitHub UI is a similar way to adding the dependabot one.</p><h3>Summary</h3><p>With a little bit of reading and experimentation, you should be able to put together some very powerful GitHub Actions builds. GitHub Actions has some great plugins, many of which are in the <a href="https://github.com/marketplace?category=&amp;query=&amp;type=actions&amp;verification=">marketplace</a>. One plugin that is worth investigating is <a href="https://github.com/codecov/codecov-action">codecov-action</a> to record code coverage metrics.</p><h4>The world’s fastest cloud data warehouse:</h4><p>When designing analytics experiences which are consumed by customers in production, even the smallest delays in query response times become critical. Learn how to achieve <strong>sub-second</strong> performance over TBs of data with <a href="https://www.firebolt.io/?v=m"><strong>Firebolt</strong>.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d71c915cfa4" width="1" height="1" alt=""><hr><p><a href="https://selectfrom.dev/using-github-actions-to-automatically-publish-gradle-build-artifacts-d71c915cfa4">Using GitHub Actions to Automatically Publish Gradle Build Artifacts</a> was originally published in <a href="https://selectfrom.dev/">SelectFrom</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sonatype Publishing Your First Open Source Library with Gradle]]></title>
            <link>https://selectfrom.dev/publishing-your-first-open-source-library-with-gradle-50bd0b1cd3af?source=rss-c43097c6c565------2</link>
            <guid isPermaLink="false">https://medium.com/p/50bd0b1cd3af</guid>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[open-source-software]]></category>
            <category><![CDATA[maven-central]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[PJ Fanning]]></dc:creator>
            <pubDate>Fri, 26 Nov 2021 21:38:30 GMT</pubDate>
            <atom:updated>2022-06-24T12:30:09.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*b-sMYnZwhr1fXtIt" /><figcaption><a href="https://unsplash.com/photos/Y7d265_7i08">Photo</a> by <a href="https://unsplash.com/@gabons">Gabriel Sollmann</a> on Unsplash</figcaption></figure><p>Creating your own open source project and publishing Maven artifacts for general consumption can be very straightforward. Here, I’m going to use a Java project as an example but much of what I intend to cover in this article can be applied to other <a href="https://en.wikipedia.org/wiki/Java_virtual_machine#:~:text=A%20Java%20virtual%20machine%20(JVM)%20is%20a%20virtual%20machine%20that,also%20compiled%20to%20Java%20bytecode.&amp;text=The%20JVM%20reference%20implementation%20is,a%20JIT%20compiler%20called%20HotSpot.">JVM</a>-based languages, like Scala and Kotlin.</p><p>The main items I would like to cover are:</p><ul><li>Creating your project in GitHub.</li><li>A quick run through of Maven artifacts.</li><li>Getting an OSS Sonatype account set up and registering your <a href="https://maven.apache.org/guides/mini/guide-naming-conventions.html">groupId</a>.</li><li>Creating a <a href="https://gnupg.org/">GPG</a> key and publishing its public part so you can sign artifacts.</li><li>Publishing a jar to Maven Central.</li></ul><h3>Hosting Your Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5GFjGTFzy_XaMXQzaaLkA.png" /></figure><p>I created a GitHub organization called <a href="https://github.com/open-source-release-demo">open-source-release-demo</a>. I intend to add some projects to provide relevant material for this and other articles. For this article, the main project is: <a href="https://github.com/open-source-release-demo/publish-java">publish-java</a>. Feel free to <a href="https://docs.github.com/en/get-started/quickstart/fork-a-repo">fork</a> this project and try to use your version of the project to publish to Maven Central.</p><p>GitHub is the most commonly used platform for hosting open source projects. It is now owned by Microsoft and they are putting a lot of investment into it. GitHub accounts are also useful for accessing other <a href="https://en.wikipedia.org/wiki/Software_as_a_service">SaaS</a> products related to open source development.</p><p>You can choose your own hosting platform, but a GitHub account would be helpful for following along with the exercises in this article. GitHub is free for open source development.</p><p>You can use your personal GitHub account or you can create a GitHub <a href="https://docs.github.com/en/organizations/collaborating-with-groups-in-organizations/creating-a-new-organization-from-scratch">organization</a>. Before we go further, if you are not too familiar with Maven publishing, it might help you to <a href="https://medium.com/@pjfanning/introduction-to-maven-publishing-719d85a95266">read more</a> about it before proceeding further.</p><h3>OSS Sonatype Registration</h3><p><a href="https://www.sonatype.com/">Sonatype</a> provides free support for open source development. You will need to create an account on the <a href="https://issues.sonatype.org/secure/Dashboard.jspa">Sonatype JIRA</a> issue tracking site.</p><p>The groupId you will use for your open source project will be based on an internet domain that you or your employers own. For example, with Java package names, the order of the elements in the domain name are reversed. If you own acme.com, then you can use com.acme as a groupId. You may need to <a href="https://central.sonatype.org/faq/how-to-set-txt-record/">prove</a> you control the domain.</p><p>It is common for users who don’t have their own domain names to create one based on their GitHub account. The current standard is:</p><p>io.github.&lt;orgOrUserName&gt; — e.g. io.github.open-source-release-demo</p><p>In the past, the norm was com.github, but OSS Sonatype no longer allows the prefix. I use com.github.pjfanning for some existing open source projects.</p><p><a href="https://issues.sonatype.org/browse/OSSRH-75400">OSSRH-75400</a> is the issue I raised to register the groupId for this article and its project.</p><p>The OSSRH JIRAs are usually resolved very quickly and you can use JIRAs to add and remove users, to allow them to publish for the groupId (or to revoke those rights).</p><h3>GPG Signing</h3><p>Signing an artifact is a way to prove who published the artifact. OSS Sonatype verifies that all artifacts are correctly signed.</p><p>A lot of this section is lifted straight from <a href="https://github.com/sbt/sbt-ci-release#gpg">sbt-ci-release</a>. I use this project a lot for my Scala projects.</p><p>If you don’t have GPG installed, you can download it from <a href="https://gnupg.org/download/">https://gnupg.org/download/</a>.</p><p>Generate a new key:</p><pre>gpg --gen-key</pre><pre># enter your name, your email address and then a passphrase<br># outputs something like</pre><pre>pub   ed25519 2021-11-26 [SC] [expires: 2023-11-26]<br>4F99EE30B6804AC7516E3EA3DB7CF378BD5A1A0B<br>uid                      PJ Fanning &lt;fanningpj@redacted.com&gt;<br>sub   cv25519 2021-11-26 [E] [expires: 2023-11-26]</pre><p>Export the public part of the key:</p><pre># put the key id in an environment variable<br>LONG_ID=4F99EE30B6804AC7516E3EA3DB7CF378BD5A1A0B</pre><pre># output the public part of the key<br>gpg --armor --export $LONG_ID</pre><pre>-----BEGIN PGP PUBLIC KEY BLOCK-----mDMEYaEgOhYJKwYBBAHaRw8BAQdAE8tJ1qEm7zjl6UDaImC5Fb6a/0AzxU2WbDV6<br>oWpVTpq0IFBKIEZhbm5pbmcgPGZhbm5pbmdwakB5YWhvby5jb20+iJoEExYKAEIW<br>IQRPme4wtoBKx1FuPqPbfPN4vVoaCwUCYaEgOgIbAwUJA8JnAAULCQgHAgMiAgEG<br>FQoJCAsCBBYCAwECHgcCF4AACgkQ23zzeL1aGguUJgEAuoGFGOCcfS+113pAOPpZ<br>6BGiCx+46cOHY6LDExDdzlgBAPIwhzMin39eRQlqOxvpnIL75zqFSCf5PifIUG7d<br>B1kGuDgEYaEgOhIKKwYBBAGXVQEFAQEHQD4WuStIOQGDaxvh3TkOJHIKL/4mXMX/<br>iGK1q8sVEupFAwEIB4h+BBgWCgAmFiEET5nuMLaASsdRbj6j23zzeL1aGgsFAmGh<br>IDoCGwwFCQPCZwAACgkQ23zzeL1aGgsNWwEAurt3UW3OY2LZSYCnhGSvcYQo3CT3<br>DYbt0K4w5YPHuPEBAJu4aOIWYdnimBwhXq9PL6JqHMRrP6gcMtRksYYiyPoI<br>=NboS<br>-----END PGP PUBLIC KEY BLOCK-----</pre><pre># on Mac, to copy straight to clipboard<br>gpg --armor --export $LONG_ID | pbcopy<br># on Linux, to copy straight to clipboard<br>gpg --armor --export $LONG_ID | xclip<br># Windows<br>gpg --armor --export %LONG_ID%</pre><p>Publish the public part of the key to a PGP key server. For example: <a href="http://keyserver.ubuntu.com:11371/">http://keyserver.ubuntu.com:11371/</a></p><p>Use the ‘Submit Key’ option and paste it in your public key.</p><h3>Setting Up gradle.properties</h3><p>This section assumes you have some experience with Gradle.</p><p>You need to set up your gradle.properties to add references to your Sonatype credentials and GPG key. On Mac/Linux, this file normally goes into the ~/.gradle directory. The Gradle build environment <a href="https://docs.gradle.org/current/userguide/build_environment.html">docs</a> have fuller details about this.</p><p>The gradle.properties should look like:</p><pre>signing.keyId=BD5A1A0B<br>signing.password=redacted<br>signing.secretKeyRingFile=/Users/pj.fanning/.gnupg/secring.gpg</pre><pre>sonatypeUsername=pjfanning<br>sonatypePassword=redacted</pre><p>The Gradle <a href="https://docs.gradle.org/current/userguide/signing_plugin.html">signing plugin</a> docs have more details. These are important as there are some potential gotchas.</p><p>The signing.keyId is the last 8 chars of the LONG_ID used above.</p><h3>Using Gradle to Publish to Maven Central</h3><p>I have a sample project on GitHub. Fork <a href="https://github.com/open-source-release-demo/publish-java">open-source-release-demo/publish-java</a> if you want to try this for yourself.</p><p>The project has one Java class, called <a href="https://github.com/open-source-release-demo/publish-java/blob/main/src/main/java/io/github/opensourcereleasedemo/ReleaseInfo.java">ReleaseInfo</a>, that reads in a version.txt generated by the Gradle build.</p><p>The project relies on these plugins:</p><pre>plugins {<br>    id &#39;java-library&#39;<br>    id &#39;signing&#39;<br>    id &#39;maven-publish&#39;<br>    id(&#39;io.github.gradle-nexus.publish-plugin&#39;) version &#39;1.1.0&#39;<br>}</pre><p>They are built-in plugins except for the gradle-nexus <a href="https://github.com/gradle-nexus/publish-plugin">publish-plugin</a>.</p><p>The artifact name appears in <a href="https://github.com/open-source-release-demo/publish-java/blob/main/settings.gradle">settings.gradle</a>. Most of the rest of the details that I would like to cover are in <a href="https://github.com/open-source-release-demo/publish-java/blob/main/build.gradle">build.gradle</a>.</p><pre>group = &#39;io.github.open-source-release-demo&#39;<br>version = &#39;0.1.0-SNAPSHOT&#39;</pre><p>The groupId is called group in build.gradle. If the version ends in ‘-SNAPSHOT’, publishing will put the file in the snapshot repository. If you’re publish with version=0.1.0, then the publishing will end up in staging area and you can use the OSS Sonatype app to release the artifacts.</p><pre>java {<br>    withJavadocJar()<br>    withSourcesJar()<br>}<br><br>nexusPublishing {<br>    repositories {<br>        sonatype {  <em>//only for users registered in Sonatype after 24 Feb 2021<br></em>            nexusUrl.set(uri(&quot;https://s01.oss.sonatype.org/service/local/&quot;))<br>            snapshotRepositoryUrl.set(uri(&quot;https://s01.oss.sonatype.org/content/repositories/snapshots/&quot;))<br>        }<br>    }<br>}<br><br>publishing {<br>    publications {<br>        mavenJava(MavenPublication) {<br>            from(components.java)<br>            pom {<br>                name = &#39;publish-java&#39;<br>                description = &#39;Demo of how to publish a Java Gradle based project to Maven Central&#39;<br>                url = &#39;https://github.com/open-source-release-demo/publish-java&#39;<br>                licenses {<br>                    license {<br>                        name = &#39;The Apache License, Version 2.0&#39;<br>                        url = &#39;http://www.apache.org/licenses/LICENSE-2.0.txt&#39;<br>                    }<br>                }<br>                developers {<br>                    developer {<br>                        id = &#39;pjfanning&#39;<br>                        name = &#39;PJ Fanning&#39;<br>                    }<br>                }<br>                scm {<br>                    url = &#39;https://github.com/open-source-release-demo/publish-java&#39;<br>                    connection = &#39;scm:git://github.com/open-source-release-demo/publish-java.git&#39;<br>                    developerConnection = &#39;scm:git://github.com/open-source-release-demo/publish-java.git&#39;<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Sonatype requires that you include the javadoc and sources jars (see the withJavadocJar() and withSourcesJar() in the excerpt above).</p><p>The ‘nexusPublishing’ section has the details of where to publish to. Users with older Sonatype accounts can use this instead.</p><pre>nexusPublishing {<br>    repositories {<br>        sonatype()<br>    }<br>}</pre><p>The publishing section specifies what to publish (components.java) and provides details that must appear in the pom file descriptor (license, developers, and <a href="https://en.wikipedia.org/wiki/Software_configuration_management">SCM</a> links).</p><pre>signing {<br>    sign publishing.publications.mavenJava<br>}</pre><p>The signing section is needed to ensure the artifacts are signed. Snapshot publishing does not need signing but full releases do. I tend to sign snapshots too.</p><p>The gradle build also generates a version.txt that gets included in the jar.</p><pre>ext.genOutputDir = file(&quot;$buildDir/generated-resources&quot;)<br><br>task generateVersionTxt()  {<br>    ext.outputFile = file(&quot;$genOutputDir/version.txt&quot;)<br>    outputs.file(outputFile)<br>    doLast {<br>        outputFile.text = &quot;&quot;&quot;GroupId: ${project.group}<br>Name: ${project.name}<br>Version: $version<br>Build-time: ${java.time.LocalDateTime.now()}<br>&quot;&quot;&quot;<br>    }<br>}<br><br>sourceSets.main.output.dir genOutputDir, <em>builtBy</em>: generateVersionTxt</pre><p>The output looks like:</p><pre>GroupId: io.github.open-source-release-demo<br>Name: publish-java<br>Version: 0.1.0-SNAPSHOT<br>Build-time: 2021-11-25T20:45:02.518</pre><p>If you have forked the sample and checked out your fork, then you can just modify the group in the build.gradle to match what you set up with your OSSRH JIRA. You should also change the ‘scm’ URLs to match your fork location.</p><p>If you have the gradle.properties set up (as described above), you can now publish a snapshot.</p><p>At the command prompt, go to the root dir of your copy of the git project. You might need to make the gradlew (or gradlew.bat) file executable (eg with <a href="https://en.wikipedia.org/wiki/Chmod">chmod</a>).</p><pre>./gradlew publishToSonatype</pre><p>This generates the artifacts and publishes them to the Sonatype snapshots repo. My setup sends the artifacts to <a href="https://s01.oss.sonatype.org/content/repositories/snapshots/io/github/open-source-release-demo/publish-java/">https://s01.oss.sonatype.org/content/repositories/snapshots/io/github/open-source-release-demo/publish-java/</a>.</p><p>I have a client project that consumes the published artifacts, called <a href="https://github.com/open-source-release-demo/publish-java-client">open-source-release-demo/publish-java-client</a>.</p><h3>Full Release</h3><p>I have a ‘release’ branch in the publish-java project.</p><p>This sets the version to 0.1.0. So when you run:</p><pre>./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository</pre><p>after running the publish command, you’ll see an output like:</p><pre><strong>&gt; Task :initializeSonatypeStagingRepository</strong></pre><pre>Created staging repository &#39;iogithubopen-source-release-demo-1000&#39; at https://s01.oss.sonatype.org/service/local/repositories/iogithubopen-source-release-demo-1000/content/</pre><p>The publishToSonatype task stages the artifacts for release and closeAndReleaseSonatypeStagingRepository task completes it. These gradle tasks are added by <a href="https://github.com/gradle-nexus/publish-plugin">gradle-nexus/publish-plugin</a>.</p><p>If you omit the 2nd command, you can complete the release using the <a href="https://oss.sonatype.org/">Sonatype UI</a>. You would need to login to <a href="https://s01.oss.sonatype.org/">https://s01.oss.sonatype.org/</a> — same username and password as you used in the OSSRH JIRA above.</p><p>You will get an email from <a href="https://www.sonatype.com/products/sonatype-lift">Sonatype Lift</a> which has details about security issues in your dependencies.</p><p>The published artifacts for my project go to <a href="https://repo1.maven.org/maven2/io/github/open-source-release-demo/publish-java/">https://repo1.maven.org/maven2/io/github/open-source-release-demo/publish-java/</a></p><h3>Next Steps</h3><p>I have a follow up <a href="https://medium.com/@pjfanning/using-github-actions-to-automatically-publish-gradle-build-artifacts-d71c915cfa4">article</a> and sample project where I use <a href="https://github.com/features/actions">GitHub Actions</a> to automate the whole process.</p><p>Feel free to comment on the article if you think I need to clarify anything.</p><h3>The world’s fastest cloud data warehouse:</h3><p>When designing analytics experiences which are consumed by customers in production, even the smallest delays in query response times become critical. Learn how to achieve <strong>sub-second</strong> performance over TBs of data with <a href="https://www.firebolt.io/?v=m"><strong>Firebolt</strong>.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50bd0b1cd3af" width="1" height="1" alt=""><hr><p><a href="https://selectfrom.dev/publishing-your-first-open-source-library-with-gradle-50bd0b1cd3af">Sonatype Publishing Your First Open Source Library with Gradle</a> was originally published in <a href="https://selectfrom.dev/">SelectFrom</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>