In the previous article, we explored what Piko2fa does, why I decided to store my 2FA keys in an encrypted file under my control, and its threat model. Now it’s time to truly look under the hood.
This is the fifth installment in the Go series. We’re not going to examine a toy example, but a real-world tool with about 2,900 lines of production code, backed by over 4,450 lines of tests, and compiled without CGO (CGO_ENABLED=0) for Windows, Linux, and macOS. Furthermore, while preparing this walkthrough, I took the opportunity to critically review the core and apply five concrete improvements in commit 69a9d80.
In this first part, we’ll focus on the core: how the project is organized, why it uses this on-disk format, how it saves data without rendering the vault unusable during a power cut or crash, and how to test failures that are typically hard to reproduce.
Project Structure and Why There’s No SQLite or CGO
The code is split between a minimal entry point and private packages under internal/:
piko2fa/
├── cmd/piko2fa/main.go # 19 líneas: arranque y salida con código de error
└── internal/
├── totp/ # RFC 6238 / RFC 4226 puro
├── model/ # Entry, validaciones y deduplicación por secreto
├── otpauth/ # parseo y formato de URIs otpauth://
├── gamigration/ # importador de Google Authenticator (protowire)
├── qrimage/ # decodificación de QR desde PNG o JPEG
├── vault/ # KDF, formato binario, cifrado y guardado atómico
├── tui/ # interfaz interactiva de solo lectura (Bubble Tea)
└── cli/ # comandos (cobra), consola, portapapeles y tests
In Go, everything residing inside internal/ can only be imported from within the module itself. This avoids having to stabilize a public API for a command-line binary and allows for complete freedom when refactoring internal packages.
One of the earliest architectural decisions was ruling out SQLite in favor of a single fully encrypted JSON file (vault.bin): it is decrypted entirely into memory upon opening, modified in-memory, and re-encrypted in its entirety when saved. Three clear reasons led to this choice:
- CGO breaks effortless cross-compilation. SQLCipher depends on C. Without CGO, building binaries for Windows, Linux, and macOS from any machine is just a single
go buildcommand. - Field-level encryption leaks metadata. Even if you encrypt the secret in each row, a database still exposes how many accounts you have, their relative sizes, or which rows have changed. With a single encrypted blob, all of that disappears.
- No decrypted temporary files on disk. Decrypting a database to a temporary file opens the door to unencrypted artifacts lingering after a crash or on an SSD (where secure deletion is trickier than it seems).
For a password manager holding tens of thousands of entries and binary attachments, this approach wouldn’t scale. For ~300 2FA accounts—a few dozen kilobytes of JSON—it’s simple, fast, and easy to audit.
The Vault Format: Authenticated Encryption and Pre-KDF Defenses
Every time Piko2fa saves the vault, it generates a binary file with this big-endian structure (internal/vault/format.go):
magic (4: "PK2F") | versión (1) | tiempo (4) | memoria en KiB (4) | hilos (1) | sal (16) | nonce (24) | texto cifrado + tag (16)
The first 30 bytes (from PK2F up to the 16-byte salt) make up the header. The 32-byte encryption key is derived using Argon2id (t=3, 64 MiB, 4 threads) from the master password and that salt. Then, the JSON payload is encrypted with XChaCha20-Poly1305, using a fresh salt and a random 24-byte nonce on every save.
There are two important details in the seal and unseal functions:
- The header is authenticated as AAD (Additional Authenticated Data). It isn’t encrypted—the salt and Argon2id parameters need to be readable to derive the key—but it is passed into
aead.Sealandaead.Open. If anyone flips a single bit in the version, parameters, or salt, Poly1305 rejects decryption. - Argon2id parameters are validated before deriving the key. This detail is easy to overlook: since the header cannot be authenticated until the key is derived, an attacker or a corrupted file could specify
4 GiBof memory or0threads in the header. Without upfront bounds checks, the program would exhaust RAM or panic before even reachingaead.Open.
Here is how it looks in internal/vault/format.go:
const (
minTime = 1
maxTime = 10
minThreads = 1
maxThreads = 16
minMemoryKiB = 32 * 1024
maxMemoryKiB = 1024 * 1024
)
func unseal(password, data []byte) ([]byte, error) {
if len(data) <= len(magic) || !bytes.HasPrefix(data, []byte(magic)) {
return nil, ErrInvalid
}
if data[len(magic)] != formatVersion {
return nil, ErrUnsupportedVersion
}
if len(data) < minSize {
return nil, ErrInvalid
}
rest := data[len(magic)+1:]
p := kdfParams{
time: binary.BigEndian.Uint32(rest[0:4]),
memoryKiB: binary.BigEndian.Uint32(rest[4:8]),
threads: rest[8],
}
if !p.valid() {
return nil, ErrInvalid
}
salt := rest[9 : 9+saltSize]
key := deriveKey(password, salt, p)
defer clear(key)
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, ErrInvalid
}
header := data[:headerSize]
nonce := data[headerSize : headerSize+chacha20poly1305.NonceSizeX]
plaintext, err := aead.Open(nil, nonce, data[headerSize+chacha20poly1305.NonceSizeX:], header)
if err != nil {
return nil, ErrInvalid
}
return plaintext, nil
}
Notice also the error handling: an incorrect password, an out-of-range header, and an authentication failure all return the exact same ErrInvalid, offering zero clues as to what went wrong. Only an unsupported future version returns ErrUnsupportedVersion, because the version byte is public and it helps to let the user know they need a newer release of the tool.
Saving Without Breaking Anything (Even on Windows)
An intact encrypted file is of little use if a sudden power loss or a write error leaves it truncated. The vault package wraps every write operation in multiple layers of defense (internal/vault/vault.go):
- Inter-process locking via a dedicated file (
vault.bin.lock). Acquired usinggofrs/flockfromOpentoClose, covering the full read-modify-write cycle. We don’t lockvault.bindirectly because saving replaces the file viarename. In addition, the CLI always prompts for the password before callingOpen, avoiding holding the lock while the user is typing. - Verifying the current file before touching
.bak. Before overwritingvault.bin.bakandvault.bin,Saveverifies that thevault.bincurrently on disk can be decrypted with the provided password:
func (s *FileStore) Save(password []byte) error {
if s.closed {
return ErrClosed
}
if !s.loaded {
return ErrNotLoaded
}
if len(password) == 0 {
return ErrEmptyPassword
}
current, err := s.readVault()
if err != nil {
return err
}
plaintext, err := unseal(password, current)
if err != nil {
return err
}
clear(plaintext)
if err := s.writeAtomic(s.path+backupSuffix, current, "backup"); err != nil {
return err
}
return s.writeVault(password)
}
This verification costs an extra Argon2id key derivation (a few hundred milliseconds) each time you add or delete an account. It is a deliberate tradeoff: it prevents a damaged file from clobbering the only healthy .bak and keeps users from accidentally re-encrypting the vault with a different password. To change the password, there is a dedicated method: ChangePassword (internal/vault/maintenance.go).
- Atomic writes and OS-specific quirks.
writeAtomiccreates a hidden temporary file in the destination directory (.piko2fa-*.tmp), writes the bytes, callstmp.Sync(), closes the file descriptor, renames over the target, and, on Linux and macOS, syncs the parent directory (syncDir) to make the directory entry durable.
Two specific quirks arise on Windows:
- You cannot call
Sync()on a directory, sosyncDiris a no-op on Windows (and on Unix, it ignoressyscall.EINVALfor filesystems that don’t support it either). - An antivirus or indexer might briefly hold
vault.binopen right as you attempt to replace it, causingos.Renameto fail. That’s whyrenameperforms up to 10 retries spaced100 msapart, exclusively on Windows.
- Crash-tolerant password changes.
ChangePassword(internal/vault/maintenance.go) re-encryptsvault.bin.bakfirst, followed byvault.bin. If a crash happens in between,vault.binstill opens with the old password, allowing the user to simply re-runpiko2fa passwd. On retry,reencryptBackupchecks whether the.bakalready opens withnewPassword: if so, it assumes it came from an interrupted attempt and proceeds. If the.bakcannot be opened with either password, it returnsErrBackupUnreadablewithout touching the primary vault.
Testing the Hard Stuff: Fault Injection and Concurrent Processes
Trivial round-trip tests don’t prove that a save operation is truly atomic. The real risk lies in partial failures and concurrent writes by multiple processes.
To test partial failures without building mock filesystems or giant mock suites, FileStore contains a single-line private field:
step func(name string) error
In production, it is nil, and runStep does nothing. In writeAtomic, before each critical step (create, write, sync, close, rename, syncdir), s.runStep(label + ":...") is called. This enables TestSaveFailureAtEveryStepKeepsVaultReadable (internal/vault/vault_test.go) to inject an error at each of the 12 stages of the save process (6 for .bak and 6 for vault.bin) and verify that:
vault.binon disk remains openable (either in its previous state, or in the new state if onlyvault:syncdirfailed post-rename), and- no orphaned
.tmpfiles are left behind in the directory.
To test inter-process locking, TestConcurrentProcessesLoseNoUpdates uses a very idiomatic Go pattern: it spawns 6 subprocesses of the test binary itself (os.Args[0]), filtering for a single helper test:
cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProcessAddEntry$", "-test.count=1")
cmd.Env = append(os.Environ(), "PIKO2FA_TEST_VAULT="+path, "PIKO2FA_TEST_NAME="+name)
Each process opens the same vault.bin, waits for the lock on vault.bin.lock, adds its entry, and saves. Once all 6 complete in parallel, the test asserts that all 6 accounts exist and no updates were lost.
Two Small Pieces Without Heavy Libraries: TOTP and Manual Protobuf
Generating a TOTP code per RFC 6238 and RFC 4226 requires no external libraries: it’s simply HMAC over a 64-bit counter followed by dynamic 4-byte truncation:
TOTP in 86 Lines (internal/totp/totp.go)
Generating a TOTP code per RFC 6238 and RFC 4226 requires no external libraries: it’s simply HMAC over a 64-bit counter followed by dynamic 4-byte truncation:
counter := uint64(t.Unix()) / uint64(period)
mac := hmac.New(newHash, secret)
mac.Write(binary.BigEndian.AppendUint64(nil, counter))
sum := mac.Sum(nil)
// Truncamiento dinámico de RFC 4226, sección 5.3.
offset := sum[len(sum)-1] & 0x0f
value := binary.BigEndian.Uint32(sum[offset:]) & 0x7fffffff
return fmt.Sprintf("%0*d", digits, value%modulus), nil
The entire package—supporting SHA1, SHA256, and SHA512, 6 or 8 digits, and calculating remaining seconds—spans 86 lines and is verified against the official RFC 6238 and RFC 4226 test vectors.
Protobuf Without protoc (internal/gamigration/payload.go)
Google Authenticator exports accounts as otpauth-migration://offline?data=... URIs, where data is a base64-encoded Protobuf message (MigrationPayload). Instead of installing protoc, generating .pb.go files, and dragging in generated message structs, the package uses google.golang.org/protobuf/encoding/protowire directly (a lightweight, low-level subpackage).
Implementing this by hand yielded three concrete takeaways:
proto3omits default/zero values. An export containing a single QR code might omitbatch_size, which is whyp.batchSize == 0is normalized to1after parsing the message.- Signed
int32integers in varints. If anint32field carries a negative value, it travels across the wire sign-extended to 64 bits; you must cast toint32(value)before converting toint. - Base64
+characters andurl.ParseQuery.url.ParseQueryalready URL-decodes thedataparameter; decoding it again would corrupt the base64 string. However, some QR readers leave+unencoded instead of%2B, andParseQueryturns+into a space. Restoring" "back to"+"before callingbase64.RawStdEncoding.DecodeStringfixes the issue without breaking properly encoded URIs.
Additionally, if new fields appear in future Google Authenticator versions, protowire.ConsumeFieldValue skips them cleanly in the default branch.
Reviewing the Code: Five Improvements Applied to the Core
Re-reading the entire project before writing this series revealed five areas for improvement in the core. All of them were implemented in commit 69a9d80:
- Removing an interface with no consumers (
vault.Store).
When designing the project, I defined aStoreinterface ininternal/vault“in case the format changes someday”. In practice, the entire CLI received the concrete*vault.FileStore, and methods likeChangePassword,Export, orRestoredidn’t even fit intoStore. It’s a reminder of a classic Go proverb: accept interfaces at the consumer when a second implementation emerges, don’t declare them upfront at the producer. - Decoupling deduplication from
gamigration.
TheDedupefunction (which detects whether a secret already exists or conflicts with another issuer/name) lived ininternal/gamigration, forcingpiko2fa addto import the Google Authenticator package just to add a manual entry. Now,Dedupe,Conflict, andDedupeResultlive ininternal/model/dedupe.go, where domain logic truly belongs. - Unifying invariants between model and store.
Entry.Validate()(internal/model/entry.go) checked the secret, algorithm, digits, period, and type, but not whetherIDwas set; that was checked separately inFileStore.Add. Worse yet:decodeContentswhen loading a vault from disk didn’t check for empty or duplicate IDs. NowEntry.Validate()requiresID != ""anddecodeContentsrejects duplicate IDs upon loading. - Avoiding duplicate cryptographic work and tightening
exportdetails.piko2fa export --encryptedpassed throughwithVault(which derived the key via Argon2id and decrypted JSON in memory) only to then callFileStore.Export, which re-read the file and derived the key a second time. Now,export --encryptedcallss.Export(...)directly after acquiring the lock, running Argon2id only once.FileStore.Exportcheckedos.Statbefore writing withwriteAtomic, leaving a small time-of-check to time-of-use (TOCTOU) race condition between checking and renaming. It now writes usingwriteExclusive(O_CREATE|O_EXCL,Sync(),Close(), andsyncDir), guaranteeing atomically at the filesystem level that it will never overwrite an existing file.- In
exportPlaintext(internal/cli/commands.go), plaintext URIs were accumulated in an immutablestrings.Builderwithout aSync()equivalent. They are now accumulated in a[]byteand wiped with a subtle Go nuance:var content []byte defer func() { clear(content) }()
Had we writtendefer clear(content)directly, Go would have evaluated the initial value ofcontent(nil) when registering thedefer, zeroing an empty slice whileappendallocated an entirely new underlying array behind the scenes.
- Module path ready for
go install.go.modstill listedmodule piko2fafrom early development. Changing it tomodule github.com/jure-ve/piko2faallows installing the tool directly with:
What We’ll See in the Next Article
With the vault and cryptography covered, in the second part we’ll move up to the layer closest to the user and human error:
- How to prevent an accidentally pasted secret URI from leaking into a Cobra error message, a
*fs.PathError, or a%#vdump. - How to read passwords securely when
stdinis piped, and restore terminal echo if the user hitsCtrl+C. - Non-obvious Bubble Tea TUI details (such as stripping the monotonic clock with
.Round(0)so sleep/suspend time counts toward auto-lock, or sanitizing ANSI sequences from imported accounts). - And the second batch of improvements: minor UX bugs in
import-ga, CLI-level sanitization, terminal width handling in the TUI, clearing the clipboard onCtrl+C, and QR decoder optimizations.
All code remains available under the MIT license at github.com/jure-ve/piko2fa, and the five changes from this article are grouped in commit 69a9d80.
Which part of the architecture did you find most interesting, or what would you have done differently? Let me know in the comments.
Keep coding.