Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 107 additions & 4 deletions src/jsc/bindings/JSEnvironmentVariableMap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@
#include "SharedEnvStore.h"
#include "wtf/NeverDestroyed.h"
#include "WebCoreJSBuiltins.h"
#include <JavaScriptCore/IntlObject.h>
#include <wtf/text/MakeString.h>

#if OS(UNIX)
#include <limits.h>
#include <stdlib.h>
#endif

using namespace JSC;

Expand Down Expand Up @@ -482,15 +489,111 @@
"no_proxy"_s,
};

// POSIX "STD[+|-]hh" -> "Etc/GMT[+|-]h" (both count hours west of UTC, so the
// sign is preserved). Whole hours in the Etc/GMT range only, matching what
// Node/V8 honors via ICU's uprv_tzname gate.
Comment thread
robobun marked this conversation as resolved.
Resolved
static String posixStdOffsetToEtcGMT(StringView v)
{
size_t i = 0;
if (!v.isEmpty() && v[0] == '<') {
size_t end = v.find('>');
if (end == notFound)
return String();
i = end + 1;
} else {

Check warning on line 503 in src/jsc/bindings/JSEnvironmentVariableMap.cpp

View check run for this annotation

Claude / Claude Code Review

Angle-bracket '<std>offset' branch has no test coverage

nit: The angle-bracket branch (`v[0] == '<'`) in `posixStdOffsetToEtcGMT` has no test coverage — none of the TZ values in `process-env-tz.test.ts` start with `<`, so deleting lines 498-503 would break no test. Add e.g. `['<+03>-3', -180, 'Etc/GMT-3']` to the accept matrix to cover the POSIX quoted-std form.
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
while (i < v.length() && isASCIIAlpha(v[i]))
++i;
if (i < 3)
return String();
}
bool negative = false;
if (i < v.length() && (v[i] == '+' || v[i] == '-')) {
negative = v[i] == '-';
++i;
}
size_t hstart = i;
while (i < v.length() && isASCIIDigit(v[i]))
++i;
if (i == hstart || i - hstart > 2 || i != v.length())
return String();
int hours = 0;
for (size_t j = hstart; j < i; ++j)
hours = hours * 10 + (v[j] - '0');
if (hours == 0)
return "UTC"_s;
if (negative ? hours > 14 : hours > 12)
return String();
return makeString("Etc/GMT"_s, negative ? '-' : '+', hours);
}

// Normalize a process.env.TZ value to an IANA name JSC's intlResolveTimeZoneID
// accepts; anything that can't be named clears the override so a stale zone
// from a prior assignment doesn't persist. Handles ":Zone", absolute tzfile
// paths (realpath + "/zoneinfo/" suffix), and POSIX "STD[+|-]hh" -> Etc/GMT.
Comment thread
robobun marked this conversation as resolved.
Resolved
bool setTimeZoneFromEnvValue(JSC::JSGlobalObject* globalObject, const WTF::String& raw)
{
auto& vm = JSC::getVM(globalObject);
auto commit = [&](const String& name) -> bool {
if (!WTF::setTimeZoneOverride(name))
return false;
WTF::timeZoneDidChange();
vm.dateCache.clearForTimeZoneChange();
return true;
};

if (raw.isEmpty())
return commit(emptyString());

String tz = raw.startsWith(':') ? raw.substring(1) : raw;

#if OS(UNIX)
if (tz.startsWith('/')) {
auto extractZoneInfoSuffix = [](StringView path) -> String {
constexpr auto marker = "/zoneinfo/"_s;
size_t pos = path.reverseFind(marker);
if (pos == notFound)
return String();
StringView suffix = path.substring(pos + marker.length());
if (suffix.startsWith("posix/"_s) || suffix.startsWith("right/"_s))
suffix = suffix.substring(6);
if (suffix.isEmpty() || suffix == "posixrules"_s || suffix == "localtime"_s)
return String();
return suffix.toString();
};
String zone = extractZoneInfoSuffix(tz);
if (zone.isNull()) {
CString utf8 = tz.utf8();
char buf[PATH_MAX];
if (const char* resolved = realpath(utf8.data(), buf))
zone = extractZoneInfoSuffix(StringView::fromLatin1(resolved));
}
if (!zone.isNull())
tz = WTF::move(zone);
}
#endif

if (JSC::intlResolveTimeZoneID(tz))
return commit(tz);

if (!tz.isEmpty()) {
String primary = JSC::toPrimaryIanaTimeZoneIdentifier(StringView(tz));
if (!primary.isEmpty() && primary != tz && JSC::intlResolveTimeZoneID(primary))
return commit(primary);
}

if (String etc = posixStdOffsetToEtcGMT(tz); !etc.isNull() && JSC::intlResolveTimeZoneID(etc))
return commit(etc);

commit(emptyString());
return false;
}

// The parse-and-apply bodies for the three side-effecting env vars, shared by
// the regular process.env CustomSetters and applySharedEnvSideEffects so a new
// side-effecting var need only be added in one place.
static void applyTZFromString(JSGlobalObject* globalObject, const String& value)
{
if (value.length() < 32 && WTF::setTimeZoneOverride(value)) {
WTF::timeZoneDidChange();
JSC::getVM(globalObject).dateCache.clearForTimeZoneChange();
}
setTimeZoneFromEnvValue(globalObject, value);
}
static void applyTLSRejectFromString(JSGlobalObject*, const String& value)
{
Expand Down
3 changes: 3 additions & 0 deletions src/jsc/bindings/JSEnvironmentVariableMap.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ namespace Bun {

JSC::JSValue createEnvironmentVariablesMap(Zig::GlobalObject* globalObject);

// process.env.TZ -> JSC date cache; accepts POSIX forms beyond IANA names.
bool setTimeZoneFromEnvValue(JSC::JSGlobalObject*, const WTF::String&);

// worker_threads SHARE_ENV: a `process.env` whose reads/writes/enumeration go
// through the SharedEnvStore of the tree its global belongs to.
JSC::JSValue createSharedEnvironmentVariablesMap(Zig::GlobalObject* globalObject);
Expand Down
10 changes: 1 addition & 9 deletions src/jsc/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3351,15 +3351,7 @@ void GlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor)

extern "C" bool JSGlobalObject__setTimeZone(JSC::JSGlobalObject* globalObject, const ZigString* timeZone)
{
auto& vm = JSC::getVM(globalObject);

if (WTF::setTimeZoneOverride(Zig::toString(*timeZone))) {
WTF::timeZoneDidChange();
vm.dateCache.clearForTimeZoneChange();
return true;
}

return false;
return Bun::setTimeZoneFromEnvValue(globalObject, Zig::toString(*timeZone));
}

extern "C" void JSGlobalObject__requestTermination(JSC::JSGlobalObject* globalObject)
Expand Down
132 changes: 132 additions & 0 deletions test/js/node/process/process-env-tz.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// https://github.com/oven-sh/bun/issues/8060
//
// JSC resolves the default time zone by name through intlResolveTimeZoneID; a
// TZ value it cannot name collapses to UTC. Bun now normalizes POSIX TZ forms
// (leading ':', absolute tzfile paths, "std offset" specs) to an IANA name
// before handing them to JSC so Date offsets match Node.
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, isPosix, tempDir } from "harness";
import { existsSync, symlinkSync } from "node:fs";
import { join } from "node:path";

const script =
"process.stdout.write(String(new Date().getTimezoneOffset()) + ' ' + Intl.DateTimeFormat().resolvedOptions().timeZone)";

async function offset(tz: string) {
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: { ...bunEnv, TZ: tz },
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(exitCode).toBe(0);
const [off, intl] = stdout.split(" ");
return { offset: Number(off), intl };
}

describe.concurrent("process.env.TZ POSIX std+offset form", () => {
test.each([
// POSIX offset sign is hours *west* of UTC, so MSK-3 is UTC+3.
["MSK-3", -180, "Etc/GMT-3"],
["UTC+5", 300, "Etc/GMT+5"],
["ABC5", 300, "Etc/GMT+5"],
["ABC-5", -300, "Etc/GMT-5"],
["XXX-14", -840, "Etc/GMT-14"],
["XXX+12", 720, "Etc/GMT+12"],
["ABC0", 0, "UTC"],
] as const)("TZ=%s", async (tz, expectedOffset, expectedIntl) => {
const { offset: off, intl } = await offset(tz);
expect(off).toBe(expectedOffset);
expect(intl).toBe(expectedIntl);
});

test("runtime assignment: process.env.TZ = 'MSK-3'", async () => {
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", "process.env.TZ = 'MSK-3'; process.stdout.write(String(new Date().getTimezoneOffset()))"],
env: { ...bunEnv, TZ: "Etc/UTC" },
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(stdout).toBe("-180");
expect(exitCode).toBe(0);
});

// Forms the normalizer must NOT parse as an offset. The fall-through zone is
// host-dependent (registry on Windows, /etc/localtime for some of these on
// POSIX), so assert the override is not an Etc/GMT* zone rather than a fixed
// offset.
test.each(["IST-5:30", "FOO4BAR", "XX-3", "ABC-05:00"])("TZ=%s is not parsed as an offset", async tz => {
const { intl } = await offset(tz);
expect(intl).not.toMatch(/^Etc\/GMT[+-]/);
});

Check warning on line 63 in test/js/node/process/process-env-tz.test.ts

View check run for this annotation

Claude / Claude Code Review

Fall-through tests still have residual host-zone dependence

The two reworked fall-through tests still carry a residual host-zone assumption after `commit(emptyString())`. Here, `expect(intl).not.toMatch(/^Etc\/GMT[+-]/)` fails when the *host* zone is itself `Etc/GMT±N` — several stock Windows zones map that way in ICU's windowsZones (Dateline Standard Time→`Etc/GMT+12`, UTC-11→`Etc/GMT+11`, UTC+12→`Etc/GMT-12`), and a POSIX `/etc/localtime` can point at one. The same class of gap remains at line 129: `expect(b).not.toBe(a)` fails on a Windows machine who
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
});

describe.concurrent("process.env.TZ leading colon", () => {
test("':America/New_York' strips the colon", async () => {
const { intl } = await offset(":America/New_York");
expect(intl).toBe("America/New_York");
});
});

describe.concurrent.skipIf(!isPosix)("process.env.TZ absolute tzfile path", () => {
const target = "Australia/Sydney";
const zoneinfo = ["/usr/share/zoneinfo", "/usr/lib/zoneinfo", "/etc/zoneinfo"]
.map(dir => join(dir, target))
.find(p => existsSync(p));

test.skipIf(!zoneinfo)("':/etc/localtime' style symlink resolves to the zone it points at", async () => {
using dir = tempDir("tz-localtime", {});
const link = join(String(dir), "localtime");
symlinkSync(zoneinfo!, link);
// Resolve through the symlink just like a container-mounted /etc/localtime.
const { intl } = await offset(":" + link);
expect(intl).toBe(target);
});

test.skipIf(!zoneinfo)("'/usr/share/zoneinfo/...' prefix is stripped", async () => {
const { intl } = await offset(zoneinfo!);
expect(intl).toBe(target);
});

test.skipIf(!zoneinfo)("':/usr/share/zoneinfo/...'", async () => {
const { intl } = await offset(":" + zoneinfo!);
expect(intl).toBe(target);
});
});

describe.concurrent("process.env.TZ IANA name unchanged", () => {
test.each([
["America/New_York", "America/New_York"],
["Etc/GMT-3", "Etc/GMT-3"],
["UTC", "UTC"],
] as const)("TZ=%s", async (tz, expectedIntl) => {
const { intl } = await offset(tz);
expect(intl).toBe(expectedIntl);
});
});

test("runtime assignment of an unrecognized TZ clears a prior override", async () => {
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`const host = new Date().getTimezoneOffset();
process.env.TZ = 'Asia/Tokyo';
const a = new Date().getTimezoneOffset();
process.env.TZ = 'not a real zone';
const b = new Date().getTimezoneOffset();
process.stdout.write(host + ' ' + a + ' ' + b);`,
],
env: { ...bunEnv, TZ: "Etc/UTC" },
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
const [host, a, b] = stdout.split(" ").map(Number);
expect(a).toBe(-540);
expect(b).not.toBe(a);
if (isPosix) expect(b).toBe(host);
expect(exitCode).toBe(0);
});
Loading