This file provides context for AI assistants (like Claude, ChatGPT, or GitHub Copilot) when working with the certwiz project.
Project Name: certwiz
Binary Name: cert
Purpose: A user-friendly CLI tool for certificate management, similar to HTTPie but for certificates.
- The project is called
certwiz - The binary/command is called
cert - Documentation should refer to the command as
cert - The repository and package remain
certwiz
certwiz/ # Project root (name: certwiz)
├── main.go # Entry point
├── Makefile # Builds binary as 'cert'
├── go.mod # Module: certwiz (go 1.20)
├── cmd/ # CLI commands
│ ├── root.go # Root command (Use: "cert"), Execute() prints unreported errors
│ ├── inspect.go # cert inspect (looksLikeFilePath decides file vs host)
│ ├── generate.go # cert generate
│ ├── convert.go # cert convert
│ ├── verify.
8000
go # cert verify
│ ├── ca.go # cert ca
│ ├── csr.go # cert csr
│ ├── sign.go # cert sign
│ ├── tls.go # cert tls
│ ├── update.go # cert update
│ ├── helpers.go # printJSON, printJSONError, reportError
│ └── helpers_test.go # Test fixtures: captureStdout, setOutputMode, startTLSServer,
│ # startSilentListener, resetCommandFlags, newTestCA/newTestLeaf
├── pkg/ # Core packages
│ ├── cert/ # Certificate operations
│ │ ├── cert.go # Inspect/generate/convert/verify/sign, TLS probing, PEM writers
│ │ ├── json.go # JSON output structures and ToJSON/MarshalJSON
│ │ ├── san.go # SAN parsing utilities
│ │ ├── usage.go # Key-usage name tables shared by JSON and UI
│ │ └── refactor_test.go # Fixtures: newTestKeyPair, startTLSServer, startTLSServerWithCert
│ └── ui/ # Terminal UI with lipgloss
│ └── ui.go
├── internal/ # Internal packages
│ ├── config/ # YAML config loading (~/.config/certwiz/config.yaml)
│ │ └── config.go
│ ├── environ/ # Environment detection
│ │ └── env.go # IsCI/SupportsUnicode (cached) over detectCI/detectUnicode
│ └── testutil/ # TestdataPath(filename) for files under testdata/
├── testdata/ # Test certificates (committed)
└── docs/ # Documentation
├── installation.md
├── usage.md
├── commands.md
├── examples.md
├── contributing.md
├── releasing.md
├── testing.md
└── faq.md
- Language: Go 1.20+ (see Go 1.20 Compatibility below)
- CLI Framework: Cobra (github.com/spf13/cobra)
- UI Library: Lipgloss v0.9.1 (github.com/charmbracelet/lipgloss)
- Config: gopkg.in/yaml.v3
- Certificate Handling: Go standard library (crypto/x509, crypto/tls)
make build # Creates ./cert binary
make install # Installs to $GOPATH/bin
make clean # Removes build artifacts
make build-all # Cross-platform builds into dist/All commands follow this pattern:
cert [command] [target] [flags]Commands:
inspect- View certificate details from files, bundles, stdin (-), or URLsgenerate- Create self-signed certificatesconvert- Convert between PEM/DER formats (bundle-aware)verify- Validate certificates (dates, hostname, CA chain, private key, expiry window)ca- Create Certificate Authority certificatescsr- Generate Certificate Signing Requestssign- Sign CSRs with a CA certificatetls- Test which TLS versions a server supportsupdate- Update cert to the latest versionversion- Show version informationcompletion- Generate shell completion scripts
Global flags: --json (machine output on stdout), --plain (no borders, colors, or emojis). --timeout on inspect and tls is a time.Duration flag (DurationVar, default 5s).
- Follow standard Go idioms
- Use meaningful variable names
- Keep functions small and focused
- Handle errors explicitly
- Add comments for complex logic
- Colors: Green (valid), Yellow (warning), Red (error), Blue (info)
- Output: Readable, terminal-width aware
- Defaults: Smart defaults that just work
- Errors: Clear, actionable error messages
- Bordered tables for certificate info; continuation lines are indented to the value column by
formatTable - Terminal width is read once per display from stdout (
terminalWidth()), falling back to 80 - Color coding for status indicators
- Symbols: check mark (success), cross (failure), arrow (detail), link (URL);
ui.Emoji(emoji, ascii)picks the ASCII form under--plain, config, or CI. There is no private emoji helper incmd.
- Create
cmd/newcommand.gowith aRunE - Report failures with
reportError(cmd, err)andreturn err - Add to rootCmd (in the file's
init()orcmd/root.go) - Add the name to
expectedCommandsincmd/root_test.go - Update documentation and CHANGELOG.md (Unreleased)
- Extend
pkg/cert/cert.go(andjson.gofor JSON fields) - Add UI support in
pkg/ui/ui.go - Wire up in the appropriate command
- Add tests (see Test Conventions)
- Update docs
- Main README uses
certcommand in examples - Docs use
certcommand throughout - Keep project name as
certwizin descriptions
// From file (first cert) or every cert in a bundle
cert, err := cert.InspectFile(path)
certs, err := cert.InspectFileAll(path)
certs, err := cert.InspectData(data, "stdin")
// From URL; the older wrappers delegate to InspectURLWithOptions
cert, chain, err := cert.InspectURLWithOptions(url, port, connectHost, timeout, sigAlg)newCertificate(c, source, format) wraps an *x509.Certificate and computes IsExpired and DaysUntilExpiry once; use it instead of building Certificate literals.
// Convert returns the detected input format ("PEM"/"DER"). PEM output keeps
// every certificate in a bundle; DER output errors on multi-cert input.
inputFormat, err := cert.Convert(inputPath, outputPath, "der")
// All generators write through these helpers. Keys are opened 0600 directly
// (and re-chmodded on non-Windows); certificates are 0644.
err = writePrivateKey(keyPath, privateKey) // PKCS#8 PEM
err = writeCertificate(certPath, der)
err = writePEMFile(path, block, perm)
// CheckTLSVersions probes TLS 1.0-1.3 concurrently. If at least one version
// succeeded, each failure is re-probed once sequentially (some servers cap
// concurrent handshakes). A host that answers nothing is not retried, so it
// fails in about one timeout.
result, err := cert.CheckTLSVersions(host, port, timeout)Key-usage names come from cert.KeyUsageNames, cert.ExtKeyUsageName, and cert.ExtKeyUsageNames in pkg/cert/usage.go; both JSON and the terminal view use them. TLS version names come from cert.TLSVersionName.
ui.SetConfig(cfg) // invalidates cached text styles
ui.DisplayCertificate(cert, showFull)
ui.DisplayCertificateChain(chain)
ui.DisplayTLSVersionResults(result)
ui.ShowErrorTo(w, msg) // ShowError writes to os.StderrText styles are cached per config. getPanelStyle() stays a builder because callers mutate it (see Go 1.20 Compatibility for why).
Commands use RunE. Cobra's own error printing is disabled on the root command.
RunE: func(cmd *cobra.Command, args []string) error {
result, err := cert.DoThing(...)
if err != nil {
reportError(cmd, err) // JSON payload on stdout under --json, styled message on stderr otherwise
return err
}
...
}Execute() in cmd/root.go prints Error: <msg> to stderr for any error a command returned without calling reportError (flag errors, verification failed). Stream contract: human-readable errors on stderr, JSON payloads ({"success": false, "error": "..."}) on stdout, exit code 1 on failure, and every failure is printed exactly once.
IMPORTANT: Run the same checks CI runs before pushing.
# Tests with race detector, repeated to catch state leaks between cases
go test -race -count=3 ./...
# Lint exactly as CI does (golangci-lint v2, no config file). No docker needed:
GOFLAGS=-mod=mod go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest run --timeout=5m ./...
# Go 1.20 floor (downloads the toolchain once)
GOTOOLCHAIN=go1.20.14 go build ./... && GOTOOLCHAIN=go1.20.14 go test ./...
gofmt -l . # must print nothing
go vet ./...The docker variants (golangci/golangci-lint:latest, golang:1.20) also work on machines that have docker.
CI (.github/workflows/test.yml) runs Go 1.20 and 1.21 on ubuntu and windows, stable on macOS, lint via golangci/golangci-lint-action@v9 with version: latest, and build jobs. All actions are on Node 24 majors (checkout v7, setup-go v7, cache v6, upload-artifact v7, codecov v7, goreleaser-action v7). CODECOV_TOKEN is an optional repository secret; without it the upload runs tokenless and never fails the build.
- All error returns must be checked, in tests too:
defer func() { _ = f.Close() }(),defer func() { _ = os.RemoveAll(dir) }(),_ = os.Setenv(...) - Use embedded struct fields directly (
cert.Verify(opts), notcert.Certificate.Verify(opts)) - No
//nolintdirectives for linters that do not exist (golangci warns on unknown names) - Follow golangci-lint default rules (no custom .golangci.yml)
CI still tests Go 1.20 and 1.21 on Linux and Windows; the local toolchain may be much newer, so code that compiles locally can break CI.
- No
min/maxbuiltins, noslices,maps, orcmppackages, nosync.OnceValue, no range-over-int - No
tls.VersionName(Go 1.21); usecert.TLSVersionName - Pass loop variables into goroutines explicitly (
go func(i int, v T) {...}(i, v)) - Lipgloss v0.9.1 shares a
Style's internal rules map between copies, so never cache aStylethat is later mutated with builder methods such asBorderForeground. Cache only render-only styles; keepgetPanelStyle()a builder.
- "Previous case" error in switch statements: Missing import (e.g., crypto/ecdsa)
- "Could remove embedded field from selector": Use
cert.FieldNameinstead ofcert.Certificate.FieldName - Unchecked errors: Add
_ =for intentionally ignored errors - Failures only with
-count>1: package-level flag variables or cobra flag state leaked from an earlier case; reset witht.CleanuporresetCommandFlags - Missing test files: Ensure all testdata files are committed to git (update .gitignore if needed)
- IP addresses in SANs: Use
--san IP:192.168.1.1format, not just--san 192.168.1.1
The most common CI failures come from not running tests locally first!
# CI's exact command (note the space, not '=', for Windows):
go test -v -race -coverprofile coverage.out ./...
# If tests pass locally but fail in CI, try:
go clean -testcache
go mod tidy
go test -v -race -coverprofile coverage.out ./...- No network in tests. Remote inspection and
cert tlsare tested against in-process TLS servers:startTLSServer/startTLSServerWithCert/newTestKeyPairinpkg/cert/refactor_test.go, andstartTLSServer/startSilentListener/newTestCA/newTestLeafincmd/helpers_test.go. - The suite must pass
go test -race -count=3 ./.... State leaking between cases was a real problem. Reset package-level flag variables,jsonOutput/plainOutput, and stdin witht.Cleanup; useresetCommandFlagsbefore repeatedrootCmd.Executecalls. - Deterministic output. Use
setOutputMode(t, json, plain)in cmd tests, orui.SetConfigwith a plain config (config.DefaultConfig()thenApplyPlainMode()) in ui tests, so assertions do not depend on ANSI codes, emojis, or the CI environment variable. - Capture the right stream.
captureStdout(cmd) andcaptureOutput(ui) capture stdout; errors go to stderr, so usecaptureStreamsorcmd.SetErrwhen asserting on them. - Testdata paths go through
testutil.TestdataPath("valid.pem"), never hard-coded relative paths. - Coverage is around 95% of statements (cmd ~84%, pkg/cert ~95%, pkg/ui ~98%, internal/environ 100%). New code should keep it there; the uncovered remainder is fault injection (PEM encoder or Close failing,
crypto/randfailing, the update exec path).
When CI tests fail but local tests pass:
- Check the exact error message in CI. Syntax errors usually mean file corruption; build failures in one package cascade to others.
- Verify file integrity
tail -c 10 cmd/update.go | xxd # single trailing newline? curl -s https://raw.githubusercontent.com/trahma/certwiz/main/cmd/update.go | diff - cmd/update.go
- Reproduce the Go version with
GOTOOLCHAIN=go1.20.14 go test ./...(see Go 1.20 Compatibility). - Reproduce a platform with docker if available:
docker run --rm -v $(pwd):/app -w /app golang:1.20-alpine go test ./...
Test data files must be committed to git. .gitignore ignores *.pem, *.crt, *.key, and *.der everywhere except testdata/:
git ls-files testdata/ # confirm they are trackedNever hard-code ../../testdata/x.pem; it breaks on Windows. Use testutil.TestdataPath("x.pem"), which builds the path with filepath.Join.
./cert inspect google.com
./cert inspect google.com --full --chain
./cert inspect fullchain.pem --chain
openssl s_client -connect example.com:443 </dev/null | ./cert inspect -
./cert inspect google.com --connect localhost:8080 --timeout 2s
./cert generate --cn test.local --san test.local --san IP:192.168.1.1
./cert convert test.pem test.der --format der
./cert verify test.crt --host test.local
./cert verify test.crt --key test.key
./cert verify test.crt --expires-in 30d
./cert tls google.com
./cert tls google.com --json
./cert ca --plain # error on stderr once, exit 1
./cert update
./cert update --force- google.com (many SANs)
- github.com (standard setup)
- expired.badssl.com (expired cert)
- self-signed.badssl.com (self-signed)
- Run full test suite:
go test -race -count=3 ./... - Lint and Go 1.20 build (see Local Testing Before Push)
- Check for any modified files:
git status - Ensure all new files are added:
git add . - Verify builds cleanly:
go build -o cert . - Test the binary:
./cert version - If adding new commands, update
expectedCommandsincmd/root_test.go
- Ensure Go 1.20+ is installed
- Run
go mod tidyfor dependencies - Check
go.modfor module name (certwiz)
- Test with different terminal widths
- Check
$TERMenvironment variable - Test with
--plainand withCI=1(ASCII borders and symbols)
- Use
--fullflag for complete details - Use
--chainto see trust path - Check SANs match hostname
- CA certificate generation (
cert ca) - Certificate signing requests (
cert csr) - Certificate signing with CA (
cert sign), including EC CA keys and DER CA certs - TLS version testing (
cert tls) with concurrent probing and a sequential retry - SHA-256 and SHA-1 fingerprints in terminal and JSON output
- Certificate bundle and stdin inspection (
cert inspect fullchain.pem --chain,cert inspect -) - Bundle-aware conversion (
cert convert) - JSON output format (all commands support
--json) - Network timeout configuration (
--timeoutis a Go duration flag, e.g.2s,500ms) - Proxy/tunnel support (
--connectflag) - Signature algorithm selection (
--sig-algflag for inspect) - Automatic update command (
cert update) - Certificate chain verification (
--caflag for verify) - Private key matching (
--key) and expiry threshold (--expires-in) for verify - Secure key permissions (0600 on Unix systems)
- Error stream contract: human errors on stderr, JSON on stdout, exit 1, printed once
- Plain output mode and YAML config file
These are planned but not yet implemented:
- ECDSA key generation (generate, ca, and csr are RSA-only)
- PKCS#12/PFX support
- ACME/Let's Encrypt integration
- Certificate transparency logs
- Web UI dashboard
- OCSP stapling verification
- Certificate pinning validation
- Automatic certificate renewal
- Integration with HashiCorp Vault
- Kubernetes cert-manager integration
- Bump
versionincmd/root.go - In CHANGELOG.md, move the
[Unreleased]entries into a## [X.Y.Z] - YYYY-MM-DDsection and add[X.Y.Z]: https://github.com/trahma/certwiz/releases/tag/vX.Y.Zto the link list at the bottom - Run the Local Testing Before Push checks
- Commit, then
git tag -a vX.Y.Z -m "vX.Y.Z" git push origin main && git push origin vX.Y.Z- The tag push triggers
.github/workflows/goreleaser.yml, which publishes archives namedcert-<os>-<arch>(x86_64,i386,arm64,armv7;.tar.gz,.zipon Windows; each contains a binary namedcert) pluschecksums.txt - Watch it:
gh run list --limit 3, thengh run watch <id> --exit-status; confirm withgh release view vX.Y.Z
make build-all cross-compiles into dist/ for local checks but is not part of the release.
- Binary is named
cert, notcertwiz - Check PATH includes install directory
- Terminal may not support colors
- Try
FORCE_COLOR=1 cert inspect ...
- Width comes from
terminalWidth()(stdout); when stdout is not a terminal it is 80 valueWidthderives the wrap width from the panel margin, padding, and longest key
- Targets that look like paths (leading
./~, absolute, Windows drive, certificate extension, or a separator after a non-host segment) are treated as files; seelooksLikeFilePathincmd/inspect.go. Everything else is tried as a host or URL.
- Local video/promo generation experiments; git-ignored, not part of the project
- Use
certcommand in scripts; prefer--jsonand parse withjq - Exit codes: 0 (success), 1 (error);
cert verify --expires-in 30dis designed for cron and pipelines - Errors are on stderr, so
2>/dev/nullhides them and--jsonkeeps stdout parseable
FROM golang:alpine
WORKDIR /app
COPY . .
RUN go build -o cert .
ENTRYPOINT ["./cert"]When contributing:
- Binary must be named
cert - Help text should show
certexamples - Maintain backward compatibility
- Update relevant documentation and CHANGELOG.md
- Follow existing code style
- GitHub Issues: Bug reports and features
- Documentation: /docs directory
- Examples: /docs/examples.md
This file helps AI assistants understand the project structure and conventions. Keep it updated as the project evolves.