mirror of
https://github.com/hanzoai/iam.git
synced 2026-11-19 18:37:16 +00:00
keys/principal takes an optional ?org=. store.HolderIn admits it exactly where a member's key filed there would act: the holder's home or an org-wide membership their standing acts in (Acts). Anything else is key_org_not_open. The answer names the org the key is filed in as keyOrg, so a resource server still addresses the key's own policy there. Without ?org= nothing changes. For hanzo-inc/cloud#429: cloud billed a key's own org whatever X-Org-Id the caller sent. Testing: go test ./... passes (45 packages). New store tests: selecting a membership acts there as member with the key's name and limit; the key's own org or none is unchanged; another tenant, an unknown org and admin are refused; a member's key may select its holder's home; removing the membership ends the selection on the next call; a plain member of a platform org (hanzo) is refused. Risk: medium. It widens where a secret key acts, but only into orgs its holder already acts in with a token, and the check is the same Acts and MembershipIn the key resolver uses. Reads one membership per selected request; no caching here. How to revert: revert this commit; ?org= is then ignored again. Co-authored-by: Claude Opus 5.5 <[email protected]>
640 lines
28 KiB
Go
640 lines
28 KiB
Go
// Copyright 2026 Hanzo AI, Inc.
|
|
// SPDX-License-Identifier: MIT OR Apache-2.0
|
|
|
|
package store
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/hanzoai/account"
|
|
policy "github.com/hanzoai/authz"
|
|
"github.com/hanzoai/orm"
|
|
|
|
"github.com/hanzoai/iam/pkg/schema"
|
|
)
|
|
|
|
// API-key → principal resolution: the ONE way an opaque Hanzo API key is turned
|
|
// into the user it authenticates, for the get-user?accessKey path cloud's identity
|
|
// boundary calls. Every shape FAILS CLOSED — an unknown, empty, or unrecognized-shape
|
|
// key resolves to orm.ErrNotFound, never a fallback or wrong user, so a bad key can
|
|
// never inherit another principal's identity.
|
|
//
|
|
// There are exactly TWO key shapes, and only the SECRET one authenticates a reader:
|
|
//
|
|
// - sk- the confidential half of a schema.Key credential (Key.AccessSecret) —
|
|
// resolve the key row, then its owning user (same-tenant pinned). This is
|
|
// the ONE durable full-access bearer credential; keys.Mint issues it.
|
|
// - pk- the PUBLISHABLE half (Key.AccessKey). Refused here, always.
|
|
//
|
|
// A pk- is deliberately NOT a resolving case: it is WRITE-ONLY and MUST NEVER become
|
|
// a principal. A pk- is public — it ships in client JS — so turning it into a read
|
|
// identity is the browser-key catastrophe. It is refused on EVERY caller of this
|
|
// function (get-user?accessKey AND the registry token path), so a public key
|
|
// authenticates no read anywhere. Its ONLY resolution is org-only, at the ingest
|
|
// endpoint (keys.resolve → /v1/iam/resolve-key), and only for a publishable key.
|
|
//
|
|
// Any other string is not a key. It carries no shape this estate mints, so it cannot
|
|
// be told apart from a value that was never issued at all, and it resolves to nobody.
|
|
|
|
// ── why a key did not resolve ────────────────────────────────────────────────
|
|
//
|
|
// FAILING CLOSED AND FAILING SILENTLY ARE DIFFERENT THINGS, and this file used to do
|
|
// both. Every non-resolution collapsed into a bare orm.ErrNotFound, which the key
|
|
// endpoint rendered as "the entity does not exist" — one sentence for causes that call
|
|
// for opposite actions from the holder. A user whose key was REVOKED went looking for
|
|
// a deleted organization instead of minting a new key, and a tenant admin's forgery
|
|
// attempt (the same-tenant pin below) was indistinguishable from a typo.
|
|
//
|
|
// The reason is therefore a VALUE, carried beside the error rather than baked into
|
|
// its text. It changes no decision here — every branch still refuses — so refusing
|
|
// and explaining stay orthogonal.
|
|
type KeyFailure string
|
|
|
|
const (
|
|
// KeyWrongDoor: a REAL credential presented at the endpoint that does not answer
|
|
// for it — a pk- at the SECRET endpoint, or a non-pk- at the publishable one. The
|
|
// holder has a working key; they used the wrong half. Reserved for exactly that,
|
|
// so the advice it carries ("use your secret sk- key") is always true when it is
|
|
// given.
|
|
KeyWrongDoor KeyFailure = "key_wrong_door"
|
|
// KeyUnknown: no live credential answers to this value. Never minted, already
|
|
// revoked, or carrying a prefix this estate does not issue — the holder cannot
|
|
// tell those apart and does not need to, because the cure is the same one: mint a
|
|
// new key. Nothing about their org is wrong. This is the honest answer for any
|
|
// string that is not a live sk-, which is why the default case lands here.
|
|
KeyUnknown KeyFailure = "key_unknown"
|
|
// KeyForeignUser: an sk- row resolved, but it names a user in ANOTHER tenant.
|
|
// The same-tenant pin (userOwningKey) refused it. This is a SECURITY EVENT, not
|
|
// a user error, and it must never again look like one.
|
|
KeyForeignUser KeyFailure = "key_foreign_user"
|
|
// KeyDanglingUser: an sk- row resolved and named a same-tenant user that does
|
|
// not exist. A data-integrity fault in the key table, not the holder's doing.
|
|
KeyDanglingUser KeyFailure = "key_dangling_user"
|
|
// KeyNotPublishable: a real key addressed by its pk- half whose scope is not
|
|
// publish. The publishable endpoint refuses it precisely because it is a secret.
|
|
KeyNotPublishable KeyFailure = "key_not_publishable"
|
|
// KeyExpired: the row exists and is the right scope, but its lifetime has run
|
|
// out. Both resolvers report it, because both ask the same question (see dead).
|
|
KeyExpired KeyFailure = "key_expired"
|
|
// KeyDisabled: the row exists and has not run out, but its lifecycle flag says
|
|
// it is turned off. Told apart from KeyExpired because the cures differ — an
|
|
// expired key is re-minted, a disabled one is switched back on — and told apart
|
|
// from KeyUnknown because the credential is real and its holder is not guessing.
|
|
KeyDisabled KeyFailure = "key_disabled"
|
|
// KeyRevoked: the row exists and was revoked (schema.KeyStateRevoked). Told
|
|
// apart from KeyDisabled because a revoked key is final: the cure is a new key.
|
|
KeyRevoked KeyFailure = "key_revoked"
|
|
// KeySuperAdmin: an sk- row names an account in the admin org, where every
|
|
// SuperAdmin lives. No durable key speaks for one (SuperAdminKey); the holder
|
|
// signs in for a short-lived token instead.
|
|
KeySuperAdmin KeyFailure = "key_superadmin"
|
|
// KeyHolderDisabled: the key is live but the account it speaks for is
|
|
// suspended (IsForbidden) or deleted. A key is its holder's credential, so it
|
|
// works exactly as long as its holder may sign in: suspending a person — by hand
|
|
// or by SCIM — ends every key they hold at once.
|
|
KeyHolderDisabled KeyFailure = "key_holder_disabled"
|
|
// KeyNotTenant: the key acts in an org the platform runs (a brand, a
|
|
// directory), and its holder is a plain member there. Such an org is no tenant
|
|
// of its plain members — a customer who landed in a brand org shares none of its
|
|
// data — so no key of theirs acts in it. Its admins' keys and its machines' do.
|
|
KeyNotTenant KeyFailure = "key_not_tenant"
|
|
// KeyOrgNotOpen: the key resolved, and the caller asked it to act in ANOTHER
|
|
// org (HolderIn) that its holder may not act in — no membership there, a plain
|
|
// member of an org the platform runs, a reserved org, or a directory. The key
|
|
// itself is fine; only that selection is refused.
|
|
KeyOrgNotOpen KeyFailure = "key_org_not_open"
|
|
)
|
|
|
|
// KeyError is an orm.ErrNotFound that ALSO says why. It Unwraps to orm.ErrNotFound
|
|
// so every existing `errors.Is(err, orm.ErrNotFound)` caller keeps working untouched
|
|
// and unaware: the reason is strictly additive, and a caller that does not care
|
|
// about it is not made to.
|
|
type KeyError struct{ Reason KeyFailure }
|
|
|
|
func (e *KeyError) Error() string { return "key not resolved: " + string(e.Reason) }
|
|
func (e *KeyError) Unwrap() error { return orm.ErrNotFound }
|
|
|
|
// Reason extracts the failure reason from a key-resolution error. A plain
|
|
// orm.ErrNotFound (from a path that predates this type) reads as KeyUnknown, and
|
|
// anything else — a real store fault — reads as "" so a caller never reports an
|
|
// infrastructure failure as a bad credential.
|
|
func Reason(err error) KeyFailure {
|
|
var ke *KeyError
|
|
if errors.As(err, &ke) {
|
|
return ke.Reason
|
|
}
|
|
if errors.Is(err, orm.ErrNotFound) {
|
|
return KeyUnknown
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func notFound(r KeyFailure) error { return &KeyError{Reason: r} }
|
|
|
|
// UserByAccessKey resolves an opaque API key to the user it authenticates, or a
|
|
// KeyError (an orm.ErrNotFound naming its cause) for anything else. It never returns
|
|
// a wrong user: only a live sk- resolves, through an exact-match lookup pinned to the
|
|
// key row's own tenant; an sk- whose row names no resolvable user fails closed rather
|
|
// than guessing one; and a public pk- resolves to nobody at all.
|
|
//
|
|
// The two shapes are refused for DIFFERENT reasons, and the difference is the whole
|
|
// value of the answer. A pk- is a real credential at the wrong endpoint (KeyWrongDoor —
|
|
// "use your secret key"). Anything else answers to no live credential at all
|
|
// (KeyUnknown — "mint a new one"), whether it was revoked, never issued, or carries
|
|
// some prefix this estate does not mint. There is no third case, because there is no
|
|
// third shape: a value that is not a pk- and not a live sk- is simply not a key, and
|
|
// special-casing any particular non-key spelling would invent the third family back.
|
|
//
|
|
// A deleted key reads as KeyUnknown. A present row stops answering too: an sk- that
|
|
// has been revoked (KeyRevoked), has run out (KeyExpired) or been switched off
|
|
// (KeyDisabled) resolves to nobody just the same, because the one place a secret
|
|
// becomes a key asks that question for every resolver (see keyBySecret).
|
|
func UserByAccessKey(ctx context.Context, db orm.DB, key string) (*schema.User, error) {
|
|
u, _, err := UserAndScopeByAccessKey(ctx, db, key)
|
|
return u, err
|
|
}
|
|
|
|
// UserAndScopeByAccessKey is UserByAccessKey plus the key row's own Scope — what
|
|
// that CREDENTIAL may reach, as distinct from what its holder may.
|
|
//
|
|
// One lookup, because it is one row: the resolver already reads the Key to find
|
|
// the user, and dropping the scope on the way out is what made a per-key limit
|
|
// unenforceable — a resource server could learn WHO a key speaks for and never
|
|
// how much of that authority the key carries. A second call would be a second
|
|
// read of the same row and a second chance for the two answers to disagree.
|
|
//
|
|
// Scope is "" for a key that names no limit, which is every key minted before
|
|
// limits existed and means unrestricted.
|
|
//
|
|
// It answers only for a key that acts in its holder's own org. A member's key acts
|
|
// in the org it was minted in, which a user alone cannot say, so a caller that
|
|
// reads only the user (the registry) refuses it rather than let it act at home;
|
|
// HolderByAccessKey is the resolver that carries the org.
|
|
func UserAndScopeByAccessKey(ctx context.Context, db orm.DB, key string) (*schema.User, string, error) {
|
|
h, err := HolderByAccessKey(ctx, db, key)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
if h.Org != h.User.Owner {
|
|
return nil, "", notFound(KeyForeignUser)
|
|
}
|
|
return h.User, h.Scope, nil
|
|
}
|
|
|
|
// Holder is what a secret key speaks for: the user it authenticates, the org it
|
|
// acts in, and the limit it carries.
|
|
//
|
|
// Org is the KEY's org. For a key minted in its holder's home org the two are the
|
|
// same. A member's key is minted in an org the holder belongs to by membership, and
|
|
// it speaks for them in that org and no other, so a resource server scopes the
|
|
// request to Org, never to the user's home.
|
|
type Holder struct {
|
|
User *schema.User
|
|
Org string
|
|
Scope string
|
|
// Role is the holder's standing in Org: the membership role for a member's key,
|
|
// the home role otherwise. It is what decides whether Org's pool pays.
|
|
Role string
|
|
// Key is the key row's Name within Org: which credential the request arrived
|
|
// on, so a resource server can apply that key's own policy.
|
|
Key string
|
|
// KeyOrg is the org the key row is filed in, set only when HolderIn moved the
|
|
// holder to another Org. Key names a row there, not in Org, so a resource
|
|
// server addressing the key's own policy reads KeyOrg/Key.
|
|
KeyOrg string
|
|
}
|
|
|
|
// HolderIn is h acting in org instead of the org its key is filed in — what a
|
|
// caller asks for when it selects an org per request (hanzo-inc/cloud#429) rather
|
|
// than minting a key in each org. It admits exactly the orgs a member's key filed
|
|
// there would act in (holderOwningKey's rule): the holder's home, or an org-wide
|
|
// membership, either one their standing there acts in (Acts). Anything else is
|
|
// KeyOrgNotOpen. It reads the membership on every call, so removing the member
|
|
// ends the selection on the next request, as it ends a member's key.
|
|
//
|
|
// The key's own limit (Scope) and its name travel unchanged: a selection moves
|
|
// where the holder acts and who pays, never what the credential may reach.
|
|
func HolderIn(ctx context.Context, db orm.DB, h Holder, org string) (Holder, error) {
|
|
org = strings.TrimSpace(org)
|
|
if org == "" || org == h.Org {
|
|
return h, nil
|
|
}
|
|
u := h.User
|
|
if u == nil {
|
|
return Holder{}, notFound(KeyOrgNotOpen)
|
|
}
|
|
role := ""
|
|
if org == u.Owner {
|
|
role = HomeRole(u)
|
|
} else {
|
|
if !memberKeyOrgs(u.Owner, org) {
|
|
return Holder{}, notFound(KeyOrgNotOpen)
|
|
}
|
|
m, err := MembershipIn(ctx, db, u.Owner+"/"+u.Name, org, "", "")
|
|
if err != nil {
|
|
return Holder{}, err
|
|
}
|
|
if m == nil {
|
|
return Holder{}, notFound(KeyOrgNotOpen)
|
|
}
|
|
role = m.Role
|
|
}
|
|
if !Acts(org, u, role) {
|
|
return Holder{}, notFound(KeyOrgNotOpen)
|
|
}
|
|
keyOrg := h.KeyOrg
|
|
if keyOrg == "" {
|
|
keyOrg = h.Org
|
|
}
|
|
return Holder{User: u, Org: org, Scope: h.Scope, Role: role, Key: h.Key, KeyOrg: keyOrg}, nil
|
|
}
|
|
|
|
// HolderByAccessKey is UserAndScopeByAccessKey with the org the key acts in and
|
|
// the holder's standing there — the whole answer a key resolution owes a resource
|
|
// server, from one read of the key row.
|
|
func HolderByAccessKey(ctx context.Context, db orm.DB, key string) (Holder, error) {
|
|
key = strings.TrimSpace(key)
|
|
switch {
|
|
case strings.HasPrefix(key, "sk-"):
|
|
return holderOwningKey(ctx, db, key)
|
|
case strings.HasPrefix(key, "pk-"):
|
|
// WRITE-ONLY and never a principal (see the package note above). Fail closed,
|
|
// and say so as the wrong endpoint: this holder has a working key, just not here.
|
|
return Holder{}, notFound(KeyWrongDoor)
|
|
default:
|
|
// Not a shape this estate issues, so no live credential can answer to it.
|
|
// Fail closed, and tell the holder the one thing that helps: mint a new key.
|
|
return Holder{}, notFound(KeyUnknown)
|
|
}
|
|
}
|
|
|
|
// holderOwningKey resolves the schema.Key a secret belongs to, then the user that
|
|
// key speaks for — CONSTRAINED to the key row's own org. A key that names no user
|
|
// (an org- or app-scoped credential) fails closed with orm.ErrNotFound: this path
|
|
// attributes a key to a USER principal or to none. Only the confidential sk- half
|
|
// reaches here; a public pk- never resolves to a principal (HolderByAccessKey
|
|
// refuses it before this point).
|
|
//
|
|
// The same-tenant pin is the F1 forgery gate. Key.User and AccessSecret are
|
|
// attacker-controlled at write time and keys CRUD authorizes only (Key.Owner,
|
|
// Key.Name), so a tenant admin could plant a Key in its OWN org whose User names
|
|
// "admin/z" or a victim tenant's user and, presenting the known secret, resolve it
|
|
// to that identity. A key therefore speaks only for a user who BELONGS to the key's
|
|
// org: its home org, or an org-wide membership, asked here on every resolution so
|
|
// that removing the member ends the key. A reserved org is never on either side of
|
|
// a membership key, so no such key can reach a SuperAdmin or be a platform key.
|
|
// Who may WRITE a member's key is the keys write gate's question (MemberKey).
|
|
//
|
|
// No secret key speaks for an account in the admin org, however the row came to
|
|
// exist (SuperAdminKey). Asked first, of the key as written, because the answer
|
|
// needs no read: the org a key names is the org of the row it would resolve to.
|
|
func holderOwningKey(ctx context.Context, db orm.DB, secret string) (Holder, error) {
|
|
k, err := keyBySecret(ctx, db, secret)
|
|
if err != nil {
|
|
return Holder{}, err
|
|
}
|
|
owner, name := keyUserRef(k)
|
|
if owner == "" || name == "" {
|
|
return Holder{}, notFound(KeyForeignUser)
|
|
}
|
|
if SuperAdminKey(k) {
|
|
return Holder{}, notFound(KeySuperAdmin)
|
|
}
|
|
role := ""
|
|
if owner != k.Owner {
|
|
// A member's key. With no membership behind it, the row reads exactly as the
|
|
// forgery this pin exists to refuse, whether it was planted or its holder was
|
|
// removed since, so it is refused as one: a key has no history to tell them
|
|
// apart by, and the security reading is the one that must never be missed.
|
|
if !memberKeyOrgs(owner, k.Owner) {
|
|
return Holder{}, notFound(KeyForeignUser)
|
|
}
|
|
m, err := MembershipIn(ctx, db, owner+"/"+name, k.Owner, "", "")
|
|
if err != nil {
|
|
return Holder{}, err
|
|
}
|
|
if m == nil {
|
|
return Holder{}, notFound(KeyForeignUser)
|
|
}
|
|
role = m.Role
|
|
}
|
|
u, err := GetUserByName(ctx, db, owner, name)
|
|
if err != nil {
|
|
return Holder{}, err
|
|
}
|
|
if u == nil {
|
|
return Holder{}, notFound(KeyDanglingUser)
|
|
}
|
|
if u.IsForbidden || u.IsDeleted {
|
|
return Holder{}, notFound(KeyHolderDisabled)
|
|
}
|
|
if role == "" {
|
|
role = HomeRole(u)
|
|
}
|
|
if !Acts(k.Owner, u, role) {
|
|
return Holder{}, notFound(KeyNotTenant)
|
|
}
|
|
return Holder{User: u, Org: k.Owner, Scope: k.Scope, Role: role, Key: k.Name}, nil
|
|
}
|
|
|
|
// Acts reports whether u, whose standing in org is role, acts in it: what a key
|
|
// filed there or a token delegated there may do for u. A brand's directory is no
|
|
// one's tenant, so nothing acts in it. An org the platform runs is a tenant only
|
|
// of those who run it (owner, admin) and of its own machines, so a plain member —
|
|
// a person, or a machine of another org — acts in none of it; a SuperAdmin acts in every one, as authz's Sudo does (no secret
|
|
// key names one: SuperAdminKey). Every other org is its members' tenant. It is authz's
|
|
// Claims.Tenancy rule asked of one row, and the one rule the key resolver, the
|
|
// key mint and the delegation read, so a credential IAM issues is one that acts.
|
|
func Acts(org string, u *schema.User, role string) bool {
|
|
switch {
|
|
case u == nil || policy.IsDirectory(org):
|
|
return false
|
|
case policy.IsPlatformOrg(org):
|
|
return (u.Machine() && u.Owner == org) || u.SuperAdmin() || role == RoleOwner || role == RoleAdmin
|
|
}
|
|
return true
|
|
}
|
|
|
|
// SuperAdminKey reports whether a secret key filed as k would speak for an account
|
|
// in the admin org. That is where every SuperAdmin lives (schema.User.SuperAdmin),
|
|
// and the refusal covers the platform machines beside them too: a durable
|
|
// credential anchored in the platform's own org is one nobody sees expire, and a
|
|
// platform machine proves itself as an application for a short-lived token
|
|
// instead. It is therefore the ORG, not the SuperAdmin predicate — a key names an
|
|
// account that may not exist yet, and the refusal must not wait for one to.
|
|
//
|
|
// The holder is read as holderOwningKey reads it — a bare name within k.Owner,
|
|
// "<owner>/<name>" as written. Resolving that name to its row folds the case of
|
|
// the name and never changes its org, so the answer needs no read. A key that
|
|
// names no account speaks for nobody.
|
|
func SuperAdminKey(k *schema.Key) bool {
|
|
owner, name := keyUserRef(k)
|
|
return name != "" && owner == policy.AdminOrg
|
|
}
|
|
|
|
// MemberKey reports whether user may hold a key minted in org other than their
|
|
// home: neither org is reserved, and an org-wide membership admits them there.
|
|
// It is the write-side twin of holderOwningKey's pin, so a row the resolver would
|
|
// refuse is never written.
|
|
func MemberKey(ctx context.Context, db orm.DB, user, org string) (bool, error) {
|
|
home, _, ok := strings.Cut(user, "/")
|
|
if !ok || home == "" || org == "" || home == org || !memberKeyOrgs(home, org) {
|
|
return false, nil
|
|
}
|
|
m, err := MembershipIn(ctx, db, user, org, "", "")
|
|
return m != nil, err
|
|
}
|
|
|
|
// memberKeyOrgs reports whether a key minted in org may speak for someone homed in
|
|
// home. Neither may be reserved, so no such key reaches a SuperAdmin or is a
|
|
// platform key. And org may not be the signup org: there every person pays from a
|
|
// wallet addressed by username in that org, so a member homed elsewhere has no
|
|
// wallet there that is theirs, and a same-named account's would be the one charged.
|
|
func memberKeyOrgs(home, org string) bool {
|
|
return !policy.IsReservedOrg(home) && !policy.IsReservedOrg(org) && account.Org(org) != account.Org(account.SignupOrg)
|
|
}
|
|
|
|
// forgetMemberKeys deletes every key a member holds in org. A membership is a
|
|
// member key's whole authority, and a key that outlived its removal would come back
|
|
// to life the moment the same person was added again.
|
|
func forgetMemberKeys(ctx context.Context, db orm.DB, user, org string) error {
|
|
ks, err := orm.TypedQuery[schema.Key](db).Filter("Owner=", org).Filter("User=", user).GetAll(ctx)
|
|
if err != nil && !errors.Is(err, orm.ErrNotFound) {
|
|
return err
|
|
}
|
|
for _, k := range ks {
|
|
if err := k.DeleteCtx(ctx); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// keyBySecret finds the key a presented secret belongs to WITHOUT the row ever
|
|
// having to hold that secret: the digest of what was presented is the lookup
|
|
// value, and one indexed read answers it.
|
|
//
|
|
// The fallback is a migration, not a second way of doing this. Rows minted
|
|
// before the digest existed carry the secret in plaintext, and the estate cannot
|
|
// re-mint every deployed credential at once — so a digest miss tries the legacy
|
|
// column, and a hit there DRAINS it: the digest is written, the plaintext is
|
|
// cleared, and that row never takes this path again. The fallback therefore
|
|
// shrinks to nothing on its own and can be deleted when the plaintext count
|
|
// reaches zero, which is a query anyone can run.
|
|
//
|
|
// A drain that fails is not an authentication failure. The caller presented a
|
|
// real credential; the write is housekeeping, and refusing them because
|
|
// housekeeping failed would turn a storage problem into an outage.
|
|
//
|
|
// FOUND IS NOT HONORED. A row that has run out or been switched off still answers
|
|
// to its secret, and it must still resolve to nobody — so the liveness question is
|
|
// asked HERE, at the one place a presented secret becomes a key, and no resolver
|
|
// can forget to ask it.
|
|
func keyBySecret(ctx context.Context, db orm.DB, secret string) (*schema.Key, error) {
|
|
digest := schema.DigestSecret(secret)
|
|
if digest == "" {
|
|
return nil, notFound(KeyUnknown)
|
|
}
|
|
k, err := only(ctx, db, "AccessSecretDigest=", digest)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if k == nil {
|
|
if k, err = only(ctx, db, "AccessSecret=", secret); err != nil {
|
|
return nil, err
|
|
}
|
|
if k == nil {
|
|
return nil, notFound(KeyUnknown)
|
|
}
|
|
k.AccessSecretDigest = digest
|
|
k.AccessSecret = ""
|
|
_ = k.UpdateCtx(ctx)
|
|
}
|
|
now := time.Now().UTC()
|
|
if r := dead(k, now); r != "" {
|
|
return nil, notFound(r)
|
|
}
|
|
sight(ctx, db, k, now)
|
|
return k, nil
|
|
}
|
|
|
|
// sightEvery is how stale a key's last sighting may grow before a resolution
|
|
// writes a new one, so a busy key costs one write a minute and not one a request.
|
|
const sightEvery = time.Minute
|
|
|
|
// sight records that k was just presented, at most once per sightEvery. A failed
|
|
// write is dropped: the key resolved, and when it was last seen is a report, never
|
|
// a reason to refuse it.
|
|
//
|
|
// Its id is the key's under its own prefix: the store keys every kind by id, so a
|
|
// sighting spelled like its key would be written over the key row itself.
|
|
func sight(ctx context.Context, db orm.DB, k *schema.Key, now time.Time) {
|
|
id := "sighting/" + k.Owner + "/" + k.Name
|
|
if s, err := orm.Get[schema.Sighting](db, id); err == nil {
|
|
if t, err := time.Parse(time.RFC3339, s.Time); err == nil && now.Sub(t) < sightEvery {
|
|
return
|
|
}
|
|
} else if !errors.Is(err, orm.ErrNotFound) {
|
|
return
|
|
}
|
|
s := orm.New[schema.Sighting](db)
|
|
s.SetId(id)
|
|
s.Owner, s.Name, s.Time = k.Owner, k.Name, now.Format(time.RFC3339)
|
|
_ = s.PutCtx(ctx)
|
|
}
|
|
|
|
// Sightings is when each key filed in owner was last seen, by key name. An empty
|
|
// owner reads every org's.
|
|
func Sightings(ctx context.Context, db orm.DB, owner string) (map[string]string, error) {
|
|
q := orm.TypedQuery[schema.Sighting](db)
|
|
if owner != "" {
|
|
q = q.Filter("Owner=", owner)
|
|
}
|
|
rows, err := q.GetAll(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make(map[string]string, len(rows))
|
|
for _, s := range rows {
|
|
out[s.Owner+"/"+s.Name] = s.Time
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// only reads the ONE key whose field equals val: nil when none does, and an error
|
|
// rather than an arbitrary pick when more than one does. A secret two rows answer
|
|
// to names no single credential, and guessing which one would let a planted
|
|
// duplicate speak for the row it was copied from.
|
|
func only(ctx context.Context, db orm.DB, field, val string) (*schema.Key, error) {
|
|
ks, err := orm.TypedQuery[schema.Key](db).Filter(field, val).GetAll(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
switch len(ks) {
|
|
case 0:
|
|
return nil, nil
|
|
case 1:
|
|
return ks[0], nil
|
|
default:
|
|
return nil, fmt.Errorf("store: %d keys share one secret — ambiguous credential", len(ks))
|
|
}
|
|
}
|
|
|
|
// keyUserRef extracts the (owner, name) of the user a schema.Key belongs to. The
|
|
// User field is the "owner/name" identity used everywhere a user is referenced
|
|
// (Token.User, Membership.User); a bare username without a "/" is taken within the
|
|
// key's own tenant (Key.Owner). An empty User yields ("",""). The owner it returns
|
|
// is NOT trusted: holderOwningKey admits an owner other than the key row's own only
|
|
// through a live membership in the key's org, so any other "/"-qualified reference
|
|
// to a foreign owner resolves to nobody.
|
|
func keyUserRef(k *schema.Key) (owner, name string) {
|
|
if o, n, ok := strings.Cut(k.User, "/"); ok && o != "" && n != "" {
|
|
return o, n
|
|
}
|
|
if k.User != "" {
|
|
return k.Owner, k.User
|
|
}
|
|
return "", ""
|
|
}
|
|
|
|
// KeyBySecret resolves a server key by its confidential sk- secret — the ONE way
|
|
// the durable 'act' grant behind as() is authenticated. It returns the KEY ROW
|
|
// (its Owner and its grants), never a user: the org key acts FOR members of its
|
|
// tenant, it is not itself one, so this is not the get-user resolver and does not
|
|
// pin to a User field.
|
|
//
|
|
// It carries NO lookup of its own: keyBySecret is how a presented secret becomes a
|
|
// key everywhere, so this resolver and the get-user resolver cannot disagree about
|
|
// which rows answer. That is not tidiness — a private query here matched the plaintext
|
|
// column the minter stopped writing, so this resolver saw only the rows minted before
|
|
// digests and none of the ones minted since.
|
|
//
|
|
// Fail closed on every non-resolution — an empty value, a non-sk- shape, or a
|
|
// secret that answers to no honored row resolves to (nil, nil). WHICH refusal it
|
|
// was is keyBySecret's word and is dropped here: this resolver asks whether a key
|
|
// speaks, not what to tell a holder, and its caller has nobody to explain to.
|
|
func KeyBySecret(ctx context.Context, db orm.DB, secret string) (*schema.Key, error) {
|
|
secret = strings.TrimSpace(secret)
|
|
if !strings.HasPrefix(secret, "sk-") {
|
|
return nil, nil
|
|
}
|
|
k, err := keyBySecret(ctx, db, secret)
|
|
if errors.Is(err, orm.ErrNotFound) {
|
|
return nil, nil
|
|
}
|
|
return k, err
|
|
}
|
|
|
|
// PublishableKeyByAccessKey resolves a WRITE-ONLY publishable pk- to the schema.Key it
|
|
// belongs to, or orm.ErrNotFound — the ORG-ONLY dual of UserByAccessKey, for the ingest
|
|
// resolver (/v1/iam/keys/org). It NEVER touches or returns a
|
|
// user: a publishable key speaks for just its org, never a principal, which is why the
|
|
// pk- path lives here and not in UserByAccessKey.
|
|
//
|
|
// Fail-closed on every non-resolution, so this resolver can only ever speak for a live
|
|
// key that was explicitly minted as a browser key: a value that is not a pk-, an
|
|
// unknown key, a non-publishable (secret) key even when addressed by its OWN pk- half
|
|
// (Scope != KeyScopePublish), or a revoked, expired or disabled key (dead) all yield
|
|
// orm.ErrNotFound.
|
|
func PublishableKeyByAccessKey(ctx context.Context, db orm.DB, key string, now time.Time) (*schema.Key, error) {
|
|
key = strings.TrimSpace(key)
|
|
if !strings.HasPrefix(key, "pk-") {
|
|
return nil, notFound(KeyWrongDoor)
|
|
}
|
|
k, err := orm.TypedQuery[schema.Key](db).Filter("AccessKey=", key).First()
|
|
if err == orm.ErrNotFound {
|
|
return nil, notFound(KeyUnknown)
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// Two different refusals, told apart. "Not publishable" means the holder used a
|
|
// secret key's public half at the ingest endpoint and should present its pk-;
|
|
// "expired" means the right key simply ran out and must be re-minted. Collapsing
|
|
// them sent the second holder hunting for a configuration error they did not have.
|
|
// The CLASS, not the whole scope: a limited publishable key carries its reach
|
|
// in the same field ("publish,model:zen5"), and comparing the whole string
|
|
// would refuse it here — the browser key would resolve to no org and every
|
|
// beacon it sends would be dropped.
|
|
if schema.ClassOf(k.Scope) != schema.KeyScopePublish {
|
|
return nil, notFound(KeyNotPublishable)
|
|
}
|
|
if r := dead(k, now); r != "" {
|
|
return nil, notFound(r)
|
|
}
|
|
sight(ctx, db, k, now)
|
|
return k, nil
|
|
}
|
|
|
|
// dead says WHY a key is no longer honored, or "" while it still is. Two ways a
|
|
// present row stops answering, one predicate, so every resolver refuses the same rows
|
|
// for the same stated reason:
|
|
//
|
|
// - State is the lifecycle flag the minter writes ("Active", or "test" for a
|
|
// test-env credential; empty on rows minted before the flag existed). Any
|
|
// other value is a key somebody switched off.
|
|
// - ExpireTime is when it stops being honored, empty meaning never. An
|
|
// unparseable stamp reads as expired — fail secure, never honor a key whose
|
|
// lifetime cannot be read.
|
|
func dead(k *schema.Key, now time.Time) KeyFailure {
|
|
switch k.State {
|
|
case "", "Active", "test":
|
|
case schema.KeyStateRevoked:
|
|
return KeyRevoked
|
|
default:
|
|
return KeyDisabled
|
|
}
|
|
if k.ExpireTime == "" {
|
|
return ""
|
|
}
|
|
exp, err := time.Parse(time.RFC3339, k.ExpireTime)
|
|
if err != nil || !now.Before(exp) {
|
|
return KeyExpired
|
|
}
|
|
return ""
|
|
}
|