[Analyzer Proposal] Warn when passing an int value to DateTimeOffset.FromUnixTimeSeconds()

Open
#108,712 2 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
csharp
Domain
devtools

Research direction

The proposal targets calls to DateTimeOffset.FromUnixTimeSeconds(long), especially arguments from int variables such as Utf8JsonReader.GetInt32(). Compare those with literals, constants, and the GetInt64() example to define the diagnostic boundaries. Done means the analyzer warns for susceptible int-valued arguments while avoiding the stated safe cases.

Written by the indexing model from the issue text.

Description

area-System.DateTime code-analyzer

Inspired by comment in this issue: https://github.com/octokit/webhooks.net/pull/591#issuecomment-2402427465


If code using DateTimeOffset.FromUnixTimeSeconds(long) passes a variable of type int to it, that value will be implicitly converted to a long and in most cases today will work just fine. However, that leaves the code susceptible to Year-2038 issues when a date is too far in the future to be represented as a 32-bit integer.

For literals or constants, this is likely fine, as maybe it's a hard-coded reference to a fixed point in time, but for code referencing a variable/property/etc. of type int, this might be a looming bug (e.g. deserializing a value from JSON to a POCO) that hints at a type mismatch that will fail at some point in the future.

An example of this is as referenced in the issue above:

private static DateTimeOffset HandleNumber(Utf8JsonReader reader)
    => DateTimeOffset.FromUnixTimeSeconds(reader.GetInt32());

This bug could have been avoided with an analyzer that warned of the potential for overflow, which could have lead to the original author instead writing the following:

private static DateTimeOffset HandleNumber(Utf8JsonReader reader)
    => DateTimeOffset.FromUnixTimeSeconds(reader.GetInt64()); 
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/runtime

All issues in dotnet/runtime

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.