auth

package
v0.17.0 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: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AudienceAuth        = "auth"
	AudienceBilling     = "billing"
	AudienceSnapDB      = "snapdb-api"
	AudienceLangsync    = "langsync-api"
	AudienceDomainradar = "domainradar"
	AudiencePrompthub   = "prompthub"
)

Audience names recognized by the auth service. These match the constants in apps/auth/internal/handler/user/user.go.

View Source
const DefaultLockTimeout = 30 * time.Second

DefaultLockTimeout is how long a command waits for another norcube process to finish refreshing the session.

View Source
const SignOutTimeout = 10 * time.Second

SignOutTimeout bounds the server call made by `norcube logout`: logging out must not hang on a slow or unreachable server.

Variables

View Source
var ErrLoginRequired = errors.New("not signed in or session expired")

ErrLoginRequired marks auth failures that a fresh `norcube login` fixes: no refresh token in the keyring, or the server rejecting the one we have (revoked / fully expired). main() detects it with errors.Is and prints the re-login hint once, instead of every command growing its own.

View Source
var ErrNotLoggedIn error = notLoggedIn{}

ErrNotLoggedIn: the profile has no session at all. It also matches ErrLoginRequired, so callers that only care about "a login fixes it" need one check.

View Source
var ErrOrgAccessDenied = errors.New("organization access denied")

ErrOrgAccessDenied: the session is fine, but the user may not act in the requested organization (not a member, or no such organization). Match it with errors.Is; the error itself is an *OrgAccessError.

View Source
var ErrSecretNotFound = credstore.ErrNotFound

ErrSecretNotFound is returned by Store.Get for a missing key.

Functions

func AccessExpiry added in v0.16.0

func AccessExpiry(profile, api, audience, orgID string) time.Time

AccessExpiry returns when the profile's cached token for (audience, org) expires; zero when none is cached.

func DeleteCredentials added in v0.16.0

func DeleteCredentials(profile, api string) error

DeleteCredentials removes everything stored for the profile, including the default profile's pre-profiles refresh token for api (so it isn't adopted again).

func DeleteCredentialsFrom added in v0.16.0

func DeleteCredentialsFrom(s Store, profile, api string) error

DeleteCredentialsFrom is DeleteCredentials on a given store.

func EndServerSession added in v0.16.0

func EndServerSession(ctx context.Context, client *http.Client, authURL, refreshToken string) error

EndServerSession ends the CLI session behind refreshToken on Norcube Auth (POST /auth/cli/sign-out), so its refresh token stops working everywhere at once. The endpoint answers 204 for a live, an already ended or an unknown token alike; anything else is an error. Callers hold the profile's refresh lock, so no refresh can rotate the token mid-call.

func HasCredentials added in v0.16.0

func HasCredentials(profile, api string) bool

HasCredentials reports whether the profile has a session for api.

func LoadRefreshToken

func LoadRefreshToken(profile, api string) (string, error)

LoadRefreshToken returns the profile's refresh token for api, or ErrNotLoggedIn.

func LockProfile added in v0.16.0

func LockProfile(ctx context.Context, dir, profile, api string, timeout time.Duration) (func(), error)

LockProfile takes the cross-process lock that serializes every change to a profile's credentials for api (refreshes, login, logout). dir empty means locks/ next to the config file; timeout <= 0 means DefaultLockTimeout. Call the returned function to release it.

func SaveAccessTokenUntil added in v0.16.0

func SaveAccessTokenUntil(profile, api, audience, orgID, token string, expiresAt time.Time) error

SaveAccessTokenUntil caches token as valid until expiresAt. A zero expiresAt falls back to the token's exp claim.

func SaveRefreshToken

func SaveRefreshToken(profile, api, token string) error

SaveRefreshToken stores the profile's refresh token for api. Cached access tokens of another auth URL are dropped.

func UseStore added in v0.16.0

func UseStore(profile string, s Store)

UseStore makes profile keep its credentials in s instead of the default store (a profile with credential_store = "file"). nil restores the default.

Types

type BrowserLoginOptions

type BrowserLoginOptions struct {
	WebApp         string        // base URL of the web app, e.g. https://app.norcube.com
	Timeout        time.Duration // how long to wait for the user to complete the flow
	BrowserOpenURL func(string) error
	OnURLReady     func(string) // called with the URL just before opening the browser, for printing
	// NoBrowser skips opening a browser: the caller prints the URL (via
	// OnURLReady) for the user to open anywhere, e.g. over SSH.
	NoBrowser bool
}

BrowserLoginOptions configures BrowserLogin.

type CallbackPayload

type CallbackPayload struct {
	State            string       `json:"state"`
	AccessToken      string       `json:"accessToken"`
	RefreshToken     string       `json:"refreshToken"`
	AccessExpiresIn  int          `json:"accessExpiresIn"`
	RefreshExpiresIn int          `json:"refreshExpiresIn"`
	User             User         `json:"user"`
	DefaultOrg       Organization `json:"defaultOrganization"`
}

CallbackPayload is what the /cli-login frontend page POSTs to our loopback server. Field names mirror the JSON shape returned by /auth/cli/exchange, passed through unchanged by the page.

func BrowserLogin

func BrowserLogin(ctx context.Context, opts BrowserLoginOptions) (*CallbackPayload, error)

BrowserLogin runs the full browser-based login handshake:

  1. Bind a loopback HTTP server on a random localhost port.
  2. Open the user's browser to <WebApp>/cli-login?port=<P>&state=<S>.
  3. Wait for the page to POST {state, tokens...} to http://127.0.0.1:P/callback.
  4. Validate state, return the payload.

The caller is responsible for persisting the returned tokens.

type OrgAccessError added in v0.16.0

type OrgAccessError struct{ Org string }

OrgAccessError reports which organization was refused.

func (*OrgAccessError) Error added in v0.16.0

func (e *OrgAccessError) Error() string

func (*OrgAccessError) Is added in v0.16.0

func (e *OrgAccessError) Is(target error) bool

type Organization

type Organization struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Slug string `json:"slug"`
}

type SessionState added in v0.16.0

type SessionState string

SessionState is what Norcube Auth says about a profile's stored session.

const (
	// SessionActive: the session refreshes, or a token minted from it a
	// few minutes ago is still cached.
	SessionActive SessionState = "active"
	// SessionEnded: Norcube Auth refused the session: revoked (from the
	// dashboard or another `logout`), replayed, or unused for too long.
	SessionEnded SessionState = "ended"
	// SessionNone: nothing is stored for the profile.
	SessionNone SessionState = "none"
	// SessionUnknown: Norcube Auth couldn't be asked (network, timeout).
	SessionUnknown SessionState = "unknown"
)

type Store added in v0.16.0

type Store = credstore.Store

Store is where credentials are kept. The OS keyring by default.

func SetStore added in v0.16.0

func SetStore(s Store) Store

SetStore replaces the default credential store and returns the previous one.

type TokenSource

type TokenSource struct {
	// Profile names whose credentials are used ("" is the default profile).
	Profile  string
	APIBase  string
	Audience string
	OrgID    string
	HTTP     *http.Client

	// Static, when set, is returned as the token for every request and
	// nothing is exchanged or stored (NORCUBE_TOKEN, --token-file).
	Static string

	// ProbeOrgID is an organization the user is known to belong to (the
	// active org). When an exchange for OrgID is refused, one exchange for
	// ProbeOrgID tells "signed out" apart from "not a member of OrgID",
	// which Norcube Auth answers with the same 401.
	ProbeOrgID string
	// OrgLabel names OrgID in error messages (its slug); defaults to the id.
	OrgLabel string

	// LockDir holds the cross-process refresh lock files. Empty means
	// locks/ next to the config file.
	LockDir string
	// LockTimeout bounds the wait for another process's refresh.
	LockTimeout time.Duration
	// contains filtered or unexported fields
}

TokenSource returns a valid Bearer access token for a (audience, organization) pair, refreshing it via /oauth/token when necessary. It is the single place the rest of the CLI should ask for "give me a token I can use right now."

It is safe for concurrent use, and refreshes are serialized across processes too: the server rotates the refresh token on every exchange and rejects the old one, so two exchanges racing with the same refresh token would sign the user out.

func NewTokenSource

func NewTokenSource(apiBase, audience, orgID string) *TokenSource

func (*TokenSource) BearerInjector

func (t *TokenSource) BearerInjector() func(ctx context.Context, req *http.Request) error

BearerInjector returns a request editor that injects a fresh access token into each outgoing request. Every generated API client shares this, so token acquisition lives in exactly one place.

func (*TokenSource) CheckSession added in v0.16.0

func (t *TokenSource) CheckSession(ctx context.Context) (SessionState, error)

CheckSession reports whether the profile's stored session still works, by getting a token for t.Audience and t.OrgID. A cached access token that hasn't expired counts as active without a request: it was minted from this session within the last few minutes, and asking again would rotate the refresh token for nothing. Otherwise it costs one refresh, under the usual locks. The error explains SessionUnknown and is nil otherwise.

func (*TokenSource) Token

func (t *TokenSource) Token(ctx context.Context) (string, error)

Token returns a valid access token, minting one via /oauth/token if no cached token exists or the cached token is close to expiring.

Side effect: when /oauth/token returns a rotated refresh token, the keyring-stored refresh token is updated in place. This keeps the CLI logged in indefinitely as long as the user runs `nrc` at least once per refresh-token TTL — the rotation pushes the expiry forward on each exchange. The user only sees `nrc login --force` again if they stay completely inactive for the full TTL window.

type User

type User struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Email     string `json:"email"`
	AvatarURL string `json:"avatarUrl"`
}

Jump to

Keyboard shortcuts

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