A source-grounded read of GoVault: purego bindings into Security.framework, OSStatus as a Go error type, and a clipboard that checks before it clears.
· 7 min read

How GoVault Reaches the macOS Keychain from Go Without cgo


Putting a secret behind Touch ID on macOS often brings cgo into the build: link Security.framework, add C glue, and require a C toolchain. GoVault at the revision reviewed here takes another route. cmd/govault/biokeychain_darwin.go opens CoreFoundation and Security at runtime with purego v0.11.3 and binds the symbols it needs to Go function values.

The interesting parts are in that file, cmd/govault/biokeychain.go, and cmd/govault/adapters.go. They show both the appeal of this approach and the places where it needs care.

Binding a macOS framework to Go function fields

The Darwin file is guarded by //go:build darwin && !ios, so non-macOS and iOS builds exclude it. Inside, a struct holds the foreign API surface as Go function types:

type cfFuncs struct {
	CFRelease                  func(uintptr)
	CFDictionaryCreateMutable  func(alloc uintptr, capacity int, keyCB, valueCB uintptr) uintptr
	CFDictionarySetValue       func(dict, key, value uintptr)
	CFDataCreate               func(alloc uintptr, bytes *byte, length int) uintptr
	// ...
	SecItemAdd                 func(attrs uintptr, result *uintptr) int32
	SecItemCopyMatching        func(query uintptr, result *uintptr) int32
	SecItemDelete              func(query uintptr) int32
	SecAccessControlCreateWith func(alloc, protection uintptr, flags uint64, err *uintptr) uintptr
}

loadSecurity fills the struct in. It Dlopens both framework paths, then runs one purego.RegisterLibFunc(&cf.SecItemAdd, secLib, "SecItemAdd") per field. Go field names and C symbol names are independent, which the file uses: SecAccessControlCreateWith is bound to SecAccessControlCreateWithFlags.

That independence cuts both ways. The Go compiler cannot check these declarations against Apple’s C signatures. A wrong argument or return type can produce corrupted values or a crash at runtime, so each binding needs to be checked against the framework API.

Loading happens once, with the failure parked in a package-level variable:

var (
	secOnce sync.Once
	secErr  error
	cf      cfFuncs
	sc      secConsts
)

This is a useful pattern for lazy initialization that can fail. sync.Once runs the body exactly once but returns nothing, so the code stores the error inside the once-protected function and reads it afterwards. The sync.Once memory guarantee safely publishes both the function table and the error to later callers.

Data symbols need different handling from functions. CoreFoundation exports kCFBooleanTrue and friends as data, not code, so the file wraps purego.Dlsym in a helper:

sym := func(lib uintptr, name string, deref bool) uintptr {
	addr, err := purego.Dlsym(lib, name)
	if err != nil {
		secErr = err
		return 0
	}
	if !deref {
		return addr
	}
	return **(**uintptr)(unsafe.Pointer(&addr))
}

Sometimes you want the address itself. kCFTypeDictionaryKeyCallBacks goes straight into CFDictionaryCreateMutable as a pointer to a callbacks struct. Sometimes you want the pointer value stored at that address, because kCFBooleanTrue is a CFTypeRef sitting in memory. The deref flag picks, and the double indirection through unsafe.Pointer does the read.

The file also defines constants such as kSecAccessControlBiometryCurrentSet = 1 << 3 and kCFStringEncodingUTF8 = 0x08000100 locally. Without imported headers, those values must be kept aligned with Apple’s SDK definitions, just like the function signatures.

Wrapping OSStatus into Go errors

Security.framework answers in OSStatus codes, which are int32. cmd/govault/biokeychain.go gives them a type:

type OSStatusError int32

func (e OSStatusError) Error() string { return fmt.Sprintf("keychain: OSStatus %d", int32(e)) }

const (
	errUserCanceled          OSStatusError = -128
	errUnimplemented         OSStatusError = -4
	errParam                 OSStatusError = -50
	errNotAvailable          OSStatusError = -25291
	errAuthFailed            OSStatusError = -25293
	errItemNotFound          OSStatusError = -25300
	errInteractionNotAllowed OSStatusError = -25308
	errMissingEntitlement    OSStatusError = -34018
)

OSStatusError is a comparable value type that implements error, so errors.Is can match these constants without a custom Is method. statusError(status int32) error returns nil for zero and an OSStatusError otherwise, which keeps raw status comparisons out of every call site.

The payoff shows up in one predicate that answers one question: should we give up on the hardware and use the ordinary keychain?

func hardwareUnavailable(err error) bool {
	var acErr *accessControlError
	return errors.As(err, &acErr) || errors.Is(err, errMissingEntitlement) || errors.Is(err, errNotAvailable) ||
		errors.Is(err, errParam) || errors.Is(err, errUnimplemented)
}

The predicate uses errors.As for the pointer type and errors.Is for the value constants. A cancelled or failed authentication does not count as unavailable hardware. Get maps errUserCanceled and errAuthFailed to a wrapped govaultui.ErrBiometricCancelled, allowing the UI to distinguish a declined or failed prompt from an unavailable keychain feature.

Two stores behind one interface

BiometricSecretStore holds a fallback store.SecretStore and an hw hardwareKeychain. Accounts prefixed userkey: go to the hardware keychain; everything else goes straight to the fallback. hardwareKeychain is four methods, Add, Copy, Exists, Delete, which is exactly why non-darwin builds and tests can exist at all.

The Set path makes the migration order explicit:

_ = s.hw.Delete(account)
err := s.hw.Add(account, []byte(value))
if err == nil {
	if err := s.fallback.Delete(account); err != nil {
		return fmt.Errorf("keychain: saved with Touch ID protection, but could not remove the login keychain copy: %w", err)
	}
	return nil
}

After a best-effort deletion of any existing hardware-protected item, the code adds the new protected copy. Only after that succeeds does it remove the fallback copy. If fallback deletion fails, the error reports both parts of the resulting state: the protected secret was saved, but a login-keychain copy remains.

The Touch ID prompt text lives in an atomic.Value, not a plain string field. SetPrompt is driven from a reactive effect in cmd/govault/app.go, app.Effect(func() { secrets.SetPrompt(locales.For(app).KeychainPromptReason()) }), so it updates when the displayed language changes while Get can read it safely from another goroutine.

Clipboard ownership as a small state machine

cmd/govault/adapters.go holds the other piece of careful code. Copy a password, clear it after a while. Sounds like four lines. It isn’t, and the comments in that file say why.

On macOS, ClipboardAdapter.CopySecret hands off to a concealed clipboard type and reports true. On other platforms it writes the value and stops any previous timer. For a timed copy, it also records the string in owned and arms time.AfterFunc(clearAfter, func() { c.expire(expected) }).

expire doesn’t clear anything until it has looked:

func (c *ClipboardAdapter) expire(expected string) {
	c.post(func() {
		c.read(func(current string) {
			switch current {
			case expected:
				c.write("")
			case "":
				c.retryExpire(expected)
			default:
				c.release(expected)
			}
		})
	})
}

If someone copied something else in the meantime, GoVault drops ownership and leaves their data alone. Wiping a clipboard you no longer own is a small, infuriating bug, and this is the shape that prevents it.

An empty read does not prove that the secret is gone: the source comment notes that Windows returns "" while another app holds the clipboard open. The adapter therefore retries up to clipboardRetries = 5 instead of releasing ownership immediately.

The API shape also makes the asynchronous flow visible: read accepts a callback rather than returning a string. The mu sync.Mutex covers owned, retries, and timer, which the time.AfterFunc goroutine and the UI thread both touch.

ClearOnQuit handles timers that would otherwise die with the process. It clears a pending concealed copy on macOS. On Windows, clearClipboardIfOwned synchronously clears the system clipboard only if it still contains GoVault’s secret. Linux needs no equivalent: the application serves the clipboard, so its copy disappears with the process, although an external clipboard manager may retain its own copy.

The test seam: function fields

ClipboardAdapter declares its platform calls as fields:

// The clipboard as the app sees it; tests replace these.
post  func(func())
read  func(func(string))
write func(string)
later func(func())

NewClipboardAdapter points them at the real scope.Post, scope.ReadClipboard, and scope.SetClipboard, with later as a one-second time.AfterFunc. Tests can replace all four, exercising the retry logic without a real clipboard or real waiting.

cmd/govault/app.go does the same thing one level up. DesktopShell carries newTray func(cx *core.Scope, opts desktop.TrayOptions) trayIcon, commented “tests record it instead”. For one or two replaceable calls, function fields keep the test seam small.

How the UI layer is wired

The app is built on NSGo, and two of its primitives do most of the work in the files here.

app.Post marshals work onto the UI thread. The state.NewService callbacks in app.go, OnStatusChange and OnVaultUpdated, can run away from that thread, so both post their model updates. The status callback then re-reads shell.service.Status() inside the posted closure because a sleep or Back to Unlock may have locked the session while the callback was queued.

app.Effect re-runs when its reactive dependencies change. cmd/govault/appmenu.go uses it to rebuild the whole menu bar:

func installApplicationMenu(app *core.Scope, goos string, checkUpdates func()) {
	app.Effect(func() {
		desktop.SetApplicationMenu(app, applicationMenu(locales.For(app), goos, checkUpdates))
	})
}

applicationMenu branches on goos. On darwin it returns the standard app, Edit and Window menus built from role constants like desktop.MenuUndo and desktop.MenuWindowMenu, deliberately with no handlers so the items travel the responder chain the way NSGo’s default menu does. Everywhere else it returns one “GoVault” menu: Check for Updates, a separator, Quit. Check for Updates is in both, and the comment explains the choice: it doesn’t depend on the vault, so it still works logged out, locked, or without a tray icon.

The tray assets are two files via go:embed, and the comments say why there are two. TrayTemplate.png is 32x36 and drawn as a template image in menu bar colors. TrayIcon.png is 64x64 color, because Windows and Linux trays render the icon as given and a black template glyph would disappear into a dark taskbar.

For contrast, there’s a Wails walkthrough and a look at Gova’s declarative structs. GoVault’s keychain path uses no C compiler; it resolves the platform APIs by name at runtime.

That is the trade-off. Every symbol name, signature, and flag constant in biokeychain_darwin.go is a hand-maintained copy of an Apple API, without a compiler checking it against the headers. In exchange, the project keeps a zero-cgo build. The approach is manageable for a small, tested surface; the maintenance risk grows with every added binding.