safewrite

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 25, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package safewrite provides a hardened file-write helper that protects against common symlink and permission attacks.

The function in this package — WriteFile — performs the same hardened atomic write security checks:

  1. Refuses to follow symlinks (O_NOFOLLOW).
  2. Writes to a temporary file in the same directory first.
  3. Sets the new file's mode to 0600 (owner read/write only).
  4. Atomically renames the temp file to the final path (os.Rename on POSIX, which is atomic for same-filesystem).
  5. Refuses to operate on paths that already exist as symlinks pointing elsewhere (TOCTOU-resistant).

GrayCode native implementation. bin/install.js (safeWriteFlag). Ported to native Go.

This is a low-level utility intended for hooks and other code that writes to disk on behalf of the agent. Callers that need more elaborate behavior (e.g. preserving existing mode bits) should use os.WriteFile directly with their own audit trail.

Index

Constants

This section is empty.

Variables

View Source
var ErrPathEscape = errors.New("safewrite: path escapes parent directory")

ErrPathEscape is returned when the resolved path tries to escape the parent directory (e.g. via "..").

View Source
var ErrSymlinkTarget = errors.New("safewrite: destination is a symlink")

ErrSymlinkTarget is returned when the destination path already exists as a symlink. The caller should remove the symlink first or use a different path.

Functions

func WriteFile

func WriteFile(path string, data []byte) error

WriteFile writes data to path atomically with strict security guarantees:

  • If path already exists and is a symlink, returns ErrSymlinkTarget.
  • Writes to path.tmp.<pid> in the same directory, then renames.
  • The final file is mode 0600.
  • The temp file is opened with O_NOFOLLOW|O_WRONLY|O_CREATE|O_TRUNC.
  • The parent directory must already exist; it is not created.

On success, the destination file exists with the requested contents and mode 0600. On failure, the destination file is unchanged and any temp file left behind is cleaned up.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL