mirror of
https://github.com/hanzoai/iam.git
synced 2026-11-19 18:37:16 +00:00
The session cookie is SameSite=Lax, which keeps it off requests from other sites but not from other hosts of the same site. Once hanzo.ai signs people in, any page on any *.hanzo.ai host could post a form to /v1/iam/login with type=device and approve an attacker's `hanzo login` code, or with type=code mint an authorization code, or edit the account. sessions.Forgeable is now the one rule for a write the cookie authorizes: Sec-Fetch-Site must be same-origin or none, and a request with a body must carry it as JSON. sessions.Writer resolves the session only past it, and every cookie write goes through it: the login SSO and device branches, callerOf/callerFrom (profile, password rotation, terms, consent, preferences, onboarding, link, unlink, passkey enrollment), and invitation accept. A refused write is 403 before the session is read. The passkey finish, which the challenge cookie authorizes, asks the same rule. A bearer from a client that is not a browser needs no fetch metadata, with or without a cookie riding along. Signing out ends sessions, so sessions.Clear asks the rule too, with one exception: a top-level navigation (Sec-Fetch-Mode navigate, Sec-Fetch-Dest document), which is how a relying party signs a person out. An image, a frame or a sibling's form ends nothing. The federation binding cookie is __Host-hanzo_fed and only that name is read; a test now pins that the bare hanzo_fed name is refused. server.RequireIssuer is the boot check for issuers: it installs IAM_ISSUER and IAM_ISSUER_MAP, then IAM_FEDERATION_ORIGIN_MAP, and returns an error for an empty or non-https IAM_ISSUER (outside IAM_DEV_HOST_RELATIVE=1), a malformed issuer map, or a sign-in map that would strand the binding. `iam serve` calls it, and a host that embeds IAM must call it before NewApp. devFallbackIssuer and the lazy env resolvers are gone: a process that never installed an issuer has none, so every issuer read is an error, discovery answers 503, no token is minted and none is accepted, where it used to answer https://hanzo.id. No issuer value changes. Co-authored-by: Hanzo Dev <[email protected]>
139 lines
5.6 KiB
Go
139 lines
5.6 KiB
Go
// Copyright 2026 Hanzo AI, Inc.
|
|
// SPDX-License-Identifier: MIT OR Apache-2.0
|
|
|
|
package oidc
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"github.com/hanzoai/orm"
|
|
"github.com/zap-proto/zip"
|
|
|
|
"github.com/hanzoai/iam/internal/httpx"
|
|
"github.com/hanzoai/iam/pkg/schema"
|
|
"github.com/hanzoai/iam/pkg/store"
|
|
)
|
|
|
|
// POST /v1/iam/preferences — the ONE account-backed store for cross-product,
|
|
// cross-device user customizations (onboarding-completed flag, theme, pinned
|
|
// favorites, …). The console's PreferencesProvider reads these from the account's
|
|
// Properties["hanzo.preferences"] JSON blob and write-through-persists partial updates
|
|
// here. Ported from the v1 me_preferences.go contract.
|
|
//
|
|
// SELF-SCOPED (never the body): the target user is ALWAYS the caller resolved from its
|
|
// session/bearer (callerOf) — never a name/org in the request — so a caller can only
|
|
// ever write its OWN preferences. MERGE: top-level keys are shallow-merged onto the
|
|
// stored object, so concurrent products/devices setting DIFFERENT keys don't clobber
|
|
// each other; the merged object is returned so the caller keeps every other key.
|
|
|
|
// PathPreferences (canonical.go) is the self-preferences endpoint.
|
|
|
|
// preferencesKey is the User.Properties entry holding the cross-product preferences
|
|
// JSON blob — the backend half of the console contract (PREFS_PROPERTY); keep in
|
|
// lockstep. Defined once in schema, where the consent record nested inside the same
|
|
// blob also reads it, so the two cannot drift onto different properties.
|
|
const preferencesKey = schema.PreferencesKey
|
|
|
|
// preferencesMaxBytes caps the serialized merged blob so a runaway client can't grow
|
|
// the properties column without bound.
|
|
const preferencesMaxBytes = 64 * 1024
|
|
|
|
// updatePreferencesHandler saves the calling person's own settings and returns
|
|
// the full set afterwards. Send only the settings you are changing — the rest
|
|
// are kept, so two screens can save at once without one undoing the other.
|
|
func updatePreferencesHandler(db orm.DB) zip.Handler {
|
|
return func(c *zip.Ctx) error {
|
|
ctx := c.Context()
|
|
owner, name, err := callerOf(ctx, c, db)
|
|
if err != nil {
|
|
return refuseCaller(c, err, "please sign in first")
|
|
}
|
|
user, err := store.GetUserByName(ctx, db, owner, name)
|
|
if err != nil {
|
|
return httpx.Err(c, "server_error")
|
|
}
|
|
if user == nil {
|
|
return httpx.Err(c, "the user does not exist")
|
|
}
|
|
|
|
// Merge under the row lock against the FRESH stored blob (updateUser): a
|
|
// concurrent product/device setting a DIFFERENT top-level key is preserved (the
|
|
// merge now reads the current value, not a snapshot), and the lockout counter is
|
|
// never clobbered by this full-row write.
|
|
body := c.Fiber().Body()
|
|
var merged map[string]json.RawMessage
|
|
if _, err := updateUser(ctx, db, owner, name, func(_ orm.DB, u *schema.User) error {
|
|
mergedJSON, m, err := mergePreferences(u.Properties[preferencesKey], body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if u.Properties == nil {
|
|
u.Properties = map[string]string{}
|
|
}
|
|
u.Properties[preferencesKey] = mergedJSON
|
|
u.UpdatedTime = provisionNow()
|
|
merged = m
|
|
return nil
|
|
}); err != nil {
|
|
return httpx.Err(c, err.Error())
|
|
}
|
|
return httpx.Ok(c, merged)
|
|
}
|
|
}
|
|
|
|
// mergePreferences shallow-merges a JSON `patch` object onto the `existing`
|
|
// preferences JSON string, returning the merged JSON plus the merged map. Pure (no
|
|
// session, no DB): a patch key overwrites ONLY that top-level key (every other stored
|
|
// key survives); an absent/blank/corrupt `existing` is an empty object (a first write
|
|
// still lands and self-heals); a non-object patch is rejected; the blob is size-capped.
|
|
func mergePreferences(existing string, patch []byte) (string, map[string]json.RawMessage, error) {
|
|
patchMap := map[string]json.RawMessage{}
|
|
if err := json.Unmarshal(patch, &patchMap); err != nil {
|
|
return "", nil, fmt.Errorf("preferences must be a JSON object: %w", err)
|
|
}
|
|
|
|
// Consent rides the same blob but is NOT a preference: it is a record of what
|
|
// a person answered, it is validated against a closed set of answers, and a
|
|
// change to it is audited. None of that is true of a shallow merge, so a patch
|
|
// naming the key is refused rather than served — reaching consent through the
|
|
// generic surface would be a second, unvalidated, unaudited writer of the one
|
|
// record that most needs a single one. There is exactly one way to answer.
|
|
if _, ok := patchMap[schema.ConsentKey]; ok {
|
|
return "", nil, fmt.Errorf("consent is not a preference; use PUT %s to answer", PathConsent)
|
|
}
|
|
|
|
// Terms acceptance is a record of what a person did, written at PUT PathTerms.
|
|
if _, ok := patchMap[schema.TermsKey]; ok {
|
|
return "", nil, fmt.Errorf("terms acceptance is not a preference; use PUT %s to accept", PathTerms)
|
|
}
|
|
|
|
// Appearance IS a preference, so it is written here — but as the record it is,
|
|
// not as opaque JSON. A density no product can render or a type scale that
|
|
// leaves the page unusable is refused where the caller can be told why, rather
|
|
// than stored for every reader to drop afterwards, which shows a person a saved
|
|
// setting that nothing obeys.
|
|
if raw, ok := patchMap[schema.AppearanceKey]; ok {
|
|
if _, err := schema.ParseAppearance(raw); err != nil {
|
|
return "", nil, err
|
|
}
|
|
}
|
|
|
|
merged := map[string]json.RawMessage{}
|
|
if existing != "" {
|
|
_ = json.Unmarshal([]byte(existing), &merged) // corrupt stored blob → treated as empty
|
|
}
|
|
for k, v := range patchMap {
|
|
merged[k] = v
|
|
}
|
|
|
|
out, err := json.Marshal(merged)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
if len(out) > preferencesMaxBytes {
|
|
return "", nil, fmt.Errorf("preferences exceed maximum size of %d bytes", preferencesMaxBytes)
|
|
}
|
|
return string(out), merged, nil
|
|
}
|