Skip to content

Commit

Permalink
Fix crash with .env files that are exactly 159 bytes long (#3369)
Browse files Browse the repository at this point in the history
* Fix crash with .env files that are exactly 158 bytes and a newline character

* Update env_loader.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
  • Loading branch information
Jarred-Sumner and Jarred-Sumner committed Jun 21, 2023
1 parent b9c950b commit f81c7f1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/env_loader.zig
Original file line number Diff line number Diff line change
Expand Up @@ -884,18 +884,21 @@ pub const Loader = struct {
defer file.close();

const stat = try file.stat();
if (stat.size == 0) {
const end = stat.size;

if (end == 0) {
@field(this, base) = logger.Source.initPathString(base, "");
return;
}

var buf = try this.allocator.allocSentinel(u8, stat.size, 0);
var buf = try this.allocator.alloc(u8, end + 1);
errdefer this.allocator.free(buf);
var contents = try file.readAll(buf);
const amount_read = try file.readAll(buf[0..end]);

// The null byte here is mostly for debugging purposes.
buf[end] = 0;

// always sentinel
buf.ptr[contents + 1] = 0;
const source = logger.Source.initPathString(base, buf.ptr[0..contents :0]);
const source = logger.Source.initPathString(base, buf[0..amount_read]);

Parser.parse(
&source,
Expand Down
23 changes: 23 additions & 0 deletions test/cli/run/env.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,29 @@ describe("dotenv priority", () => {
});
});

test(".env doesnt crash with 159 bytes", () => {
const dir = tempDirWithFiles("dotenv-159", {
".env":
"123456789=1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678" +
"\n",
"index.ts": "console.log(process.env['123456789']);",
"package.json": `{
"name": "foo",
"devDependencies": {
"conditional-type-checks": "1.0.6",
"prettier": "2.8.8",
"tsd": "0.22.0",
"typescript": "5.0.4"
}
}`,
});

const { stdout } = bunRun(`${dir}/index.ts`);
expect(stdout.trim()).toBe(
`1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678`,
);
});

test.todo(".env space edgecase (issue #411)", () => {
const dir = tempDirWithFiles("dotenv-issue-411", {
".env": "VARNAME=A B",
Expand Down

0 comments on commit f81c7f1

Please sign in to comment.