Documentation
¶
Overview ¶
Package auth implements authentication and authorization primitives: PAT and session token handling, PAT scopes, sealing of small secrets, and the single authorization chokepoint. People sign in through an OpenID provider; the server stores no password and no second factor of its own.
Index ¶
- Constants
- Variables
- func Check(p *Principal, res Resource, act Action) error
- func CheckAgent(p *Principal, res AgentResource, act Action) error
- func ClientIPFrom(ctx context.Context) string
- func DisplayPrefix(token string) string
- func HasScope(scopes []string, s Scope) bool
- func HashToken(token string) []byte
- func HoldPermits(act Action) bool
- func IsPAT(token string) bool
- func NewToken(prefix string) (string, error)
- func ParseSSHPublicKey(line string) (keyType, canonical, fingerprint string, err error)
- func ReadOnly(act Action) bool
- func ScheduleScopes() []string
- func SignInGrantScopes() []string
- func SyntheticAddress(email string) bool
- func Unactivated(emailVerifiedAt *time.Time, email string) bool
- func ValidAgentRole(r AgentRole) bool
- func ValidScope(s Scope) bool
- func WithClientIP(ctx context.Context, ip string) context.Context
- type Action
- type AgentResource
- type AgentRole
- type OrgRole
- type Principal
- type Resource
- type Scope
- type ScopeError
- type Sealer
Constants ¶
const ( PATPrefix = "agy_" SessionPrefix = "agys_" // InvitePrefix marks an organization invitation token. // It is a credential like the others: shown once, stored as its hash. InvitePrefix = "agyi_" VerificationPrefix = "agyv_" // TrustedDevicePrefix marks the cookie a browser earns by answering the // second factor at a directory, so a later sign-in from it skips the code. // A distinct prefix so a leaked string identifies itself // as a 30-day browser credential rather than a session or a PAT. TrustedDevicePrefix = "agyd_" // PATDisplayPrefixLen is how many characters of a PAT are stored and // shown for identification (pats.token_prefix). PATDisplayPrefixLen = 12 )
Token kinds and their prefixes. PATs use `agy_`, registered with secret scanners (S2 ships a matching rule). Sessions and verification tokens get distinct prefixes so leaked strings identify themselves.
const SyntheticAddressSuffix = ".social.local"
SyntheticAddressSuffix ends the address a social sign-in with no email is given (handlers_social_login.go): a placeholder that keeps the users table's NOT NULL/UNIQUE contract and was never anybody's mailbox.
Variables ¶
var ( ErrForbidden = errors.New("forbidden") )
ErrUnauthorized means "no valid credential" (401); ErrForbidden means "credential valid, permission denied" (403). Handlers map them to problems.
var SSHKeyScopes = []string{string(ScopeRepoRead), string(ScopeRepoWrite), string(ScopeAgentPublish)}
SSHKeyScopes is what an SSH key is worth: the repository transport and the release tag it may create when the role allows; never the API.
Functions ¶
func Check ¶
Check is the single authorization chokepoint: every handler calls it with its declared action. It never consults anything but the principal and the resource — no ambient state.
func CheckAgent ¶
func CheckAgent(p *Principal, res AgentResource, act Action) error
CheckAgent is the chokepoint for agent-scoped actions. Public agents are readable by anyone (including anonymous); everything else needs the role threshold and, for PATs and schedule credentials, the matching scope.
func ClientIPFrom ¶
ClientIPFrom returns the address WithClientIP recorded, or "".
func DisplayPrefix ¶
DisplayPrefix returns the identifying prefix of a PAT for UI/lookup.
func HasScope ¶
HasScope reports whether the scope set includes s. Broader scopes do not imply narrower ones in v1 — the list is flat by design (simple to audit).
func HashToken ¶
HashToken returns the sha256 of the full token string — the only form stored at rest.
func HoldPermits ¶
HoldPermits reports whether an organization in its decommission hold still permits the action (members keep read and export): the reads, and a member leaving, since a person belongs to one organization at a time and must not be held in one on its way out. Everything else changes something the hold has frozen.
func ParseSSHPublicKey ¶
ParseSSHPublicKey validates an authorized_keys-style line and returns the key type, the canonical "type base64" form and the SHA256 fingerprint.
func ReadOnly ¶
ReadOnly reports whether an action only reads. The audit export creates a job, but what it produces is the organization's own record.
func ScheduleScopes ¶
func ScheduleScopes() []string
ScheduleScopes are the scopes a schedule's credential carries: what one autonomous run of a QuickAgent needs and nothing more — read the agent, start and read the run, and attach the owner's knowledge and Writing Voice the schedule names. No write to knowledge, voice or the vault, no repository access and nothing administrative: a schedule starts a run, it does not change what the run reads. Fresh on every call, so no caller can widen another's set.
func SignInGrantScopes ¶
func SignInGrantScopes() []string
SignInGrantScopes is the scope set the desktop app's and the CLI's sign-in grant mints: browse and install (agent:read, repo:read), Build → publish (agent:publish, repo:write), identity (user:profile), and hosted runs — In Agentry on RunPanel (run:read, run:write), the Knowledge panel's packs and their keys (knowledge:read, knowledge:write), and the hosted-run start's secrets, set and deleted, never read (secret:write), and the account's Writing Voice, read, uploaded and downloaded (voice:read, voice:write), and the owner actions on the person's own QuickAgents and their organizations' where they are an admin (agent:manage), and connecting a vendor whose token endpoint needs a client secret through the registry (connection:broker). Deliberately no review:act and no org scopes. Fixed server-side so a caller of the grant endpoint cannot widen it, and shown verbatim on the approval page.
func SyntheticAddress ¶
SyntheticAddress reports the placeholder address of an account that signed in without one.
func Unactivated ¶
Unactivated reports whether an account is unactivated: its address is unconfirmed and is a real address a link can be sent to. An account with only a synthetic placeholder has nothing to activate, so it is never locked into read-only by a mail it cannot receive; the gates that need a verified address (publishing, organizations) still refuse it.
func ValidAgentRole ¶
ValidAgentRole reports whether r is a grantable role. AgentRoleAdmin is deliberately absent: an organization decides who administers its agents through its own roles, and a grant on one agent must not be a way to hand that out.
func ValidScope ¶
ValidScope reports whether s is in the closed scope list.
func WithClientIP ¶
WithClientIP records the caller's resolved address on the context. The API middleware sets it exactly once, after the X-Forwarded-For trust decision, so every consumer — rate limiting, audit, the registry's IP-cluster hash — sees the same value.
Types ¶
type Action ¶
type Action string
Action is a declared (resource, action) pair the chokepoint understands. Every API route declares exactly one; the authorization matrix test enumerates this list against every role.
const ( ActAgentCreate Action = "agent.create" // authed; org ns needs admin+ ActAgentRead Action = "agent.read" // registry metadata/resolve; public agents anonymous ActAgentRepoRead Action = "agent.repo.read" // git clone/fetch ActAgentRepoWrite Action = "agent.repo.write" // git push ActAgentMaintain Action = "agent.maintain" // settings ActAgentPublish Action = "agent.publish" // v* tags, submit, yank // ActAgentAdminister is what only the namespace's own administrators // may do: delete the agent, change whether the world can see it, hand // out grants on it, and let it skip the pipeline. Separate from // maintain because an organization's members outrank maintain and // must not inherit these. ActAgentAdminister Action = "agent.administer" // ActAgentManage is the owner actions: making the agent public or // private, retiring, restoring and deleting it. The same rung as // ActAgentAdminister, but a token may take it with agent:manage as // well as org:admin, so the sign-in grant reaches these four and // still none of the agent's settings or grants. ActAgentManage Action = "agent.manage" )
Agent-scoped actions. Declared like every other action. Transport (git) and registry surfaces are distinct actions because they map to different PAT scopes (repo:* vs agent:*).
const ( // Org-scoped. ActOrgRead Action = "org.read" // public profile: anonymous ok ActOrgUpdate Action = "org.update" // admin+ ActOrgMembersRead Action = "org.members.read" // member+ (any role) ActOrgMembersManage Action = "org.members.manage" // admin: member/security_reviewer roles ActOrgMembersElevate Action = "org.members.elevate" // admin: grant/revoke admin ActOrgTeamsRead Action = "org.teams.read" // member+ ActOrgTeamsManage Action = "org.teams.manage" // admin+ ActOrgAuditRead Action = "org.audit.read" // admin+ ActOrgSettingsManage Action = "org.settings.manage" // admin (enforced SSO, policy) // ActOrgBrandingManage sets or removes the organization's logo. ActOrgBrandingManage Action = "org.branding.manage" // admin // ActOrgInvitationsManage is the invitation door: send, // list and revoke. Declared apart from members.manage because an // invitation reserves a seat before any membership exists. ActOrgInvitationsManage Action = "org.invitations.manage" // admin // ActOrgDecommission ends the organization: admin, // session only — a token never decides that an organization goes. ActOrgDecommission Action = "org.decommission" // ActOrgLeave is a member ending their own membership: a person // belongs to one organization at a time, so they must be able to leave // the one they hold. The last-admin guard applies. ActOrgLeave Action = "org.leave" // Self-scoped (resource is the caller's own account). ActUserSelfRead Action = "user.self.read" ActUserSelfUpdate Action = "user.self.update" ActUserTokensRead Action = "user.tokens.read" ActUserTokensManage Action = "user.tokens.manage" // session-only (a PAT cannot mint or revoke PATs) ActUserSecurityManage Action = "user.security.manage" // session-only: logout, sessions, remembered browsers // ActUserOrgRequest asks the administrators of the organization at the // caller's email domain for access: session only, since // it mails people on the caller's behalf. ActUserOrgRequest Action = "user.org.request" // Org creation (no target org yet). ActOrgCreate Action = "org.create" // Anonymous-capable reads. ActPublicRead Action = "public.read" // The caller's own knowledge packs: self-scoped, since a pack is found // only by its owner. // Read covers the packs, their reports and trees, the export and // having a data key unwrapped; write covers the rest. ActKnowledgeRead Action = "knowledge.read" ActKnowledgeWrite Action = "knowledge.write" // An organization's shared knowledge: org-scoped, so membership is // checked at every call through the roles the request resolved. Read covers the packs, // their trees, the meter and having a data key unwrapped, for any // active member; write covers the rest, for its admins. Exporting is // a read an admin may always make and a member only once the pack is // marked exportable, which the handler decides with the pack in hand. ActOrgKnowledgeRead Action = "org.knowledge.read" ActOrgKnowledgeWrite Action = "org.knowledge.write" // admin // An organization's house report designs: org-scoped, so membership // is checked at every call through the roles the request resolved. // Read covers the library and each design with its images, for any // active member, since a member's run picks one; write covers the // rest, for its admins, since a house design is the organization's. ActOrgReportDesignsRead Action = "org.report_designs.read" ActOrgReportDesignsWrite Action = "org.report_designs.write" // admin // The caller's own Writing Voice: self-scoped, since a voice is found // only by its owner. // Read covers every version's text and review; write covers the rest. ActVoiceRead Action = "voice.read" ActVoiceWrite Action = "voice.write" // ActReviewAct is the review surface (review:act). Check only // enforces the PAT scope gate for it: WHO may review — platform staff or // an org security_reviewer who is not the version's author — is a // per-item judgement the handler makes with the review item in hand. ActReviewAct Action = "review.act" )
Actions are only ever appended; an id is never reused.
type AgentResource ¶
type AgentResource struct {
Public bool
// EffectiveRole = max(namespace-derived, user grant, team grants),
// computed by registry.EffectiveAgentRole.
EffectiveRole AgentRole
}
AgentResource describes the agent an action targets, resolved by the caller (API/gitsrv) from the database: the caller's effective role plus the agent's visibility.
type AgentRole ¶
type AgentRole string
AgentRole is a per-agent level: read < write < maintain < publish < admin. AgentRoleNone means no access (private agents deny by default).
The top of the ladder is not grantable (ValidAgentRole): it is derived from the namespace alone. Everything below it is about an agent's *content* — reading it, pushing to it, releasing it — and can sensibly be handed to a collaborator. AgentRoleAdmin is about the agent's *existence and exposure*: deleting it, changing whether the world can see it, handing out access to it. An organization's members hold publish on its agents, so those acts need a level above publish rather than below it, or every member would inherit them: only admins change visibility, transfer or delete.
const ( AgentRoleNone AgentRole = "" AgentRoleRead AgentRole = "read" AgentRoleWrite AgentRole = "write" AgentRoleMaintain AgentRole = "maintain" AgentRolePublish AgentRole = "publish" // AgentRoleAdmin is derived, never granted: the namespace's own people. AgentRoleAdmin AgentRole = "admin" )
Agent roles in ascending order.
func MaxAgentRole ¶
MaxAgentRole returns the higher of two agent roles.
func NamespaceDerivedAgentRole ¶
func NamespaceDerivedAgentRole(p *Principal, namespaceKind string, namespaceID uuid.UUID, orgRole OrgRole) AgentRole
NamespaceDerivedAgentRole computes the implicit role a caller holds on an agent from its namespace, before explicit grants:
- personal namespace: the owning user administers their own agents;
- org namespace: an org admin administers them, and an org **member** may release them (publish) — a seat buys a share of the organization's agents, which is what an organization is for, while what the agent *is* stays the admins';
- everyone else: none (explicit grants only).
A pending member holds nothing, and needs no case here: a membership that is not active never reaches Principal.OrgRoles, so they arrive as RoleNone like any outsider.
type OrgRole ¶
type OrgRole string
OrgRole is an organization role, ordered admin > security_reviewer | member (there is no owner role and none above admin, and the last admin can only leave through a decommission). security_reviewer is a platform-internal role that exists only inside a first-party organization; in every other organization the admins hold its powers. The empty string means "not a member".
type Principal ¶
type Principal struct {
// Anonymous is true when no credential was presented.
Anonymous bool
UserID uuid.UUID
Handle string
// Via is "session", "pat" or "ssh" (git over SSH), or
// "user": a principal the core loaded for an account with no
// credential, for an extension to ask about a user it holds by id. A
// "user" principal carries the account's roles and no scopes; it
// passes no session-only route and satisfies no enforced SSO.
// "schedule" is the credential of a run a schedule starts on its
// owner's behalf with no live request: the core mints it for an
// extension (extension.ScheduleCredentials.ForSchedule), it carries
// ScheduleScopes and the schedule's id, every scope gate reads it as
// it reads a token's (ScopeBound), and it is never presented over
// HTTP.
// "extension" is a bearer token an extension minted for its own routes
// (pkg/extension.TakesOwnTokens): the middleware accepts it only under
// that extension's mount, it carries no scopes and no roles, and every
// scope gate reads it as scope-bound, so it can do nothing in the core.
Via string
// Scopes holds a PAT's scopes, or a schedule's ScheduleScopes; nil
// for sessions.
Scopes []string
// OrgRoles maps org id → role for the caller's memberships.
OrgRoles map[uuid.UUID]OrgRole
// EmailVerified gates publishing flows.
EmailVerified bool
// Unactivated marks an account whose address has not been confirmed
// and can be: it may read, but every write outside a short list of
// its own housekeeping is refused until it follows the activation
// link. See Unactivated.
Unactivated bool
// PlatformStaff marks trust & safety operators (SaaS platform roles;
// self-host: the instance admin). Gates the platform review queue and
// quarantine/block actions.
PlatformStaff bool
// SessionID / PATID / SSHKeyID / ScheduleID identify the credential
// for audit; ScheduleID is the schedule's id in the extension that
// owns schedules, and the core holds no row for it.
SessionID uuid.UUID
PATID uuid.UUID
SSHKeyID uuid.UUID
ScheduleID uuid.UUID
// SSOFresh maps org id → the moment SSO was last asserted for this
// session (enforced SSO; from sessions.sso_tags). Sessions only.
SSOFresh map[uuid.UUID]time.Time
// PATOrgID is the org a PAT is bound to (pats.org_id): a PAT minted under
// an SSO-fresh session. uuid.Nil for personal PATs and sessions.
PATOrgID uuid.UUID
}
Principal is the resolved caller identity for one request.
func ResolvePAT ¶
ResolvePAT authenticates a presented PAT string against the store and builds the Principal (shared by the API middleware and the git layer).
func ResolveSSHKey ¶
func ResolveSSHKey(ctx context.Context, q *storegen.Queries, fingerprint string) (*Principal, error)
ResolveSSHKey builds the Principal for a presented SSH public key by its fingerprint. Via is "ssh": an SSH key is never org-bound, so SSOSatisfied is false and an enforced-SSO org's push stays HTTPS-with-org-bound-PAT only.
func (*Principal) CreditsOnly ¶ added in v0.7.0
CreditsOnly reports whether the principal is a token minted with ScopeCreditsSession, which carries no other scope: it may open, renew and end a credits session on the routes an extension declares for them and is refused everywhere else, the anonymous reads included.
func (*Principal) SSOSatisfied ¶
SSOSatisfied reports whether the caller meets an org's enforced-SSO requirement: a session must carry an sso tag for the org refreshed within maxAge; a PAT must be bound to the org. Anonymous callers and non-enforcing orgs are decided by the RBAC chokepoint, not here.
func (*Principal) ScopeBound ¶
ScopeBound reports whether the principal acts only within its Scopes: a token, a schedule's credential, or an extension's own token. A session carries the account's full authority instead, and a "user" principal is no caller at all. Every scope gate asks this rather than naming "pat", so a credential minted with a fixed scope set is never read as a session.
type Resource ¶
Resource identifies what an action targets. OrgID is set for org-scoped actions; self-scoped actions carry nothing (the principal is the target).
type Scope ¶
type Scope string
Scope is a PAT permission scope. Sessions carry no scopes: a browser session acts with the user's full authority (mutations gated by CSRF); PATs are least-privilege credentials.
const ( ScopeRepoRead Scope = "repo:read" ScopeRepoWrite Scope = "repo:write" ScopeAgentPublish Scope = "agent:publish" ScopeAgentRead Scope = "agent:read" // ScopeAgentManage lets a token take the owner actions on // a QuickAgent it administers: make it public or private, retire, // restore and delete it. It is narrower than org:admin, which also // covers these: it reaches no other setting of the agent, no grant on // it and no organization route. It changes no rung, so the caller must // still be the namespace itself or one of its organization's admins. ScopeAgentManage Scope = "agent:manage" ScopeOrgAdmin Scope = "org:admin" ScopeReviewAct Scope = "review:act" ScopeAuditRead Scope = "audit:read" ScopeUserProfile Scope = "user:profile" // The hosted-run scopes: a token that may start, cancel and feed a // hosted run of a QuickAgent (run:write) or read a run, its log and // its artefacts (run:read). No core route consumes them; the hosted // runs extension requires them through pkg/extension, so a registry // without it treats a token carrying only these as a token with no // scope at all. ScopeRunRead Scope = "run:read" ScopeRunWrite Scope = "run:write" // The knowledge scopes: a token that may read the caller's knowledge // packs, their scan reports and their trees and have a pack's data key // unwrapped (knowledge:read), or create, upload, delete and wrap // (knowledge:write). ScopeKnowledgeRead Scope = "knowledge:read" ScopeKnowledgeWrite Scope = "knowledge:write" // The vault scope: a token that may set and delete the caller's // hosted-run secrets and never list or read one. No core route // consumes it; the hosted vault requires it through pkg/extension, and // keeps its list for a session alone. ScopeSecretWrite Scope = "secret:write" // The voice scopes: a token that may read the caller's Writing Voice, // every version's text and review (voice:read), or put, restore, set // and delete it (voice:write). ScopeVoiceRead Scope = "voice:read" ScopeVoiceWrite Scope = "voice:write" // ScopeCreditsSession lets a token open, renew and end a credits // session, which pays for a run's model with the account's credits, // and do nothing else: it reads no account data and starts no run. // It is what a machine that runs the person's work unattended holds // in place of an account-wide sign-in. No core route consumes it; the // credits extension requires it through pkg/extension, so a registry // without that extension treats a token carrying only this as a token // with no scope at all. ScopeCreditsSession Scope = "credits:session" // ScopeConnectionBroker lets a token start a sign-in that the registry // completes for a vendor whose token endpoint needs a client secret, // collect its result, refresh that connection and revoke it, and do // nothing else: the connection stays on the person's machine, and the // registry adds the deployment's secret to each exchange and keeps // nothing. No core route consumes it; the vault extension requires it // through pkg/extension, so a registry without that extension treats a // token carrying only this as a token with no scope at all. ScopeConnectionBroker Scope = "connection:broker" )
The closed v1 scope list.
type ScopeError ¶ added in v0.7.9
type ScopeError struct {
Scopes []Scope
}
ScopeError is a forbidden answer whose cause is a token that lacks the scope the action needs: any one of Scopes admits it. errors.Is(err, ErrForbidden) holds for it, so a caller that only maps 403 needs nothing new; one that can name the scope finds it with errors.As.
func (*ScopeError) Error ¶ added in v0.7.9
func (e *ScopeError) Error() string
func (*ScopeError) Unwrap ¶ added in v0.7.9
func (e *ScopeError) Unwrap() error
Unwrap makes a ScopeError an ErrForbidden.
type Sealer ¶
type Sealer struct {
// contains filtered or unexported fields
}
Sealer encrypts small secrets at rest (for example webhook secrets and sign-in state). AES-256-GCM with a key from configuration; SaaS wraps the key with KMS (envelope encryption is an operational concern, not a code path change).
func NewSealer ¶
NewSealer builds a Sealer from a base64 key (32 bytes decoded). An empty key is only permitted in dev, where a fixed insecure key keeps local setups friction-free; config validation rejects that in prod.
func (*Sealer) For ¶
For is a sealer under a key of its own, derived from this one's for one purpose (HKDF-SHA256). What it seals this sealer cannot open, nor can a sealer for another purpose, and it opens nothing they sealed: the server hands one to each extension, so an extension's values and the server's own (webhook secrets, sign-in state) never share a key.
func (*Sealer) MAC ¶ added in v0.6.1000
MAC is HMAC-SHA256 of msg under a key derived from this sealer's for one purpose (HKDF-SHA256), distinct from every sealing key For derives: a value keyed this way can be compared to another keyed the same way, and cannot be turned back into msg without the server's sealing key.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package oidc implements the OpenID Connect Relying Party side of sign-in through an OpenID provider: authorization-code flow with PKCE, issuer pinning (the discovery document's issuer must match the configured issuer), and email_verified respected.
|
Package oidc implements the OpenID Connect Relying Party side of sign-in through an OpenID provider: authorization-code flow with PKCE, issuer pinning (the discovery document's issuer must match the configured issuer), and email_verified respected. |
|
Package social implements sign-in for individual accounts through the deployment's OpenID provider (linked via identities; no password), on the relying party in internal/auth/oidc.
|
Package social implements sign-in for individual accounts through the deployment's OpenID provider (linked via identities; no password), on the relying party in internal/auth/oidc. |