mirror of
https://github.com/hanzoai/iam.git
synced 2026-11-19 18:37:16 +00:00
The resolver records a Sighting when it resolves a key, at most once a minute, in a row of its own so a use never rewrites a key row someone is editing. The key list fills usedTime from the sightings.
871 lines
34 KiB
Go
871 lines
34 KiB
Go
// Copyright 2026 Hanzo AI, Inc.
|
|
// SPDX-License-Identifier: MIT OR Apache-2.0
|
|
|
|
package keys
|
|
|
|
import (
|
|
"context"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
policy "github.com/hanzoai/authz"
|
|
"github.com/hanzoai/orm"
|
|
ormdb "github.com/hanzoai/orm/db"
|
|
|
|
"github.com/hanzoai/iam/internal/principal"
|
|
"github.com/hanzoai/iam/pkg/schema"
|
|
"github.com/hanzoai/iam/pkg/store"
|
|
)
|
|
|
|
func memDB(t *testing.T) orm.DB {
|
|
t.Helper()
|
|
_ = schema.Kinds()
|
|
dir := t.TempDir()
|
|
db, err := orm.OpenSQLite(&ormdb.SQLiteDBConfig{
|
|
Path: filepath.Join(dir, "keys.db"),
|
|
Config: ormdb.SQLiteConfig{BusyTimeout: 5000, JournalMode: "WAL"},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("open sqlite: %v", err)
|
|
}
|
|
t.Cleanup(func() { _ = db.Close() })
|
|
return db
|
|
}
|
|
|
|
// F1 write-side gate: keys.create and keys.update must REJECT a Key whose User field
|
|
// names a different owner than the key — the row that would let get-user?accessKey
|
|
// forge a cross-tenant / SuperAdmin identity can never be persisted. A same-owner or
|
|
// bare User is accepted.
|
|
func TestKeys_RejectCrossTenantUserOnWrite(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
c := create(db)
|
|
|
|
// Cross-tenant qualified User → rejected (attacker in "a" pointing at admin/z).
|
|
if _, err := c(ctx, &schema.Key{Owner: "a", Name: "forge", User: "admin/z"}); err == nil {
|
|
t.Fatal("create accepted a cross-tenant User reference (forgery row)")
|
|
}
|
|
|
|
// Same-owner qualified User → accepted.
|
|
ok, err := c(ctx, &schema.Key{Owner: "a", Name: "own", User: "a/alice"})
|
|
if err != nil || ok == nil {
|
|
t.Fatalf("create rejected a same-owner User: %v", err)
|
|
}
|
|
// Bare username → accepted (resolves within the key's own owner).
|
|
if _, err := c(ctx, &schema.Key{Owner: "a", Name: "bare", User: "bob"}); err != nil {
|
|
t.Fatalf("create rejected a bare username: %v", err)
|
|
}
|
|
|
|
// update must enforce it too: flipping an existing key's User cross-tenant fails.
|
|
u := update(db)
|
|
if _, err := u(ctx, &schema.Key{Owner: "a", Name: "own", User: "victimorg/ceo"}); err == nil {
|
|
t.Fatal("update accepted a cross-tenant User reference (forgery row)")
|
|
}
|
|
// A same-owner update still works.
|
|
if _, err := u(ctx, &schema.Key{Owner: "a", Name: "own", User: "a/carol"}); err != nil {
|
|
t.Fatalf("update rejected a same-owner User: %v", err)
|
|
}
|
|
}
|
|
|
|
// A publishable key (Scope=publish) mints a pk- publishable half ONLY — never a
|
|
// confidential sk- secret — so it can carry no full-access material. A default key
|
|
// still mints BOTH halves (its sk- is the reader-authenticating credential).
|
|
func TestKeys_PublishableMintsNoSecret(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
c := create(db)
|
|
|
|
pub, err := c(ctx, &schema.Key{Owner: "hanzo", Name: "site", Scope: schema.KeyScopePublish})
|
|
if err != nil {
|
|
t.Fatalf("create publish key: %v", err)
|
|
}
|
|
if !strings.HasPrefix(pub.AccessKey, "pk-") {
|
|
t.Fatalf("publish key AccessKey = %q, want a pk-", pub.AccessKey)
|
|
}
|
|
if pub.AccessSecret != "" {
|
|
t.Fatalf("publish key minted a secret %q, want none (write-only)", pub.AccessSecret)
|
|
}
|
|
|
|
def, err := c(ctx, &schema.Key{Owner: "hanzo", Name: "server"})
|
|
if err != nil {
|
|
t.Fatalf("create default key: %v", err)
|
|
}
|
|
if !strings.HasPrefix(def.AccessKey, "pk-") || !strings.HasPrefix(def.AccessSecret, "sk-") {
|
|
t.Fatalf("default key halves = %q/%q, want pk-/sk-", def.AccessKey, def.AccessSecret)
|
|
}
|
|
}
|
|
|
|
// A publishable key is write-only even if the caller SUPPLIES a secret: create and
|
|
// update both force AccessSecret empty, so a browser key can never carry a confidential
|
|
// half for its whole lifecycle.
|
|
func TestKeys_PublishableForcesSecretEmpty(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
// Caller tries to smuggle a secret onto a publish key at create.
|
|
pub, err := create(db)(ctx, &schema.Key{
|
|
Owner: "hanzo", Name: "site", Scope: schema.KeyScopePublish,
|
|
AccessKey: "pk-live-CHOSEN", AccessSecret: "sk-live-SMUGGLED",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
if pub.AccessSecret != "" {
|
|
t.Fatalf("create let a publish key keep a supplied secret %q", pub.AccessSecret)
|
|
}
|
|
|
|
// And again at update — the invariant holds across the key's lifecycle.
|
|
upd, err := update(db)(ctx, &schema.Key{
|
|
Owner: "hanzo", Name: "site", Scope: schema.KeyScopePublish,
|
|
AccessSecret: "sk-live-SMUGGLED2",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("update: %v", err)
|
|
}
|
|
if upd.AccessSecret != "" {
|
|
t.Fatalf("update let a publish key gain a secret %q", upd.AccessSecret)
|
|
}
|
|
}
|
|
|
|
// The round-trip that did not exist, and whose absence let a dead credential ship:
|
|
// a key minted by mint-user-keys MUST resolve back to the user it was minted for.
|
|
//
|
|
// It did not. mintUserKeysHandler stamped the sk- onto schema.User.AccessKey, while
|
|
// store.UserByAccessKey's sk- branch reads schema.Key.AccessSecret — the write and
|
|
// the read never met, so every minted key authenticated nobody.
|
|
func TestMintUserKey_ResolvesBackToItsUser(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
secret, err := MintUserKey(ctx, db, "acme", "ada", "")
|
|
if err != nil {
|
|
t.Fatalf("MintUserKey: %v", err)
|
|
}
|
|
if !strings.HasPrefix(secret, "sk-") {
|
|
t.Fatalf("minted secret = %q, want an sk- confidential half", secret[:3])
|
|
}
|
|
|
|
// The row the resolver reads must exist, name its user, and answer to the
|
|
// secret's DIGEST — the row itself never holds the secret.
|
|
k, err := orm.TypedQuery[schema.Key](db).Filter("AccessSecretDigest=", schema.DigestSecret(secret)).First()
|
|
if err != nil || k == nil {
|
|
t.Fatalf("no schema.Key row resolves the minted secret (err=%v) — this is the bug", err)
|
|
}
|
|
if k.User != "ada" || k.Owner != "acme" {
|
|
t.Fatalf("key resolves to %s/%s, want acme/ada", k.Owner, k.User)
|
|
}
|
|
if !strings.HasPrefix(k.AccessKey, "pk-") {
|
|
t.Fatalf("publishable half = %q, want pk-", k.AccessKey)
|
|
}
|
|
if k.Scope == schema.KeyScopePublish {
|
|
t.Fatal("a user's authenticating key must NOT be publish-scoped")
|
|
}
|
|
}
|
|
|
|
// Re-minting REPLACES the credential rather than leaving a second live secret: a
|
|
// user holds one key, so revoking it revokes them.
|
|
func TestMintUserKey_RemintReplacesRatherThanAccumulates(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
first, err := MintUserKey(ctx, db, "acme", "ada", "")
|
|
if err != nil {
|
|
t.Fatalf("first mint: %v", err)
|
|
}
|
|
second, err := MintUserKey(ctx, db, "acme", "ada", "")
|
|
if err != nil {
|
|
t.Fatalf("re-mint: %v", err)
|
|
}
|
|
if first == second {
|
|
t.Fatal("re-mint returned the same secret; it must rotate")
|
|
}
|
|
if old, _ := orm.TypedQuery[schema.Key](db).Filter("AccessSecretDigest=", schema.DigestSecret(first)).First(); old != nil {
|
|
t.Fatal("the superseded secret still resolves — a revoked key would stay live")
|
|
}
|
|
cur, err := orm.TypedQuery[schema.Key](db).Filter("AccessSecretDigest=", schema.DigestSecret(second)).First()
|
|
if err != nil || cur == nil {
|
|
t.Fatalf("the current secret does not resolve: %v", err)
|
|
}
|
|
// The row holds the digest and NOT the secret: a leak of this table reveals
|
|
// nothing anyone can present.
|
|
if cur.AccessSecret != "" {
|
|
t.Fatalf("the minted row stored the secret in plaintext: %q", cur.AccessSecret)
|
|
}
|
|
}
|
|
|
|
// Revoke is a statement about the END state: after it, the user holds nothing, and
|
|
// revoking again is still success (a caller may always assert "holds no credential").
|
|
func TestRevokeUserKey_EndStateAndIdempotent(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
secret, err := MintUserKey(ctx, db, "acme", "ada", "")
|
|
if err != nil {
|
|
t.Fatalf("mint: %v", err)
|
|
}
|
|
if err := RevokeUserKey(ctx, db, "acme", "ada", ""); err != nil {
|
|
t.Fatalf("revoke: %v", err)
|
|
}
|
|
if k, _ := orm.TypedQuery[schema.Key](db).Filter("AccessSecretDigest=", schema.DigestSecret(secret)).First(); k != nil {
|
|
t.Fatal("secret still resolves after revoke")
|
|
}
|
|
if err := RevokeUserKey(ctx, db, "acme", "ada", ""); err != nil {
|
|
t.Fatalf("revoke on an already-revoked user must succeed, got %v", err)
|
|
}
|
|
}
|
|
|
|
// A caller must not be able to CHOOSE a key's credential. The sk- half resolves its
|
|
// owning user by exact match (store.userOwningKey), so a body that carries one lets
|
|
// the sender pick a secret it already knows and then present it as that principal.
|
|
// This is a forgery primitive the moment the secret is stored as a digest.
|
|
func TestKeys_CallerCannotChooseTheCredential(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
k, err := create(db)(ctx, &schema.Key{
|
|
Owner: "acme", Name: "planted",
|
|
AccessKey: "pk-live-chosen-by-caller",
|
|
AccessSecret: "sk-live-chosen-by-caller",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
if k.AccessSecret == "sk-live-chosen-by-caller" {
|
|
t.Fatal("caller-supplied AccessSecret was persisted — a chosen credential is a forgery")
|
|
}
|
|
if k.AccessKey == "pk-live-chosen-by-caller" {
|
|
t.Fatal("caller-supplied AccessKey was persisted")
|
|
}
|
|
if !strings.HasPrefix(k.AccessSecret, "sk-") || !strings.HasPrefix(k.AccessKey, "pk-") {
|
|
t.Fatalf("both halves must be minted; got key=%q secret-prefix=%q", k.AccessKey, k.AccessSecret[:3])
|
|
}
|
|
}
|
|
|
|
// Scope is the ACCESS CLASS and is fixed at mint. An update that could flip a secret
|
|
// key to publish scope would blank its secret and make its pk- half org-resolvable at
|
|
// the ingest endpoint — a privilege change wearing the clothes of a profile edit.
|
|
func TestKeys_UpdateCannotReScopeOrRotate(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
made, err := create(db)(ctx, &schema.Key{Owner: "acme", Name: "svc"})
|
|
if err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
secret, access := made.AccessSecret, made.AccessKey
|
|
|
|
// Flipping the class is refused outright: it would blank the secret and make
|
|
// the pk- half org-resolvable at the ingest endpoint.
|
|
if _, err := update(db)(ctx, &schema.Key{Owner: "acme", Name: "svc", Scope: schema.KeyScopePublish}); err == nil {
|
|
t.Fatal("update re-scoped a secret key to publish")
|
|
}
|
|
|
|
got, err := update(db)(ctx, &schema.Key{
|
|
Owner: "acme", Name: "svc",
|
|
DisplayName: "renamed",
|
|
AccessSecret: "sk-live-attacker",
|
|
AccessKey: "pk-live-attacker",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("update: %v", err)
|
|
}
|
|
if got.Scope == schema.KeyScopePublish {
|
|
t.Fatal("update re-scoped a secret key to publish — that blanks the secret and makes the pk- half org-resolvable at the ingest endpoint")
|
|
}
|
|
// Assert on the STORED row, not the response: the response is masked (an edit is
|
|
// not a mint), so reading the secret back out of it would only ever prove the mask.
|
|
stored, err := orm.Get[schema.Key](db, "acme/svc")
|
|
if err != nil {
|
|
t.Fatalf("read back: %v", err)
|
|
}
|
|
if stored.AccessSecretDigest != schema.DigestSecret(secret) || stored.AccessKey != access {
|
|
t.Fatal("update rotated the credential to caller-supplied values")
|
|
}
|
|
if stored.AccessSecret != "" {
|
|
t.Fatalf("the stored row holds a plaintext secret: %q", stored.AccessSecret)
|
|
}
|
|
if got.AccessSecret != "" {
|
|
t.Fatalf("update echoed the confidential secret %q — the secret is revealed once, by create", got.AccessSecret)
|
|
}
|
|
if got.DisplayName != "renamed" {
|
|
t.Fatalf("update failed to apply a legitimately mutable field: %q", got.DisplayName)
|
|
}
|
|
}
|
|
|
|
// The gap that made a publishable key unmintable: there was NO path anywhere that
|
|
// produced one for a user. IAM owned the model (schema.KeyScopePublish), the resolver
|
|
// (store.PublishableKeyByAccessKey) and the ingest endpoint (compat resolve-key), and
|
|
// nothing minted the credential they were written for — so every surface configured
|
|
// its own thing. Type is a field on the ONE mint, and this is the proof it works.
|
|
func TestMintUserKey_PublishableTypeMintsAPublicKeyAndNoSecret(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
got, err := MintUserKey(ctx, db, "acme", "ada", schema.KeyScopePublish)
|
|
if err != nil {
|
|
t.Fatalf("MintUserKey(publish): %v", err)
|
|
}
|
|
if !strings.HasPrefix(got, "pk-") {
|
|
t.Fatalf("publishable mint returned %q, want the pk- half — a browser key is the value you ship", got)
|
|
}
|
|
k, err := orm.Get[schema.Key](db, "acme/"+PublishKeyName)
|
|
if err != nil {
|
|
t.Fatalf("no publishable key row: %v", err)
|
|
}
|
|
if k.Scope != schema.KeyScopePublish {
|
|
t.Fatalf("row scope = %q, want %q — the resolver refuses anything else", k.Scope, schema.KeyScopePublish)
|
|
}
|
|
if k.AccessSecret != "" {
|
|
t.Fatalf("a publishable key stored a confidential secret %q — it must have no secret half at all", k.AccessSecret)
|
|
}
|
|
if k.AccessKey != got {
|
|
t.Fatalf("returned %q but stored %q; the value handed out must be the value that resolves", got, k.AccessKey)
|
|
}
|
|
if k.User != "ada" || k.Owner != "acme" {
|
|
t.Fatalf("publishable key filed under %s/%s, want acme/ada", k.Owner, k.User)
|
|
}
|
|
}
|
|
|
|
// The two scopes are two rows, so a user holds both at once and rotating one does not
|
|
// touch the other. One row would make "rotate the key in my browser bundle" also sign
|
|
// the holder out of their own API.
|
|
func TestMintUserKey_ScopesAreIndependentCredentials(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
secret, err := MintUserKey(ctx, db, "acme", "ada", "")
|
|
if err != nil {
|
|
t.Fatalf("mint secret: %v", err)
|
|
}
|
|
pub, err := MintUserKey(ctx, db, "acme", "ada", schema.KeyScopePublish)
|
|
if err != nil {
|
|
t.Fatalf("mint publishable: %v", err)
|
|
}
|
|
if k, _ := orm.TypedQuery[schema.Key](db).Filter("AccessSecretDigest=", schema.DigestSecret(secret)).First(); k == nil {
|
|
t.Fatal("minting the publishable key destroyed the secret key")
|
|
}
|
|
|
|
// Rotating the publishable key leaves the secret key alone…
|
|
pub2, err := MintUserKey(ctx, db, "acme", "ada", schema.KeyScopePublish)
|
|
if err != nil {
|
|
t.Fatalf("re-mint publishable: %v", err)
|
|
}
|
|
if pub2 == pub {
|
|
t.Fatal("re-minting the publishable key did not rotate it")
|
|
}
|
|
if k, _ := orm.TypedQuery[schema.Key](db).Filter("AccessSecretDigest=", schema.DigestSecret(secret)).First(); k == nil {
|
|
t.Fatal("rotating the publishable key revoked the secret key")
|
|
}
|
|
// …and revoking it likewise.
|
|
if err := RevokeUserKey(ctx, db, "acme", "ada", schema.KeyScopePublish); err != nil {
|
|
t.Fatalf("revoke publishable: %v", err)
|
|
}
|
|
if _, err := orm.Get[schema.Key](db, "acme/"+PublishKeyName); err == nil {
|
|
t.Fatal("publishable key survived its own revoke")
|
|
}
|
|
if k, _ := orm.TypedQuery[schema.Key](db).Filter("AccessSecretDigest=", schema.DigestSecret(secret)).First(); k == nil {
|
|
t.Fatal("revoking the publishable key revoked the secret key — the whole reason they are separate rows")
|
|
}
|
|
}
|
|
|
|
// A key LIST must never carry a confidential secret. Before schema.Key.Mask the list
|
|
// handed every reader every sk- in the org verbatim, which meant read AUTHORIZATION
|
|
// was standing in for redaction — and so widening who may see their own keys could
|
|
// not be done safely. The publishable half survives the mask on purpose: it is the
|
|
// value the holder needs, and it authenticates nobody.
|
|
func TestKeys_ReadsMaskTheSecretAndKeepThePublishableHalf(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
made, err := create(db)(ctx, &schema.Key{Owner: "acme", Name: "svc", User: "ada"})
|
|
if err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
if made.AccessSecret == "" {
|
|
t.Fatal("create must reveal the secret ONCE, or a minted key is unusable")
|
|
}
|
|
|
|
listed, err := list(db)(as("acme"), &ListRequest{Owner: "acme"})
|
|
if err != nil || len(listed.Keys) != 1 {
|
|
t.Fatalf("list: %v (%d keys)", err, len(listed.Keys))
|
|
}
|
|
if listed.Keys[0].AccessSecret != "" {
|
|
t.Fatalf("list disclosed the confidential secret %q", listed.Keys[0].AccessSecret)
|
|
}
|
|
if listed.Keys[0].AccessKey != made.AccessKey {
|
|
t.Fatalf("list blanked the publishable half (%q); the holder needs it", listed.Keys[0].AccessKey)
|
|
}
|
|
|
|
one, err := get(db)(ctx, &Ref{Owner: "acme", Name: "svc"})
|
|
if err != nil {
|
|
t.Fatalf("get: %v", err)
|
|
}
|
|
if one.AccessSecret != "" {
|
|
t.Fatalf("get disclosed the confidential secret %q", one.AccessSecret)
|
|
}
|
|
// And the STORED secret is untouched — the mask is a projection, not a deletion.
|
|
stored, err := orm.Get[schema.Key](db, "acme/svc")
|
|
if err != nil || stored.AccessSecretDigest != made.AccessSecretDigest {
|
|
t.Fatal("masking a read mutated the stored credential")
|
|
}
|
|
}
|
|
|
|
// Two members of one org hold two secret keys. When the row was named by scope
|
|
// alone, (owner, scope) identified a session-equivalent credential and an org had
|
|
// exactly ONE secret key row, so the second member to mint overwrote the first in
|
|
// place — B authenticates, A mints, and B's next call is not recognized. This pins
|
|
// that each member's key stands on its own.
|
|
func TestMintUserKey_oneMemberDoesNotRevokeAnother(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
ada, err := MintUserKey(ctx, db, "acme", "ada", "")
|
|
if err != nil {
|
|
t.Fatalf("mint ada: %v", err)
|
|
}
|
|
bob, err := MintUserKey(ctx, db, "acme", "bob", "")
|
|
if err != nil {
|
|
t.Fatalf("mint bob: %v", err)
|
|
}
|
|
if ada == bob {
|
|
t.Fatal("two members were handed the same secret")
|
|
}
|
|
for who, secret := range map[string]string{"ada": ada, "bob": bob} {
|
|
k, err := orm.TypedQuery[schema.Key](db).Filter("AccessSecretDigest=", schema.DigestSecret(secret)).First()
|
|
if err != nil || k == nil {
|
|
t.Fatalf("%s's secret stopped resolving once the other member minted", who)
|
|
}
|
|
if k.User != who {
|
|
t.Fatalf("%s's secret resolves to %q", who, k.User)
|
|
}
|
|
}
|
|
|
|
// …and one member's revoke reaches only their own row.
|
|
if err := RevokeUserKey(ctx, db, "acme", "ada", ""); err != nil {
|
|
t.Fatalf("revoke ada: %v", err)
|
|
}
|
|
if k, _ := orm.TypedQuery[schema.Key](db).Filter("AccessSecretDigest=", schema.DigestSecret(bob)).First(); k == nil {
|
|
t.Fatal("revoking ada's key revoked bob's")
|
|
}
|
|
}
|
|
|
|
// The org-wide secret row an older build left behind still authenticates, as
|
|
// whichever member minted last — a live credential nobody can see in their own
|
|
// listing or revoke from their own account. Minting retires it.
|
|
func TestMintUserKey_retiresTheSharedRow(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
shared := orm.New[schema.Key](db)
|
|
shared.SetId("acme/" + UserKeyName)
|
|
shared.Owner, shared.Name = "acme", UserKeyName
|
|
shared.Type, shared.User = "User", "ada"
|
|
shared.AccessKey, shared.AccessSecret = Mint("pk", ""), Mint("sk", "")
|
|
shared.State = "Active"
|
|
if err := shared.CreateCtx(ctx); err != nil {
|
|
t.Fatalf("seed shared row: %v", err)
|
|
}
|
|
stale := shared.AccessSecret
|
|
|
|
if _, err := MintUserKey(ctx, db, "acme", "bob", ""); err != nil {
|
|
t.Fatalf("mint: %v", err)
|
|
}
|
|
if k, _ := orm.TypedQuery[schema.Key](db).Filter("AccessSecretDigest=", schema.DigestSecret(stale)).First(); k != nil {
|
|
t.Fatal("the org-wide secret still resolves after a mint")
|
|
}
|
|
}
|
|
|
|
// A LIMIT MUST NOT CHANGE WHAT KIND OF KEY YOU GET.
|
|
//
|
|
// Scope carries two facts in one field: the access CLASS ("publish") and the
|
|
// REACH a credential is limited to ("model:zen5"). They were compared as one
|
|
// string, so asking for a limited browser key minted a SECRET key instead —
|
|
// under the secret row's name, with a confidential sk- half, returned to a
|
|
// caller who asked for something safe to put in a browser bundle. Measured in
|
|
// production: the limit was echoed back by the mint and stored nowhere.
|
|
func TestALimitDoesNotChangeTheKeyClass(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
plain, err := MintUserKey(ctx, db, "hanzo", "alice", schema.KeyScopePublish)
|
|
if err != nil {
|
|
t.Fatalf("publishable: %v", err)
|
|
}
|
|
limited, err := MintUserKey(ctx, db, "hanzo", "alice", schema.KeyScopePublish+",model:zen5,project:acme")
|
|
if err != nil {
|
|
t.Fatalf("limited publishable: %v", err)
|
|
}
|
|
|
|
// BOTH are publishable: the pk- half is what the holder presents.
|
|
for name, got := range map[string]string{"unlimited": plain, "limited": limited} {
|
|
if !strings.HasPrefix(got, "pk-") {
|
|
t.Fatalf("%s publishable key presented %q — a limit must not turn a browser key into a secret one", name, got[:3])
|
|
}
|
|
}
|
|
|
|
// ONE row, because a limit is not a second key class. Re-minting replaces
|
|
// the credential in place, exactly as it does without a limit.
|
|
// ONE row, addressed by the name the publishable class gives it — a limit
|
|
// must not spill into a second row under the SECRET key's name, which is
|
|
// exactly what comparing the whole scope did.
|
|
k, err := orm.TypedQuery[schema.Key](db).Filter("Id=", "hanzo/"+PublishKeyName).First()
|
|
if err != nil || k == nil {
|
|
t.Fatalf("the limited key must live in the publishable row: %v", err)
|
|
}
|
|
if secret, _ := orm.TypedQuery[schema.Key](db).Filter("Id=", "hanzo/alice-"+UserKeyName).First(); secret != nil {
|
|
t.Fatalf("a limited publishable mint wrote a SECRET row too: %+v", secret.Name)
|
|
}
|
|
// The reach is STORED, which is what makes it enforceable downstream.
|
|
if k.Scope != schema.KeyScopePublish+",model:zen5,project:acme" {
|
|
t.Fatalf("scope = %q, want the class AND the reach", k.Scope)
|
|
}
|
|
// And the key stays write-only: a publishable row never holds a secret.
|
|
if k.AccessSecret != "" {
|
|
t.Fatal("a limited publishable key must still carry NO confidential half")
|
|
}
|
|
if schema.ClassOf(k.Scope) != schema.KeyScopePublish {
|
|
t.Fatalf("ClassOf(%q) must read the class", k.Scope)
|
|
}
|
|
}
|
|
|
|
// seedUser puts the user a minted key names on the store, so a resolve that
|
|
// reaches the same-tenant pin has someone to land on.
|
|
func seedUser(t *testing.T, db orm.DB, owner, name string) {
|
|
t.Helper()
|
|
u := orm.New[schema.User](db)
|
|
u.SetId(owner + "/" + name)
|
|
u.Owner, u.Name = owner, name
|
|
if err := u.CreateCtx(context.Background()); err != nil {
|
|
t.Fatalf("seed %s/%s: %v", owner, name, err)
|
|
}
|
|
}
|
|
|
|
// A MINT HANDS OUT A CREDENTIAL THAT WORKS, and the only proof of that is the
|
|
// resolver the estate authenticates through — store.UserAndScopeByAccessKey, what
|
|
// /v1/iam/keys/principal answers with. Every other assertion here reads the row
|
|
// directly, which is a weaker question: a row can hold the right digest and still
|
|
// resolve to nobody.
|
|
//
|
|
// Each case below is one way the mint used to answer a live sk- that authenticated
|
|
// nobody. All three end at the same place, so they are one test.
|
|
func TestMintUserKey_TheMintedSecretAuthenticates(t *testing.T) {
|
|
resolves := func(t *testing.T, db orm.DB, secret string) {
|
|
t.Helper()
|
|
u, _, err := store.UserAndScopeByAccessKey(context.Background(), db, secret)
|
|
if err != nil {
|
|
t.Fatalf("the minted key does not authenticate: %s", store.Reason(err))
|
|
}
|
|
if u.Owner != "acme" || u.Name != "ada" {
|
|
t.Fatalf("it authenticated %s/%s, want acme/ada", u.Owner, u.Name)
|
|
}
|
|
}
|
|
|
|
// A key minted for the first time.
|
|
t.Run("first mint", func(t *testing.T) {
|
|
db := memDB(t)
|
|
seedUser(t, db, "acme", "ada")
|
|
secret, err := MintUserKey(context.Background(), db, "acme", "ada", "")
|
|
if err != nil {
|
|
t.Fatalf("mint: %v", err)
|
|
}
|
|
resolves(t, db, secret)
|
|
})
|
|
|
|
// A key minted after the previous one was revoked. Revocation leaves the store
|
|
// holding a deleted row under the SAME deterministic id, and a write that landed
|
|
// on it reported success while the row stayed deleted — so the second key was
|
|
// stored where every reader filters it out, and re-minting never helped.
|
|
t.Run("after a revoke", func(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
seedUser(t, db, "acme", "ada")
|
|
if _, err := MintUserKey(ctx, db, "acme", "ada", ""); err != nil {
|
|
t.Fatalf("first mint: %v", err)
|
|
}
|
|
if err := RevokeUserKey(ctx, db, "acme", "ada", ""); err != nil {
|
|
t.Fatalf("revoke: %v", err)
|
|
}
|
|
secret, err := MintUserKey(ctx, db, "acme", "ada", "")
|
|
if err != nil {
|
|
t.Fatalf("mint after revoke: %v", err)
|
|
}
|
|
resolves(t, db, secret)
|
|
})
|
|
|
|
// A key minted onto a row that had run out or been switched off. The mint used
|
|
// to carry only the new credential onto such a row and leave State/ExpireTime
|
|
// as they were, so the resolver kept refusing what had just been handed over.
|
|
for _, dead := range []struct {
|
|
name string
|
|
set func(*schema.Key)
|
|
}{
|
|
{"onto an expired row", func(k *schema.Key) {
|
|
k.ExpireTime = time.Now().UTC().Add(-time.Hour).Format(time.RFC3339)
|
|
}},
|
|
{"onto a disabled row", func(k *schema.Key) { k.State = "Inactive" }},
|
|
} {
|
|
t.Run(dead.name, func(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
seedUser(t, db, "acme", "ada")
|
|
if _, err := MintUserKey(ctx, db, "acme", "ada", ""); err != nil {
|
|
t.Fatalf("first mint: %v", err)
|
|
}
|
|
k, err := orm.Get[schema.Key](db, id("acme", NameFor("ada", "")))
|
|
if err != nil {
|
|
t.Fatalf("read the row: %v", err)
|
|
}
|
|
dead.set(k)
|
|
if err := k.UpdateCtx(ctx); err != nil {
|
|
t.Fatalf("age the row: %v", err)
|
|
}
|
|
secret, err := MintUserKey(ctx, db, "acme", "ada", "")
|
|
if err != nil {
|
|
t.Fatalf("re-mint: %v", err)
|
|
}
|
|
resolves(t, db, secret)
|
|
})
|
|
}
|
|
}
|
|
|
|
// The same rule on the CRUD surface: a name that was deleted can be used again,
|
|
// and the key issued under it is retrievable and authenticates. Revocation is
|
|
// deletion, so without this an organization could spend a key name once.
|
|
func TestKeys_ANameCanBeUsedAgainAfterDelete(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
seedUser(t, db, "acme", "ada")
|
|
|
|
c, d, g := create(db), del(db), get(db)
|
|
if _, err := c(ctx, &schema.Key{Owner: "acme", Name: "server", User: "ada"}); err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
if _, err := d(ctx, &Ref{Owner: "acme", Name: "server"}); err != nil {
|
|
t.Fatalf("delete: %v", err)
|
|
}
|
|
again, err := c(ctx, &schema.Key{Owner: "acme", Name: "server", User: "ada"})
|
|
if err != nil {
|
|
t.Fatalf("create under a name that was deleted: %v", err)
|
|
}
|
|
if _, err := g(ctx, &Ref{Owner: "acme", Name: "server"}); err != nil {
|
|
t.Fatalf("the re-created key is not retrievable: %v", err)
|
|
}
|
|
if _, _, err := store.UserAndScopeByAccessKey(ctx, db, again.AccessSecret); err != nil {
|
|
t.Fatalf("the re-created key does not authenticate: %s", store.Reason(err))
|
|
}
|
|
}
|
|
|
|
// A member's key — minted in an org the holder belongs to by membership — is
|
|
// written only by a caller that mints on a person's behalf, and only for a member.
|
|
// A tenant admin cannot write one: it would be a credential that speaks as any of
|
|
// the org's members.
|
|
func TestKeys_MemberKeyIsWrittenOnlyForAMemberByAMinter(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
if _, err := store.EnsureMembership(ctx, db, "agency/josh", "client", store.RoleAdmin); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
minter := principal.Bind(ctx, &principal.Principal{App: &policy.App{Name: "hanzo-console", Owner: "admin"}})
|
|
tenantAdmin := principal.Bind(ctx, &policy.Principal{Org: "client", User: "boss", Admin: true})
|
|
c := create(db)
|
|
|
|
if _, err := c(minter, &schema.Key{Owner: "client", Name: "josh-secret", User: "agency/josh"}); err != nil {
|
|
t.Fatalf("the minter could not write a member's key: %v", err)
|
|
}
|
|
if _, err := c(minter, &schema.Key{Owner: "client", Name: "stranger", User: "elsewhere/stray"}); err == nil {
|
|
t.Fatal("the minter wrote a key for someone who is not a member of the key's org")
|
|
}
|
|
if _, err := c(tenantAdmin, &schema.Key{Owner: "client", Name: "planted", User: "agency/josh"}); err == nil {
|
|
t.Fatal("a tenant admin wrote a key that speaks as a member from another org")
|
|
}
|
|
if _, err := c(ctx, &schema.Key{Owner: "client", Name: "anon", User: "agency/josh"}); err == nil {
|
|
t.Fatal("a write with no principal produced a member's key")
|
|
}
|
|
|
|
// Once written, a member's key names its member for good: neither the tenant
|
|
// admin nor the minter can repoint the secret the member holds.
|
|
u := update(db)
|
|
for _, who := range []context.Context{tenantAdmin, minter} {
|
|
for _, to := range []string{"victim", "client/victim", ""} {
|
|
if _, err := u(who, &schema.Key{Owner: "client", Name: "josh-secret", User: to}); err == nil {
|
|
t.Fatalf("a member's key was repointed at %q", to)
|
|
}
|
|
}
|
|
}
|
|
if _, err := u(minter, &schema.Key{Owner: "client", Name: "josh-secret", User: "agency/josh", DisplayName: "renamed"}); err != nil {
|
|
t.Fatalf("an edit that keeps the member was refused: %v", err)
|
|
}
|
|
}
|
|
|
|
// A key records the head of the credential its holder presents, so a listing can
|
|
// say which string a row is: the sk- of a secret key, the pk- of a publishable one.
|
|
func TestKeys_PrefixIsTheHeadOfThePresentedCredential(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
|
|
made, err := create(db)(ctx, &schema.Key{Owner: "acme", Name: "svc"})
|
|
if err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
if made.Prefix == "" || !strings.HasPrefix(made.AccessSecret, made.Prefix) || !strings.HasPrefix(made.Prefix, "sk-") {
|
|
t.Fatalf("prefix %q is not the head of the secret", made.Prefix)
|
|
}
|
|
if len(made.Prefix) >= len(made.AccessSecret)/2 {
|
|
t.Fatalf("prefix %q carries too much of the secret", made.Prefix)
|
|
}
|
|
stored, err := orm.Get[schema.Key](db, "acme/svc")
|
|
if err != nil {
|
|
t.Fatalf("read back: %v", err)
|
|
}
|
|
if stored.Prefix != made.Prefix {
|
|
t.Fatalf("the stored prefix %q differs from the minted %q", stored.Prefix, made.Prefix)
|
|
}
|
|
|
|
pub, err := create(db)(ctx, &schema.Key{Owner: "acme", Name: "web", Scope: schema.KeyScopePublish})
|
|
if err != nil {
|
|
t.Fatalf("create publishable: %v", err)
|
|
}
|
|
if !strings.HasPrefix(pub.AccessKey, pub.Prefix) || !strings.HasPrefix(pub.Prefix, "pk-") {
|
|
t.Fatalf("publishable prefix %q is not the head of %q", pub.Prefix, pub.AccessKey)
|
|
}
|
|
|
|
secret, err := MintUserKey(ctx, db, "acme", "ada", "")
|
|
if err != nil {
|
|
t.Fatalf("MintUserKey: %v", err)
|
|
}
|
|
row, err := orm.Get[schema.Key](db, id("acme", NameFor("ada", "")))
|
|
if err != nil {
|
|
t.Fatalf("read the minted row: %v", err)
|
|
}
|
|
if row.Prefix == "" || !strings.HasPrefix(secret, row.Prefix) {
|
|
t.Fatalf("MintUserKey recorded prefix %q for %q", row.Prefix, secret[:3])
|
|
}
|
|
}
|
|
|
|
// A key's reach is policy: an update changes it and the credential keeps
|
|
// working, unchanged.
|
|
func TestKeys_UpdateChangesTheReachAndKeepsTheSecret(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
seedUser(t, db, "acme", "ada")
|
|
|
|
made, err := create(db)(ctx, &schema.Key{Owner: "acme", Name: "svc", User: "ada", State: "Active"})
|
|
if err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
if _, err := update(db)(ctx, &schema.Key{Owner: "acme", Name: "svc", User: "ada", State: "Active", Scope: "model:zen5"}); err != nil {
|
|
t.Fatalf("update: %v", err)
|
|
}
|
|
h, err := store.HolderByAccessKey(ctx, db, made.AccessSecret)
|
|
if err != nil {
|
|
t.Fatalf("the edited key stopped resolving: %s", store.Reason(err))
|
|
}
|
|
if h.Scope != "model:zen5" || h.Key != "svc" {
|
|
t.Fatalf("resolved scope %q key %q, want model:zen5 svc", h.Scope, h.Key)
|
|
}
|
|
|
|
pub, err := create(db)(ctx, &schema.Key{Owner: "acme", Name: "web", Scope: schema.KeyScopePublish})
|
|
if err != nil {
|
|
t.Fatalf("create publishable: %v", err)
|
|
}
|
|
if _, err := update(db)(ctx, &schema.Key{Owner: "acme", Name: "web", Scope: "model:zen5"}); err == nil {
|
|
t.Fatal("an update turned a publishable key into a secret one")
|
|
}
|
|
got, err := update(db)(ctx, &schema.Key{Owner: "acme", Name: "web", Scope: schema.KeyScopePublish + ",model:zen5"})
|
|
if err != nil {
|
|
t.Fatalf("narrow the publishable key: %v", err)
|
|
}
|
|
if got.Scope != "publish,model:zen5" || got.AccessKey != pub.AccessKey {
|
|
t.Fatalf("publishable update gave scope %q key %q", got.Scope, got.AccessKey)
|
|
}
|
|
}
|
|
|
|
// Revoking keeps the row, says who and when, refuses the credential with its own
|
|
// reason, and is final.
|
|
func TestKeys_RevokeIsAFinalStateThatStaysListed(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
seedUser(t, db, "acme", "ada")
|
|
|
|
made, err := create(db)(ctx, &schema.Key{Owner: "acme", Name: "svc", User: "ada", State: "Active"})
|
|
if err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
other, err := create(db)(ctx, &schema.Key{Owner: "acme", Name: "svc2", User: "ada", State: "Active"})
|
|
if err != nil {
|
|
t.Fatalf("create second: %v", err)
|
|
}
|
|
got, err := update(db)(ctx, &schema.Key{Owner: "acme", Name: "svc", User: "ada", State: schema.KeyStateRevoked, Revoker: "acme/bob"})
|
|
if err != nil {
|
|
t.Fatalf("revoke: %v", err)
|
|
}
|
|
if got.Revoker != "acme/bob" || got.RevokeTime == "" {
|
|
t.Fatalf("revoke recorded revoker %q at %q", got.Revoker, got.RevokeTime)
|
|
}
|
|
if _, err := store.HolderByAccessKey(ctx, db, made.AccessSecret); store.Reason(err) != store.KeyRevoked {
|
|
t.Fatalf("a revoked key resolved with reason %q, want %q", store.Reason(err), store.KeyRevoked)
|
|
}
|
|
if _, err := store.HolderByAccessKey(ctx, db, other.AccessSecret); err != nil {
|
|
t.Fatalf("revoking one key ended its sibling: %s", store.Reason(err))
|
|
}
|
|
listed, err := list(db)(as("acme"), &ListRequest{Owner: "acme"})
|
|
if err != nil {
|
|
t.Fatalf("list: %v", err)
|
|
}
|
|
if len(listed.Keys) != 2 {
|
|
t.Fatalf("a revoked key must stay listed, got %d rows", len(listed.Keys))
|
|
}
|
|
if _, err := update(db)(ctx, &schema.Key{Owner: "acme", Name: "svc", User: "ada", State: "Active"}); err == nil {
|
|
t.Fatal("an update reopened a revoked key")
|
|
}
|
|
}
|
|
|
|
// A key that is used says when: the resolver records a sighting, at most one write
|
|
// a minute, and the list reads it back as usedTime without the key row changing.
|
|
func TestKeys_AResolvedKeyIsListedWithWhenItWasUsed(t *testing.T) {
|
|
db := memDB(t)
|
|
ctx := context.Background()
|
|
seedUser(t, db, "acme", "ada")
|
|
|
|
made, err := create(db)(ctx, &schema.Key{Owner: "acme", Name: "svc", User: "ada", State: "Active"})
|
|
if err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
if _, err := create(db)(ctx, &schema.Key{Owner: "acme", Name: "idle", User: "ada", State: "Active"}); err != nil {
|
|
t.Fatalf("create idle: %v", err)
|
|
}
|
|
before, err := orm.Get[schema.Key](db, "acme/svc")
|
|
if err != nil {
|
|
t.Fatalf("read: %v", err)
|
|
}
|
|
for range 3 {
|
|
if _, err := store.HolderByAccessKey(ctx, db, made.AccessSecret); err != nil {
|
|
t.Fatalf("resolve: %s", store.Reason(err))
|
|
}
|
|
}
|
|
listed, err := list(db)(as("acme"), &ListRequest{Owner: "acme"})
|
|
if err != nil {
|
|
t.Fatalf("list: %v", err)
|
|
}
|
|
used := map[string]string{}
|
|
for _, k := range listed.Keys {
|
|
used[k.Name] = k.UsedTime
|
|
}
|
|
if used["svc"] == "" || used["idle"] != "" {
|
|
t.Fatalf("usedTime: svc %q, idle %q; want svc set and idle empty", used["svc"], used["idle"])
|
|
}
|
|
after, err := orm.Get[schema.Key](db, "acme/svc")
|
|
if err != nil {
|
|
t.Fatalf("read: %v", err)
|
|
}
|
|
if after.UpdatedTime != before.UpdatedTime || after.UsedTime != "" {
|
|
t.Fatal("recording a use rewrote the key row")
|
|
}
|
|
n, err := orm.TypedQuery[schema.Sighting](db).GetAll(ctx)
|
|
if err != nil || len(n) != 1 {
|
|
t.Fatalf("three uses inside a minute wrote %d sightings (%v), want 1", len(n), err)
|
|
}
|
|
}
|