Files
iam/internal/applications/applications.go
zeekay 30276040e1 An account, a service account and an application's org are org names, so nothing reads as Admin
The owner an account is filed under is orgs[0] of every token it is ever
issued, the org platform authority is decided on. users.Create held the
username to a rule and the owner to none, so a SuperAdmin's create stored
Admin/<name> and ac/me/<name>: accounts in orgs that do not exist, the
first of which a case-folding reader took for the reserved org. The org
name rule moves to schema.OrgName and every write that files a principal
under an org asks it; a name that is not one is refused, never lowercased.
2026-10-18 21:51:33 -07:00

415 lines
18 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
// Package applications is the Phase-1 typed CRUD surface for the `applications`
// entity. Every operation is a zip typed handler (decode In -> run -> encode
// Out) over hanzoai/orm and is owner-scoped by the (owner, name) natural key,
// materialized as the orm id "<owner>/<name>". The same In/Out types back both
// the REST route and the MCP tools/call projection zip derives from them, so
// identity arguments travel in the typed request, not in ad-hoc path parsing.
package applications
import (
"context"
"errors"
policy "github.com/hanzoai/authz"
"github.com/hanzoai/orm"
"github.com/zap-proto/zip"
"github.com/hanzoai/iam/internal/authz"
"github.com/hanzoai/iam/internal/principal"
"github.com/hanzoai/iam/pkg/schema"
"github.com/hanzoai/iam/pkg/store"
)
// authorizeOrganization gates the Organization an application will SERVE (the
// tenant a credential minted through it lands in), not just its registry Owner:
// the op-invoke authz hook authorizes the top-level Owner, but Organization is a
// separate field that a tenant admin could otherwise set to the reserved admin
// org (a SuperAdmin-minting app) or to a victim tenant. On a gated HTTP request
// the Guard attached a Principal; a non-super may point an app only at its OWN
// org. A context carrying no principal is refused for the reason AuthorizeCert
// states: this handler is reached from the router and nowhere else, so arriving
// without one is a door left open rather than a caller to trust.
//
// The org it names is an org name before it is anyone's to grant: a SuperAdmin may
// point an app at any org, and "Admin" is not one — it names no org, and every
// app token minted through it would carry it.
func authorizeOrganization(ctx context.Context, in *schema.Application) error {
if in.Organization == "" {
return nil // an org-less app mints no cross-tenant/SuperAdmin identity
}
if err := schema.OrgName(in.Organization); err != nil {
return zip.ErrBadRequest(err.Error())
}
p, ok := principal.From(ctx)
if !ok {
return zip.ErrForbidden("not authorized to set the application organization to " + in.Organization)
}
if !authz.CanSetOrg(p, in.Organization) {
return zip.ErrForbidden("not authorized to set the application organization to " + in.Organization)
}
return nil
}
// authorizeSpan gates an application that serves organizations other than its
// own — one whose fields declare it (schema.Application.Spans: isShared, or an
// orgChoiceMode other than ""/"None"). Such an application signs in every org's
// people, and its redirect URIs decide where their codes go, so it is a platform
// decision: only a SuperAdmin (authz.IsSuper) writes one. Everyone else writes
// only an application that serves its own org alone, both as stored (existing,
// nil on a create) and as written — so a non-SuperAdmin neither makes one, nor
// edits one, nor confines one.
func authorizeSpan(ctx context.Context, in, existing *schema.Application) error {
if authz.IsSuper(ctx) {
return nil
}
if in.Spans() || (existing != nil && existing.Spans()) {
return zip.ErrForbidden("only a SuperAdmin may write an application that serves other organizations")
}
return nil
}
// authorizePlatformRow gates a write to, or the removal of, one of the platform's
// own applications: only a SuperAdmin makes either. Its redirect URIs, secret and
// grants decide who can hold its tokens, and its tokens act where only the
// platform may, so a row's other fields are guarded with the flag.
func authorizePlatformRow(ctx context.Context, existing *schema.Application) error {
if !existing.Platform || authz.IsSuper(ctx) {
return nil
}
return zip.ErrForbidden("the platform's own applications are changed by a SuperAdmin only")
}
// authorizeProviders gates the identity providers an application LINKS. A link is a
// reference to credentials: the sign-in leg runs on the provider record's own client
// id and secret (store.EnrichProviders resolves it, federationProvider uses it), and
// the application never holds those — it names them. The row's own (Owner, Name)
// does not cover the reference, so the seam that authorizes the row left the link
// open.
//
// The rule is the one the seeding makes true: the PLATFORM's connectors are shared,
// so any application may name one — that is what "sign in with Google" is, and a
// link naming no owner resolves there. What no application may name is ANOTHER
// TENANT's provider, whose client id and secret are that tenant's own. A SuperAdmin
// may name any.
//
// The owner is resolved through store.ProviderOwner, the same function the
// resolution uses, so the record authorized here is the record the sign-in reaches.
// Only a foreign-tenant link is decided, and authz.Can answers no for a request
// there is no principal for, so an application linking nothing — or linking only
// what everyone may — passes without a decision to make.
func authorizeProviders(ctx context.Context, in *schema.Application) error {
for _, item := range in.Providers {
if item == nil || item.Name == "" {
continue
}
owner := store.ProviderOwner(item)
if policy.IsReservedOrg(owner) || owner == in.Owner || owner == in.Organization {
continue
}
if !authz.Can(ctx, "POST", "providers", owner, item.Name) {
return zip.ErrForbidden("not authorized to link the identity provider " + owner + "/" + item.Name)
}
}
return nil
}
// ensureClientIdUnique rejects a create/update whose clientId is already held by a
// DIFFERENT application (any owner). clientId is the GLOBAL key the mint and Basic-auth
// resolvers authenticate against, so it must be unique across every owner, not merely
// within one — otherwise a tenant could register a row whose clientId collides with a
// platform console's and (on a backend whose duplicate-row order is unspecified) shadow
// it. A JSON-document store has no per-field column to carry a DB UNIQUE index, so the
// invariant is enforced here at the write, exactly as the (owner,name) natural key is.
// An empty clientId cannot collide (a public app authenticates no confidential grant);
// the self-row (same owner,name) is skipped so an update that keeps its own clientId is
// never a self-collision.
func ensureClientIdUnique(ctx context.Context, db orm.DB, clientId, owner, name string) error {
if clientId == "" {
return nil
}
existing, err := store.ListApplicationsByClientId(ctx, db, clientId)
if err != nil {
return zip.ErrInternal(err.Error())
}
for _, a := range existing {
if a.Owner != owner || a.Name != name {
return zip.ErrConflict("clientId already in use: " + clientId)
}
}
return nil
}
// appID is the owner-scoped natural key "<owner>/<name>" — the single source
// of an application's orm id. Every handler routes through it so reads and
// writes address the exact same row.
func appID(owner, name string) string { return owner + "/" + name }
// ApplicationRef identifies one application by its owner-scoped natural key.
// It is the input for the get and delete operations.
type ApplicationRef struct {
Owner string `json:"owner" validate:"required"`
Name string `json:"name" validate:"required"`
}
// ApplicationQuery filters applications by owner for the list operation.
type ApplicationQuery struct {
Owner string `json:"owner" validate:"required"`
}
// ApplicationListResult wraps the applications owned by one owner, newest
// first.
type ApplicationListResult struct {
Applications []*schema.Application `json:"applications"`
}
// DeleteResult reports the outcome of a delete operation.
type DeleteResult struct {
Deleted bool `json:"deleted"`
}
//go:generate go run github.com/zap-proto/zip/cmd/zipdoc
// Route registers the applications CRUD surface on app, closing over db.
//
// The kind is addressed in the PLURAL, like every other kind in this service —
// users, certs, roles, invitations, keys, projects, workspaces, permissions,
// providers, tokens, sessions, organizations, audit-logs,
// webauthn-credentials. The collection is `/v1/iam/applications`; one
// application is `/v1/iam/applications/:owner/:name`, read with GET, replaced
// with PUT, removed with DELETE. This was the only singular, so
// `/v1/iam/application` and `/v1/iam/applications` both answered and which
// spelling a reader wanted depended on the operation. Fourteen kinds against
// one is not a matter of taste; the odd one moved, and the singular is now a
// retirement notice (internal/gone).
func Route(app *zip.Group, db orm.DB) {
app.Get("/v1/iam/applications", listApplications(db), zip.WithTags("applications"))
app.Post("/v1/iam/applications", Create(db), zip.WithTags("applications"))
app.Get("/v1/iam/applications/:owner/:name", getApplication(db), zip.WithTags("applications"))
app.Put("/v1/iam/applications/:owner/:name", Update(db), zip.WithTags("applications"))
app.Delete("/v1/iam/applications/:owner/:name", deleteApplication(db), zip.WithTags("applications"))
}
// listApplications returns the applications in one organization, newest first —
// each product or site your people sign in to, with the sign-in methods and
// redirect URIs it allows.
func listApplications(db orm.DB) zip.TypedHandler[ApplicationQuery, ApplicationListResult] {
return func(ctx context.Context, in *ApplicationQuery) (*ApplicationListResult, error) {
if in.Owner == "" {
return nil, zip.ErrBadRequest("owner is required")
}
// The owner is resolved by principal.Scope from the authenticated principal,
// never taken from the input: a tenant reads only its own org, a SuperAdmin
// reads the owner it asks for. The op's Authorize hook re-checks the decoded
// target above this, but that is a SECOND gate — the Guard reads the FIRST
// value of a repeated query key and the binder the LAST, so the two can be
// handed different strings, and this handler filters on the one it was
// actually given. Every sibling listing resolves its owner the same way.
owner, err := principal.Scope(ctx, in.Owner)
if err != nil {
return nil, err
}
apps, err := orm.TypedQuery[schema.Application](db).
Filter("Owner=", owner).
Order("-CreatedTime").
GetAll(ctx)
if err != nil {
return nil, zip.ErrInternal(err.Error())
}
for i, app := range apps {
apps[i] = app.Mask() // never emit clientSecret in a list response
}
return &ApplicationListResult{Applications: apps}, nil
}
}
// getApplication returns one application: its sign-in methods, its allowed
// redirect URIs and the client credentials your integration authenticates with.
func getApplication(db orm.DB) zip.TypedHandler[ApplicationRef, schema.Application] {
return func(ctx context.Context, in *ApplicationRef) (*schema.Application, error) {
if in.Owner == "" || in.Name == "" {
return nil, zip.ErrBadRequest("owner and name are required")
}
id := appID(in.Owner, in.Name)
app, err := orm.Get[schema.Application](db, id)
if errors.Is(err, orm.ErrNotFound) {
return nil, zip.ErrNotFound("application not found: " + id)
}
if err != nil {
return nil, zip.ErrInternal(err.Error())
}
return app.Mask(), nil
}
}
// Create registers an application in your organization — one product or site
// your people sign in to, with its own client credentials, sign-in methods and
// allowed redirect URIs. A name already used in the organization is refused
// rather than overwritten. An application that serves other organizations —
// isShared, or any orgChoiceMode but "" and "None" — is created by a SuperAdmin
// only.
//
// Exported so the legacy add-application alias reuses this exact path — one
// create, two spellings.
func Create(db orm.DB) zip.TypedHandler[schema.Application, schema.Application] {
return func(ctx context.Context, in *schema.Application) (*schema.Application, error) {
if in.Owner == "" || in.Name == "" {
return nil, zip.ErrBadRequest("owner and name are required")
}
if err := authorizeOrganization(ctx, in); err != nil {
return nil, err
}
if err := authz.AuthorizeCert(ctx, db, in.Cert, ""); err != nil {
return nil, err
}
if err := authorizeSpan(ctx, in, nil); err != nil {
return nil, err
}
// Which applications are the platform's own is the seed's to say
// (internal/seed markPlatform), and nobody else's: a create never makes one.
in.Platform = false
if err := authorizeProviders(ctx, in); err != nil {
return nil, err
}
id := appID(in.Owner, in.Name)
// Owner-scoped uniqueness: (owner, name) must be free.
if _, err := orm.Get[schema.Application](db, id); err == nil {
return nil, zip.ErrConflict("application already exists: " + id)
} else if !errors.Is(err, orm.ErrNotFound) {
return nil, zip.ErrInternal(err.Error())
}
// Global uniqueness: clientId is the mint/Basic-auth resolution key, so it must
// be free across ALL owners — the invariant the confidential-client gates rely on.
if err := ensureClientIdUnique(ctx, db, in.ClientId, in.Owner, in.Name); err != nil {
return nil, err
}
// And the name: an account records the application that registered it by name
// alone (see store.NameHeldElsewhere).
if held, err := store.NameHeldElsewhere(ctx, db, in.Owner, in.Name); err != nil {
return nil, zip.ErrInternal(err.Error())
} else if held {
return nil, zip.ErrConflict("application name already in use: " + in.Name)
}
// Bind the decoded entity to db under its natural key and persist.
in.Init(db)
in.SetId(id)
if err := in.Create(); err != nil {
return nil, zip.ErrInternal(err.Error())
}
return in.Mask(), nil
}
}
// Update changes an application's display, its sign-in methods and the redirect
// URIs it may return to — the call that makes login work from a new host. Which
// organization it belongs to and what it is named are fixed when it is created
// and are not editable here. An application that serves other organizations —
// isShared, or any orgChoiceMode but "" and "None" — is written by a SuperAdmin
// only, before and after the change.
//
// Exported so the legacy update-application alias reuses this exact path — one
// update, two spellings.
func Update(db orm.DB) zip.TypedHandler[schema.Application, schema.Application] {
return func(ctx context.Context, in *schema.Application) (*schema.Application, error) {
if in.Owner == "" || in.Name == "" {
return nil, zip.ErrBadRequest("owner and name are required")
}
if err := authorizeOrganization(ctx, in); err != nil {
return nil, err
}
id := appID(in.Owner, in.Name)
existing, err := orm.Get[schema.Application](db, id)
if errors.Is(err, orm.ErrNotFound) {
return nil, zip.ErrNotFound("application not found: " + id)
}
if err != nil {
return nil, zip.ErrInternal(err.Error())
}
if err := authz.AuthorizeCert(ctx, db, in.Cert, existing.Cert); err != nil {
return nil, err
}
if err := authorizeSpan(ctx, in, existing); err != nil {
return nil, err
}
if err := authorizePlatformRow(ctx, existing); err != nil {
return nil, err
}
// The flag is the seed's; an update keeps what is stored.
in.Platform = existing.Platform
if err := authorizeProviders(ctx, in); err != nil {
return nil, err
}
// Global clientId uniqueness (see Create): an update may keep its own clientId
// but must never steal another app's.
if err := ensureClientIdUnique(ctx, db, in.ClientId, in.Owner, in.Name); err != nil {
return nil, err
}
// A write that says NOTHING about the credential must not destroy it.
//
// This verb is a full REPLACE, and every read of an application MASKS its
// client secret (Mask, and get-app-login before it) — so the natural admin
// round-trip — read the record, change one field, write it back — posts
// ClientSecret:"" for an app that holds one, so the write would blank it. Any
// console "save" on an application page is then one request from turning a
// confidential client public, which the token endpoint reads as "PKCE, demand
// no client auth", weakening every flow that app serves.
//
// So an OMITTED secret preserves what is stored. This is the same rule the
// operator upsert already settled in resolveSecret ("existing app -> preserve
// what it has"), stated once more here because this is the other path onto the
// same row; rotation stays possible, it just has to be DELIBERATE — send the
// new secret to change it.
//
// Clearing a secret on purpose (confidential -> public) is therefore no longer
// expressible as an accident. It goes through the operator upsert's explicit
// `public: true`, which is the one place that decision is named.
if in.ClientSecret == "" {
in.ClientSecret = existing.ClientSecret
}
in.Init(db)
in.SetId(id)
in.CreatedTime = existing.CreatedTime
in.CreatedAt = existing.CreatedAt
if err := in.Update(); err != nil {
return nil, zip.ErrInternal(err.Error())
}
return in.Mask(), nil
}
}
// deleteApplication removes an application. Anyone mid-sign-in through it is
// turned away and its client credentials stop working, so retire the integration
// before deleting it.
func deleteApplication(db orm.DB) zip.TypedHandler[ApplicationRef, DeleteResult] {
return func(ctx context.Context, in *ApplicationRef) (*DeleteResult, error) {
if in.Owner == "" || in.Name == "" {
return nil, zip.ErrBadRequest("owner and name are required")
}
id := appID(in.Owner, in.Name)
app, err := orm.Get[schema.Application](db, id)
if errors.Is(err, orm.ErrNotFound) {
return nil, zip.ErrNotFound("application not found: " + id)
}
if err != nil {
return nil, zip.ErrInternal(err.Error())
}
if err := authorizePlatformRow(ctx, app); err != nil {
return nil, err
}
if err := app.Delete(); err != nil {
return nil, zip.ErrInternal(err.Error())
}
return &DeleteResult{Deleted: true}, nil
}
}