Personal API tokens and OpenAPI discovery for Go apps — zero third-party dependencies.
Designed to be dropped into the same apps as go-ai, go-draw, go-wiki and go-login: one token scheme, one scope model, and one place to serve the document that describes your API.
- One token scheme, per-app prefix —
fw_…for folioworth,75h_…for 75hard. A token found in a log says which system issued it. - Hash-only storage — the plaintext is shown once and is unrecoverable. A leaked database yields hashes, not credentials.
- Two scopes that people actually read —
readandwrite, enforced on the HTTP method so a route added later cannot forget to check. - Bring your own storage and router — Postgres or SQLite, Echo or chi, UUID or integer keys. The library owns the cryptography and the rules, nothing else.
- OpenAPI discovery — serve your document under one convention, and hand a new token its own working
curlexample.
go get github.com/anchoo2kewl/go-api
<prefix>_<64 hex characters>
32 bytes from crypto/rand. Stored as the SHA-256 of the whole string, plus a
non-secret prefix — the marker and eight hex characters — so a token can be
listed and revoked without the secret ever being written down.
Plain SHA-256 is correct here and would be wrong for a password: the input is 32 bytes of CSPRNG output, so there is no dictionary to attack and nothing for a work factor to slow down, while every request has to verify one.
scheme := api.NewScheme("75h_")
cred, err := scheme.Generate()
// cred.Plaintext — return this once, then forget it
// cred.Hash — store this
// cred.Prefix — store this, safe to display
discovery := api.NewDiscovery("https://75hard.biswas.me", cred.Plaintext, api.Scopes{api.ScopeRead})
// discovery.SpecURL — the OpenAPI document
// discovery.Example — a curl command that works as printedImplement Store over your own database. The type parameter is whatever you
identify users by.
type tokenStore struct{ db *sql.DB }
func (s tokenStore) Lookup(ctx context.Context, hash string) (api.Record, int64, error) {
var (
userID int64
scopes string
active bool
expires sql.NullTime
)
err := s.db.QueryRowContext(ctx,
`SELECT user_id, scopes, revoked_at IS NULL, expires_at
FROM api_tokens WHERE token_hash = ?`, hash).
Scan(&userID, &scopes, &active, &expires)
if errors.Is(err, sql.ErrNoRows) {
return api.Record{}, 0, api.ErrNotFound
}
rec := api.Record{Scopes: api.ParseScopes(scopes), Active: active}
if expires.Valid {
rec.ExpiresAt = &expires.Time
}
return rec, userID, err
}Then, in middleware:
auth := api.NewAuthenticator[int64](scheme, tokenStore{db})
userID, record, err := auth.AuthenticateRequest(r)
if err != nil {
http.Error(w, api.PublicMessage(err), api.StatusFor(err))
return
}AuthenticateRequest returns ErrNotFound when the header carries something
this scheme did not issue — a session JWT, say — so an app can fall through to
its other authentication path.
Add a Touch method to your store and it is called after a successful
authentication, to record last use. It runs after the decision, and a failure
is reported rather than failing the request.
| Request | read |
write |
|---|---|---|
| GET, HEAD, OPTIONS | yes | yes |
| POST, PUT, PATCH, DELETE | no | yes |
Write implies read. An empty or unrecognised scope set normalises to read:
the safe reading of an ambiguous request is the one that cannot change data.
ErrScopeDenied maps to 403, every other failure to 401 — the
difference being whether presenting a different credential of the same kind
could help. StatusFor and PublicMessage do that mapping, and collapse every
authentication failure to one message so a prober cannot learn which token
strings were once real.
A token is only half of what someone needs. The other half is a description of what the API offers — and a machine-readable one means a person can hand both to an LLM or a client generator and have it work out the calls unaided.
//go:embed openapi.yaml
var specBytes []byte
var spec = api.MustSpec(specBytes, api.SpecYAML)
mux.Handle(api.SpecPath, spec.Handler()) // /api/openapi.yamlThe handler does ETag revalidation, HEAD, and permissive CORS, because the
document is public and tooling fetches it from other origins. It is
unauthenticated by design: requiring a credential to discover how to present a
credential is a loop.
NewSpec refuses a document carrying neither an openapi: nor a swagger:
version field, so an app that embeds the wrong file — or embeds nothing because
a build tag excluded it — fails at startup instead of serving a confident 200
of garbage. Both spellings are accepted: OpenAPI 3 uses the first, and a
generator like swaggo still emits the second.
token.go Scheme — generation, hashing, prefixes
scopes.go Scopes — the read/write model and method enforcement
record.go Record — stored metadata, and the verification order
auth.go Store, Authenticator, and the HTTP error mapping
spec.go Spec and Discovery — serving OpenAPI, and onboarding a new token
MIT