Help us shape the future of Go! Take the 2026 Go Developer Survey

devidp

package
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package devidp is the sign-in broker's client for a Zitadel instance: it drives the OIDC authorization-code flow with PKCE on the server's behalf (BeginFlow, SignIn, SignUp, RedeemCode), creates and finalizes sessions with the login broker's token, and resets passwords. The token may come from a file that is re-read on each use, so a rotated credential needs no restart.

It does NOT converge an instance. Registering the project, applications, roles, users and the broker account is pkg/identity's job: `forge env up` runs it against the dev IdP and the control plane runs it against hosted instances.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidResetCode = errors.New("the reset code is not valid for this user")

ErrInvalidResetCode means the issuer rejected the reset code: wrong, expired, or already used. Deliberately one error for all three — a form that tells "expired" from "wrong" teaches a guesser when to stop.

View Source
var ErrUserNotFound = errors.New("no single user has that email address")

ErrUserNotFound is returned by FindUserByEmail when no human user has that address — or when more than one does, which is treated the same way: a reset keyed by an ambiguous email cannot know whose password it is changing.

Functions

This section is empty.

Types

type BrokerCredential

type BrokerCredential struct {
	UserID string
	Token  string
}

BrokerCredential is the service account the login broker authenticates as, and the token it presents.

UserID is returned alongside the token because the role grant is keyed by user id, not by token — a caller that needs to re-grant (or audit) the role has the handle without another lookup.

type Client

type Client struct {
	// Base is the address this process DIALS. Inside a deploy-time Job
	// that is the in-network address (a compose service name or a
	// cluster-local Service DNS name), which is not necessarily the
	// BROWSER-facing origin — see Host.
	Base string

	// Host overrides the HTTP Host header, for when the address this
	// process dials differs from the address the instance is REGISTERED
	// under (Base above). Empty sends the Host implied by Base.
	//
	// Zitadel is multi-tenant and resolves which instance a request
	// belongs to from the Host header, matched against the instance's
	// ExternalDomain — not from the socket the request arrived on. A Job
	// running inside the compose network dials "idp:8080", but the dev
	// instance is registered under "localhost" (the browser's origin), so
	// every call needs this override or Zitadel answers "Instance not
	// found" with an otherwise perfectly valid, correctly authenticated
	// request.
	Host string

	// Token is the personal access token of the service account declared
	// in idp-steps.yaml, which Zitadel writes to disk on first boot.
	Token string

	// TokenFile, when set, names a file holding the token, read on every use
	// so the credential can rotate without a restart. It takes precedence over
	// Token while it yields one; Token stays the fallback. See token_file.go.
	TokenFile string

	// OrgID scopes management calls to one organization. Resolved by
	// DefaultOrg when empty.
	OrgID string
	// contains filtered or unexported fields
}

Client talks to a running Zitadel instance.

ONE base URL, unlike a provider that splits its admin API onto a second port: Zitadel serves the OIDC endpoints, the resource APIs (`/v2/...`) and the management API (`/management/v1/...`) on a single port, and authorizes all of them with the same bearer token.

func (*Client) BeginFlow

func (c *Client) BeginFlow(ctx context.Context, cfg FlowConfig) (Flow, error)

BeginFlow creates an authorization request at the issuer and returns the handle needed to complete it.

This calls /authorize the way a browser would, but WITHOUT following the redirect: the response's Location header carries the auth request id, which is the only part that matters. Nothing navigates.

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, creds Credentials) (Session, error)

CreateSession authenticates a user and returns the resulting session.

The credential check happens INSIDE the issuer: this call ships the password to Zitadel, which verifies it against its own stored hash. This process never sees, stores or compares a password hash, which is the property that makes brokering the call acceptable in the first place.

A bad password returns an error carrying Zitadel's own message (COMMAND-3M0fs, with a failedAttempts count) rather than a paraphrase: lockout policy is the issuer's to enforce and to report.

func (*Client) DefaultOrg

func (c *Client) DefaultOrg(ctx context.Context) (Org, error)

DefaultOrg returns the instance's first organization, which for a forge-scaffolded instance is the one idp-steps.yaml declared.

It is looked up rather than pinned because the ID is generated: the NAME is declarative (it is in idp-steps.yaml), the snowflake ID it gets is not.

func (*Client) EnsureLoginBroker

func (c *Client) EnsureLoginBroker(ctx context.Context, username string) (BrokerCredential, error)

EnsureLoginBroker provisions the DEDICATED service account the login broker runs as, grants it the login-client role, and returns a token for it.

WHY A SEPARATE ACCOUNT rather than reusing the provisioning credential. The provisioner's token is an IAM_OWNER credential that exists to register applications at deploy time; the broker's token exists to complete logins at request time, lives in a long-running server, and is reachable from the request path. Those are different lifetimes and very different blast radii, and folding them into one token means a compromise of the busiest surface in the app yields the credential that administers the whole instance.

Splitting them costs one more account in the dev bootstrap and buys the ability to rotate or revoke the login path without touching provisioning.

NOT IDEMPOTENT IN THE USUAL SENSE, and deliberately: Zitadel issues a personal access token exactly once and never returns it again, so a re-run against an existing account cannot recover the previous token and mints a NEW one instead. The old token stays valid until it expires or is removed — so callers should provision once and persist the result, rather than calling this on every boot. ProvisionLoginBroker is that caller: it keeps a stored token the issuer still accepts and mints only when it must.

func (*Client) EnsureLoginClientRole

func (c *Client) EnsureLoginClientRole(ctx context.Context, userID string) error

EnsureLoginClientRole grants the service account behind this client the role the API-only sign-in flow requires, preserving whatever roles it already holds.

THIS IS A PRIVILEGED GRANT. IAM_LOGIN_CLIENT permits completing an authorization request on behalf of any user in the instance, so the credential holding it is as sensitive as the sign-in flow itself. It belongs to the one backend that brokers logins — never in a frontend bundle, a build environment, or a shared operator token.

userID is the service account's own user id. Roles are reconciled as a SET: the existing roles are read and this one added, so a re-run is a no-op and an unrelated role is never dropped.

func (*Client) FinalizeAuthRequest

func (c *Client) FinalizeAuthRequest(ctx context.Context, authRequestID string, session Session) (string, error)

FinalizeAuthRequest completes an OIDC authorization request with an authenticated session, and returns the callback URL the browser should be sent to. That URL carries the authorization code and the original `state`.

authRequestID is the value the issuer put in the query string when it redirected into this app (see SetLoginUI). Pass it through unchanged, INCLUDING any prefix: Zitadel's v2 ids are prefixed (`V2_...`), and the prefix is part of the id.

A v1 auth request cannot be finalized this way — it fails "Auth Request does not exist (COMMAND-jae5P)", which reads like a expiry bug but means the LoginV2 feature is not enabled for this instance. SetLoginUI is what makes the issuer mint v2 requests in the first place, so the two are a package: neither is useful alone.

func (*Client) FindUserByEmail

func (c *Client) FindUserByEmail(ctx context.Context, email string) (User, error)

FindUserByEmail resolves an email address to the one human user that has it, case-insensitively.

The broker's login-client credential may search users, so this works with the same token SignIn uses.

func (*Client) FindUserByID added in v1.0.0

func (c *Client) FindUserByID(ctx context.Context, id string) (User, error)

FindUserByID resolves a user id to the human user it names. ErrUserNotFound when there is none, or when it is a machine account.

func (*Client) HasBrokerToken added in v0.1.46

func (c *Client) HasBrokerToken() bool

HasBrokerToken reports whether a token is available from either source. Use it for a boot-time "is sign-in configured" check; it reads the file.

func (*Client) MintPasswordResetCode added in v1.0.0

func (c *Client) MintPasswordResetCode(ctx context.Context, userID string) (string, error)

MintPasswordResetCode asks the issuer for a reset code and returns it to the CALLER instead of mailing it.

THE RETURNED CODE IS THE CREDENTIAL. Whoever holds it can set the user's password. It belongs in a server log in development, or in a channel the account's owner controls (an SMS, a chat message, an admin screen only they can see) — never in a response to the request that asked for it, which is anyone on the internet. A handler that returned it from a "forgot password" endpoint would turn that endpoint into "take over any account".

func (*Client) PasswordPolicy added in v1.0.0

func (c *Client) PasswordPolicy(ctx context.Context) (PasswordPolicy, error)

PasswordPolicy reads the instance's password-complexity policy.

func (*Client) RedeemCode

func (c *Client) RedeemCode(ctx context.Context, cfg FlowConfig, code string, pkce PKCE) (Tokens, error)

RedeemCode exchanges an authorization code for tokens.

The PKCE verifier proves this is the same party that started the flow. It has been in this process's memory the entire time, which is what makes the proof meaningful — in a browser flow it has to survive a redirect in storage a script can read.

No client secret: this is a public client using PKCE. Adding one would not improve anything here, and would put a credential in config that PKCE already replaced.

func (*Client) Register

func (c *Client) Register(ctx context.Context, reg Registration) (string, error)

Register creates a new human user at the issuer and returns its id.

WHY THIS IS A SERVER CALL. Creating a user needs `user.write`, which a browser cannot hold — the same reason the session and callback calls are brokered. The credential is the login broker's, so registration and sign-in share one account and one blast radius rather than adding a second privileged token.

The issuer enforces its own password policy and uniqueness; a rejection comes back as its own message rather than a paraphrase, because "must contain a symbol" is exactly what the person filling in the form needs to read.

func (*Client) ResetPassword

func (c *Client) ResetPassword(ctx context.Context, r PasswordReset) error

ResetPassword sets a user's password using a one-time reset code.

A missing field is refused BEFORE any network call — above all a missing Code. See the file header: with the broker's credential, the issuer would accept a code-less request and overwrite the password of whichever user is named. There is no safe default for "which code did the person present".

Errors a caller should branch on:

  • ErrInvalidResetCode (wrapped): wrong, expired or used code;
  • *PasswordPolicyError: code fine, password rejected — the code is still usable.

Anything else is the issuer or the credential failing, and is returned with the issuer's own message.

func (c *Client) SendPasswordResetLink(ctx context.Context, userID, urlTemplate string) error

SendPasswordResetLink asks the issuer to EMAIL the user a link to set a new password. urlTemplate is the link's shape, with the issuer's placeholders:

https://app.example.com/auth/reset?userID={{.UserID}}&code={{.Code}}&orgID={{.OrgID}}

── This sends mail only if the instance has an SMTP provider ───────────

The call SUCCEEDS either way. An instance with no SMTP configuration (every customer instance, unless its environment declares `smtp`) accepts the request, queues a notification nothing can deliver, and tells the caller nothing. A nil error therefore means "the issuer accepted the request", never "an email arrived".

The code travels only in the email. This function never returns it, so a request handler that calls it cannot leak one to the person asking.

func (*Client) SetLoginUI

func (c *Client) SetLoginUI(ctx context.Context, loginURI string) error

SetLoginUI points the instance's login UI at loginURI — the app's OWN sign-in route — so /oauth/v2/authorize redirects there instead of rendering the issuer's bundled pages.

This is the switch that makes the whole flow possible, and it is why a project that merely calls CreateSession still ends up on the issuer's login screen. Empty loginURI restores the issuer-hosted UI.

Enabling it also changes the SHAPE of the auth request the issuer mints (v2 rather than v1), which is what FinalizeAuthRequest requires. That coupling is the reason both live in this file.

func (*Client) SignIn

func (c *Client) SignIn(ctx context.Context, cfg FlowConfig, creds Credentials) (Tokens, error)

SignIn runs the ENTIRE flow — begin, authenticate, finalize, redeem — and returns the tokens. One call, no browser involvement at all.

This is the function an app's POST /auth/login handler wraps. Everything it needs from the browser is a login name and a password; everything the browser gets back is whatever session representation the app chooses.

The login name may be an EMAIL, which is what a sign-in form asks for. It is resolved to the account's real login name first (see loginNameFor): the issuer creates sessions by login name, and the two differ for any account created with a bare username.

func (*Client) SignUp

func (c *Client) SignUp(ctx context.Context, cfg FlowConfig, reg Registration) (Tokens, error)

SignUp registers an account and signs it in, in one call.

The sign-in is not a convenience: an account created without a session leaves the person who just chose a password on a login form retyping it, which is the worst step of most sign-up flows and one this shape removes for free.

func (*Client) WaitReady

func (c *Client) WaitReady(ctx context.Context) error

WaitReady blocks until the IdP answers its readiness probe, or ctx expires.

/debug/ready is Zitadel's own unauthenticated readiness route, and it reports READY rather than merely listening — which matters here because the first boot runs the declarative setup (schema, instance, org, admin user, PAT) before serving, and a probe that only checked for an open socket would hand back a client that 404s every call.

type Credentials

type Credentials struct {
	// LoginName identifies the account: the username, email or other
	// login name the issuer knows. Required.
	LoginName string

	// Password is the user's password. Required unless another verifying
	// factor is set — see buildChecks.
	Password string

	// TOTP is a time-based one-time code, when the account has TOTP
	// enrolled. Supplied ALONGSIDE Password: Zitadel records each factor
	// separately on the session, so a second factor adds to the password
	// check rather than replacing it.
	TOTP string
}

The API-only sign-in flow: how an app authenticates a user WITHOUT ever sending the browser to the identity provider's own login pages.

── Why this exists ───────────────────────────────────────────────────

The default OIDC authorization-code flow redirects the user agent to the issuer's /authorize endpoint, which answers with the IdP's OWN login UI. The user types their password on the issuer's origin, under the issuer's branding, and comes back with a code. That works, and for many products it is the right choice — an IdP-hosted page is one less place for a credential bug to live.

It is the wrong choice when the sign-in screen is part of the PRODUCT. Leaving the app to authenticate is a visible seam: different typography, a different URL in the address bar, no way to put a product's own empty states or error copy on the most-seen screen it has. This package's job is to make the other option available without asking anyone to reverse-engineer it.

── The three calls, and the one that is easy to get wrong ────────────

Zitadel's v2 API exposes the whole flow, so an app can drive it:

  1. The browser hits /oauth/v2/authorize as usual. With the LoginV2 feature pointed at the app (SetLoginUI below), the issuer redirects BACK INTO THE APP with an `authRequest` id instead of rendering its own page.
  2. The app collects credentials on its own screen and calls CreateSession — the credential check happens here.
  3. The app calls FinalizeAuthRequest with the resulting session, and receives the callback URL carrying the authorization code. From there the browser completes a standard PKCE token exchange; the backend never handles the user's tokens.

── THE BYPASS THIS FILE EXISTS TO PREVENT ────────────────────────────

Zitadel treats "which factors were checked" as the CALLER's decision. A session created with a user check and NO password check is a perfectly valid session, and it will finalize an auth request and yield real tokens. Verified against v4.19.4: a session with `checks: {user: {...}}` and nothing else produced a working access_token and id_token for an admin account, and the id_token carried NO `amr` claim — so a downstream validator cannot even tell the credential was never verified.

A wrong password is correctly rejected (COMMAND-3M0fs). Omitting the password entirely is not rejected at all. The difference matters because it is the difference between a login form and an impersonation endpoint.

So this package does NOT expose a "build your own checks" surface, and deliberately accepts no caller-supplied JSON for the checks object. Credentials is a closed set of typed fields, each mapping to exactly one factor, and buildChecks REFUSES to produce a checks object with no verifying factor in it. A handler that forwards a request body straight through cannot silently create a passwordless session, because there is no code path that accepts one.

If you need a factor this does not model, add a field to Credentials and a case to buildChecks. Do not reach around them.

type Flow

type Flow struct {
	AuthRequestID string
	PKCE          PKCE
}

Flow is one in-progress login: the issuer's auth request id, and the PKCE pair that will redeem it.

Hold this for the duration of ONE login attempt. It is not a session and must not be given to a browser: whoever holds the verifier can redeem the code.

type FlowConfig

type FlowConfig struct {
	ClientID    string
	RedirectURI string
	// Scopes requested. Empty defaults to the standard OIDC set.
	Scopes []string
}

FlowConfig is what an app needs to drive the flow: the OAuth client it registered, and where the issuer should send the code.

RedirectURI is still required even though no browser is redirected — the issuer validates it against the registered allowlist, and the token exchange must present the identical value. It is a protocol parameter here, not a navigation target.

type Org

type Org struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

Org is a Zitadel organization — the container a project and its users live in.

type PKCE

type PKCE struct {
	Verifier  string
	Challenge string
}

PKCE is one flow's proof-of-possession pair.

The verifier NEVER leaves the server. That is the point of doing this here: in the browser flow the verifier has to survive a redirect, which means sessionStorage, which means it is readable. Here it is a value in a struct that lives as long as one login attempt.

func NewPKCE

func NewPKCE() (PKCE, error)

NewPKCE generates a verifier and its S256 challenge (RFC 7636).

type PasswordPolicy added in v1.0.0

type PasswordPolicy struct {
	MinLength    int  `json:"min_length"`
	HasUppercase bool `json:"has_uppercase"`
	HasLowercase bool `json:"has_lowercase"`
	HasNumber    bool `json:"has_number"`
	HasSymbol    bool `json:"has_symbol"`
}

PasswordPolicy is the issuer's password-complexity policy. The JSON tags are the shape the scaffolded broker serves at GET /auth/password-policy.

func (PasswordPolicy) Describe added in v1.0.0

func (p PasswordPolicy) Describe(rules []PasswordRule) string

Describe joins the requirements for rules into one sentence fragment: "at least 8 characters, an uppercase letter and a number".

func (PasswordPolicy) Requirement added in v1.0.0

func (p PasswordPolicy) Requirement(rule PasswordRule) string

Requirement renders one rule as the noun phrase a sentence can list: "at least 8 characters", "an uppercase letter".

func (PasswordPolicy) Unmet added in v1.0.0

func (p PasswordPolicy) Unmet(password string) []PasswordRule

Unmet returns every rule of the policy the password breaks, in a stable order (length, uppercase, lowercase, number, symbol).

The issuer reports only the FIRST rule a password breaks — "Sh0rt!" is answered with "too short" alone, though it also lacks nothing else, and "short" is answered with "too short" though it also lacks an uppercase letter, a number and a symbol. Telling the person all of it at once saves them a round trip per rule, which is why the broker evaluates the policy itself on a rejection rather than relaying the one message.

The classes mirror the issuer's: A-Z, a-z, 0-9, and a symbol is anything else (a space counts — verified against v4.19.5). This is guidance; the issuer decides.

type PasswordPolicyError

type PasswordPolicyError struct {
	// Rule is the complexity rule the issuer reported, or "" when it
	// reported one this package does not know. The issuer names only the
	// first rule a password breaks; PasswordPolicy.Unmet lists them all.
	Rule PasswordRule
	// Reason is the issuer's own description ("Password is too short"),
	// safe and useful to show the person who typed it.
	Reason string
}

PasswordPolicyError means the code was ACCEPTED but the new password failed the issuer's password policy. The code is still valid afterwards (verified), so the person should pick a different password, not ask for a new code — which is why a caller must be able to tell this apart from ErrInvalidResetCode.

func (*PasswordPolicyError) Error

func (e *PasswordPolicyError) Error() string

type PasswordReset

type PasswordReset struct {
	UserID      string
	Code        string
	NewPassword string
}

PasswordReset is one redemption of a reset code. Every field is required.

type PasswordRule added in v1.0.0

type PasswordRule string

PasswordRule names one clause of the complexity policy. The values are the wire spelling the scaffolded frontend reads, so they are part of the contract between a broker and its sign-up form.

const (
	RuleMinLength PasswordRule = "min_length"
	RuleUppercase PasswordRule = "uppercase"
	RuleLowercase PasswordRule = "lowercase"
	RuleNumber    PasswordRule = "number"
	RuleSymbol    PasswordRule = "symbol"
)

type Registration

type Registration struct {
	Email      string
	Password   string
	GivenName  string
	FamilyName string
	// EmailVerified marks the address trusted without a mail round trip.
	EmailVerified bool
}

Registration is a new account's details, as a sign-up form collects them.

EmailVerified is deliberately a caller decision rather than a fixed value. A dev stack has no mail server, so an unverified address strands the account behind a verification step nothing can deliver — the exact dead end that makes a scaffolded sign-up feel broken. A production deployment with real mail should set it false and let the issuer send the verification.

type Session

type Session struct {
	ID    string `json:"sessionId"`
	Token string `json:"sessionToken"`
}

Session is an authenticated session at the issuer: the handle that FinalizeAuthRequest exchanges for an authorization code.

The token is a bearer credential for this session. It is returned so a caller can hold it across the two calls, and for no other reason — it must never be sent to a browser.

type Tokens

type Tokens struct {
	AccessToken  string `json:"access_token"`
	IDToken      string `json:"id_token"`
	RefreshToken string `json:"refresh_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
}

Tokens is what a completed flow yields.

These are the credentials themselves. They belong in a server-side session, or in an HttpOnly cookie — never in a JSON response a script can read, which would give away the property this whole file exists to establish.

type User

type User struct {
	ID string
	// LoginName is what CreateSession identifies the account by, and it is
	// NOT necessarily the email. An account created with a bare username
	// gets a login name of `<username>@<org domain>` — the seeded admin of
	// a forge dev IdP is `admin@<org>.localhost` while its email is the
	// address people actually type. Resolve through FindUserByEmail
	// rather than passing a typed email to CreateSession.
	LoginName string
	Email     string
}

User is the subset of an issuer account a sign-in or reset flow needs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL