Documentation
¶
Index ¶
- Constants
- Variables
- func AccessExpiry(profile, api, audience, orgID string) time.Time
- func DeleteCredentials(profile, api string) error
- func DeleteCredentialsFrom(s Store, profile, api string) error
- func DescribeScopes(granted []string) string
- func EndServerSession(ctx context.Context, client *http.Client, authURL, refreshToken string) error
- func ForgetMetadata(authURL string)
- func HasCredentials(profile, api string) bool
- func IsCIToken(s string) bool
- func LimitedScopes(granted []string) []string
- func LoadRefreshToken(profile, api string) (string, error)
- func LockProfile(ctx context.Context, dir, profile, api string, timeout time.Duration) (func(), error)
- func LoginScopeNames() []string
- func ParseLoginScopes(values []string) ([]string, error)
- func RevokeRefreshToken(ctx context.Context, httpc *http.Client, authURL, refreshToken string) error
- func SaveAccessTokenUntil(profile, api, audience, orgID, token string, expiresAt time.Time) error
- func SaveOAuthSession(profile, api, refresh, cliAccess string, accessExpiresAt time.Time, ...) error
- func SaveRefreshToken(profile, api, token string) error
- func ScopesFull(granted []string) bool
- func ServiceName(audience string) string
- func UseStore(profile string, s Store)
- func ValidateCIToken(s string) error
- type BrowserLoginOptions
- type CIExchanger
- type CIGrant
- type CIScopeAudience
- type CallbackPayload
- type DeviceCode
- type DeviceLoginOptions
- type LoginScope
- type Metadata
- type OAuthError
- type OAuthLoginOptions
- type OrgAccessError
- type Organization
- type ScopeError
- type SessionState
- type Store
- type StoredSession
- type TokenSource
- type User
Constants ¶
const ( FormatLegacy = 1 FormatOAuth = 2 )
Credential formats. Format 1 (no "format" field) is the older sign-in: a refresh JWT of Norcube Auth's own sessions, refreshed straight into per-(audience, organization) tokens, which are cached in the blob too. Format 2 is the OAuth sign-in: the grant's refresh token, the cached 5-minute CLI access token and the granted scopes. Its per-service tokens are only cached in memory (see oauthsession.go), so the blob changes only on a refresh, under the profile's lock.
const ( ScopeFull = "full" ScopeOrgRead = "org.read" ScopeOfflineAccess = "offline_access" )
Scopes of a CLI sign-in. A sign-in has full access (everything the person can do in the dashboard) unless `login --scopes` named a subset. Norcube Auth always adds org.read (the account and its organizations) and keeps offline_access (the refresh token); the person's own permissions apply on every call either way.
const ( AudienceAuth = "auth" AudienceBilling = "billing" AudienceSnapDB = "snapdb-api" AudienceLangsync = "langsync-api" AudienceDomainradar = "domainradar" AudiencePrompthub = "prompthub" AudienceCMS = "cms-api" AudienceMonitor = "monitor" )
Audience names recognized by the auth service. These match the constants in apps/auth/internal/handler/user/user.go.
const (
CITokenPrefix = "nrc_ci_"
)
CI tokens are organization-scoped secrets for automation, created under IAM › CI tokens in the dashboard or with `norcube auth ci-token create`. They act as a service principal of one organization, not as a person, and are exchanged at Norcube Auth for short-lived access tokens, one per service. Nothing is stored: the CLI keeps the access tokens in memory for the life of the process.
The format is `nrc_ci_` + 32 base62 characters + a 6-character base62 CRC32 (IEEE) of those 32, the scheme GitHub uses so secret scanners can recognize leaks and typos are caught before any request.
const ClientID = DeviceClientID
ClientID is the CLI's OAuth client id.
const DefaultLockTimeout = 30 * time.Second
DefaultLockTimeout is how long a command waits for another norcube process to finish refreshing the session.
const DeviceClientID = "norcube-cli"
DeviceClientID identifies the CLI to Norcube Auth's device endpoints.
const SignInWait = 10 * time.Minute
SignInWait is how long a sign-in waits for the browser: as long as Norcube Auth keeps the pending request (10 minutes), so an approval the server still accepts always finds the CLI listening.
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 ¶
var ( ErrDeviceDenied = errors.New("the sign-in was denied on the approval page") ErrDeviceExpired = errors.New("the code expired before it was approved") )
Errors a device sign-in ends with. Both mean the person is still not signed in, so they map to exit code 4.
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.
var ErrMalformedCIToken = errors.New("malformed CI token")
ErrMalformedCIToken: the value starts like a CI token but its length, characters or checksum are wrong, almost always a copy-paste mistake.
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.
ErrOAuthUnavailable: Norcube Auth has no OAuth sign-in for the CLI (an older server, or the OAuth server is switched off). The CLI then uses the older sign-in.
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.
var ErrSecretNotFound = credstore.ErrNotFound
ErrSecretNotFound is returned by Store.Get for a missing key.
var LoginScopes = []LoginScope{ {ScopeFull, "Everything you can do in the dashboard (the default)"}, {"backup.read", "View backups: data sources, backup jobs, restore checks and policies"}, {"backup.write", "Run backups, plus everything backup.read allows"}, {"backup.verify", "Run restore checks, plus everything backup.read allows"}, {"domainradar.check", "Run single and bulk DomainRadar checks and read the results"}, {"langsync.read", "View namespaces, terms, translations, languages and the glossary"}, {"langsync.sync", "Run `langsync sync`: push source terms and pull translations"}, {"langsync.write", "Add and edit terms and translations, translate missing values"}, {"billing.read", "View billing status, usage, invoices and the subscription"}, {"cms.read", "View CMS sites, content, schema and media"}, {"cms.write", "Edit CMS content and media, plus everything cms.read allows"}, {"monitor.read", "View monitors, check results, uptime, incidents and alert channels"}, {"monitor.check", "Run a monitor's check now, plus everything monitor.read allows"}, {"monitor.write", "Create, change and delete monitors and acknowledge incidents, plus everything monitor.read allows"}, {"monitor.channels", "Create, change and delete alert channels and send test alerts, plus everything monitor.read allows"}, {"monitor.statuspages", "Create, publish and delete status pages and post incidents on them, plus everything monitor.read allows"}, {"monitor.maintenance", "Schedule, change and cancel maintenance windows, plus everything monitor.read allows"}, }
LoginScopes mirrors the scope catalog of Norcube Auth for CLI sign-ins, minus the two scopes every sign-in carries anyway (org.read, offline_access). The server is the authority: it refuses an unknown scope with invalid_scope. A well-formed scope missing here (one Norcube Auth added after this release) is still sent, so it only misses the description and completion.
Functions ¶
func AccessExpiry ¶ added in v0.16.0
AccessExpiry returns when the profile's cached token for (audience, org) expires; zero when none is cached.
func DeleteCredentials ¶ added in v0.16.0
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
DeleteCredentialsFrom is DeleteCredentials on a given store.
func DescribeScopes ¶ added in v0.26.0
DescribeScopes reads like "full" or "backup.read, backup.write".
func EndServerSession ¶ added in v0.16.0
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 ForgetMetadata ¶ added in v0.26.0
func ForgetMetadata(authURL string)
ForgetMetadata drops the cached discovery answer for authURL.
func HasCredentials ¶ added in v0.16.0
HasCredentials reports whether the profile has a session for api.
func IsCIToken ¶ added in v0.18.0
IsCIToken reports whether s has the CI token prefix. It says nothing about validity; see ValidateCIToken.
func LimitedScopes ¶ added in v0.26.0
LimitedScopes are a scoped sign-in's scopes as the person asked for them: without the implicit org.read and offline_access. Empty for a full sign-in.
func LoadRefreshToken ¶
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 LoginScopeNames ¶ added in v0.26.0
func LoginScopeNames() []string
LoginScopeNames lists the scopes `login --scopes` accepts.
func ParseLoginScopes ¶ added in v0.26.0
ParseLoginScopes validates the scopes given to `login --scopes` and returns the ones to ask for: the known ones in catalog order, then the well-formed ones this release doesn't know, as given (Norcube Auth decides on those). Nothing means full. org.read and offline_access are dropped (every sign-in carries them), and full absorbs the rest. A malformed scope is an error naming the valid ones.
func RevokeRefreshToken ¶ added in v0.26.0
func RevokeRefreshToken(ctx context.Context, httpc *http.Client, authURL, refreshToken string) error
RevokeRefreshToken signs an OAuth sign-in out on Norcube Auth (RFC 7009 revocation of its refresh token): the grant, its tokens and the CLI session end, also when the token was already rotated out. Norcube Auth answers 200 for unknown or already revoked tokens too; anything else is an error. Callers hold the profile's lock.
func SaveAccessTokenUntil ¶ added in v0.16.0
SaveAccessTokenUntil caches token as valid until expiresAt. A zero expiresAt falls back to the token's exp claim.
func SaveOAuthSession ¶ added in v0.26.0
func SaveOAuthSession(profile, api, refresh, cliAccess string, accessExpiresAt time.Time, scopes []string) error
SaveOAuthSession stores an OAuth sign-in (format 2) for the profile: its refresh token, the CLI access token that came with it and the granted scopes. It replaces whatever the profile had, older sign-in included. Callers hold the profile's lock.
func SaveRefreshToken ¶
SaveRefreshToken stores the profile's refresh token for api as an older (format 1) sign-in. Cached access tokens of another auth URL are dropped, and so is an OAuth sign-in it replaces.
func ScopesFull ¶ added in v0.26.0
ScopesFull reports whether a sign-in's granted scopes include full access. A sign-in without recorded scopes (the older sign-in) has full access too.
func ServiceName ¶ added in v0.26.0
ServiceName names an audience for messages.
func UseStore ¶ added in v0.16.0
UseStore makes profile keep its credentials in s instead of the default store (a profile with credential_store = "file"). nil restores the default.
func ValidateCIToken ¶ added in v0.18.0
ValidateCIToken checks a CI token's shape and checksum locally.
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 CIExchanger ¶ added in v0.18.0
type CIExchanger struct {
APIBase string
HTTP *http.Client
Secret string
// contains filtered or unexported fields
}
CIExchanger trades a CI token for access tokens at Norcube Auth (POST /auth/ci/token) and caches them per service in memory until shortly before they expire. It is safe for concurrent use.
func NewCIExchanger ¶ added in v0.18.0
func NewCIExchanger(apiBase, secret string) *CIExchanger
NewCIExchanger returns an exchanger for secret against Norcube Auth at apiBase.
type CIGrant ¶ added in v0.18.0
type CIGrant struct {
AccessToken string
ExpiresAt time.Time
Audience string
// Scopes the access token carries for this service.
Scopes []string
OrgID string
OrgSlug string
OrgName string
TokenID string
TokenName string
TokenExpiresAt time.Time
}
CIGrant is what an exchange returns: an access token for one service plus what the CI token is.
type CIScopeAudience ¶ added in v0.18.0
type CIScopeAudience struct {
Audience string `json:"audience" yaml:"audience"`
}
CIScopeAudience is set as clierr.Error.Details on an insufficient-scope refusal, naming the service the CI token has no scope for.
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"`
// OAuth marks a session from the OAuth sign-in (format 2): the access
// token is a CLI access token, User is empty (the caller asks
// /auth/me), and Scopes are the granted scopes.
OAuth bool `json:"-"`
Scopes []string `json:"-"`
}
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 older browser-based login handshake, for a Norcube Auth without the OAuth sign-in (see OAuthLogin):
- Bind a loopback HTTP server on a random localhost port.
- Open the user's browser to <WebApp>/cli-login?port=<P>&state=<S>.
- Wait for the page to POST {state, tokens...} to http://127.0.0.1:P/callback.
- Validate state, return the payload.
The caller is responsible for persisting the returned tokens.
func DeviceLogin ¶ added in v0.18.0
func DeviceLogin(ctx context.Context, opts DeviceLoginOptions) (*CallbackPayload, error)
DeviceLogin runs the whole device flow and returns the session, in the same shape a browser login delivers. Polling follows RFC 8628: never faster than the server's interval, 5 seconds slower after every slow_down, until the code expires. Network errors back off and retry within the code's lifetime. Cancelling ctx stops it (Ctrl-C); the pending request then simply expires on the server.
func OAuthLogin ¶ added in v0.26.0
func OAuthLogin(ctx context.Context, opts OAuthLoginOptions) (*CallbackPayload, error)
OAuthLogin signs in through the browser:
- Listen on 127.0.0.1 on a random port.
- Open the authorization endpoint with PKCE (S256), a random state, the scopes, and the device's name and User-Agent for the consent screen and the session.
- Norcube Auth redirects the browser to http://127.0.0.1:<port>/callback with a code, the state and its issuer (RFC 9207), all checked.
- Exchange the code with the PKCE verifier.
The caller stores the returned session.
type DeviceCode ¶ added in v0.18.0
type DeviceCode struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete"`
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval"`
}
DeviceCode is Norcube Auth's answer to a device sign-in request.
type DeviceLoginOptions ¶ added in v0.18.0
type DeviceLoginOptions struct {
AuthURL string
HTTP *http.Client
// Metadata selects the OAuth device flow (it must support it, see
// Metadata.SupportsDevice); nil means the older flow.
Metadata *Metadata
// Scopes to ask for in the OAuth flow; empty means full.
Scopes []string
// Hostname labels the session under Account › CLI sessions.
Hostname string
// OnCode is called once with the code to show the person.
OnCode func(DeviceCode)
// OnWait is called before every poll with the time left.
OnWait func(left time.Duration)
// contains filtered or unexported fields
}
DeviceLoginOptions configures DeviceLogin.
type LoginScope ¶ added in v0.26.0
LoginScope is a scope `login --scopes` accepts.
type Metadata ¶ added in v0.26.0
type Metadata struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
RevocationEndpoint string `json:"revocation_endpoint,omitempty"`
DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint,omitempty"`
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
CodeChallengeMethods []string `json:"code_challenge_methods_supported,omitempty"`
IssParameterSupported bool `json:"authorization_response_iss_parameter_supported,omitempty"`
}
Metadata is the part of Norcube Auth's RFC 8414 metadata the CLI uses.
func Discover ¶ added in v0.26.0
Discover returns Norcube Auth's metadata for authURL, or ErrOAuthUnavailable when the server has no OAuth sign-in for the CLI. Answers are cached (24 hours, one hour for "unavailable") in memory and in the user cache directory, so commands don't pay a request for it. Network failures are returned as they are and never cached.
func (*Metadata) SupportsCLISignIn ¶ added in v0.26.0
SupportsCLISignIn reports whether the server signs the CLI in through OAuth: it advertises the token exchange the CLI needs for every command. Older servers don't, and the CLI keeps their older sign-in.
func (*Metadata) SupportsDevice ¶ added in v0.26.0
SupportsDevice reports whether the server takes device sign-ins through OAuth.
type OAuthError ¶ added in v0.26.0
OAuthError is an RFC 6749 §5.2 error answer of Norcube Auth's OAuth server.
func (*OAuthError) Error ¶ added in v0.26.0
func (e *OAuthError) Error() string
type OAuthLoginOptions ¶ added in v0.26.0
type OAuthLoginOptions struct {
Metadata *Metadata
HTTP *http.Client
// Scopes to ask for (see ParseLoginScopes); empty means full.
Scopes []string
Timeout time.Duration
// BrowserOpenURL opens the authorization URL; the default browser
// by default.
BrowserOpenURL func(string) error
// OnURLReady is called with the authorization URL before the browser
// opens, for printing.
OnURLReady func(string)
// NoBrowser skips opening a browser: the caller prints the URL.
NoBrowser bool
}
OAuthLoginOptions configures OAuthLogin.
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 ScopeError ¶ added in v0.26.0
type ScopeError struct {
Audience string
// Scopes are the sign-in's granted scopes.
Scopes []string
}
ScopeError: the sign-in is limited by `login --scopes` and its scopes don't cover the service. Match it with errors.As.
func (*ScopeError) Error ¶ added in v0.26.0
func (e *ScopeError) Error() string
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 StoredSession ¶ added in v0.26.0
type StoredSession struct {
// Format is FormatLegacy or FormatOAuth; 0 when nothing is stored.
Format int
// Scopes are the granted scopes of an OAuth sign-in (nil for the
// older sign-in, which always has full access).
Scopes []string
// CLIAccessExpiresAt is when the cached CLI access token expires
// (format 2; zero when none is cached).
CLIAccessExpiresAt time.Time
}
StoredSession describes what a profile has stored, without secrets.
func LoadSession ¶ added in v0.26.0
func LoadSession(profile, api string) (StoredSession, error)
LoadSession describes the profile's stored session for api.
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
// CI, when set, mints the token from a CI token instead: one exchange
// per service, cached in memory (NORCUBE_TOKEN=nrc_ci_…).
CI *CIExchanger
// 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
// KeepLegacy leaves an older sign-in (format 1) as it is instead of
// moving it to the OAuth sign-in on first use. For diagnostics such
// as doctor, which must not change the profile they describe.
KeepLegacy bool
// 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 refresh and rejects the old one, so two refreshes racing with the same refresh token would sign the user out.
An OAuth sign-in (credentials format 2) refreshes only its CLI access token under the lock and exchanges it per (audience, organization) without it; see oauthsession.go. An older sign-in (format 1) refreshes straight into each token, under the lock, and is moved to OAuth on its first refresh when Norcube Auth offers it.
func NewTokenSource ¶
func NewTokenSource(apiBase, audience, orgID string) *TokenSource
func (*TokenSource) BearerInjector ¶
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package authtest is a fake Norcube Auth for tests: the OAuth server the CLI signs in with (metadata, authorization redirect, code exchange, refresh with rotation and reuse detection, token exchange, device flow, session upgrade, revocation) plus the few account routes commands call right after a login.
|
Package authtest is a fake Norcube Auth for tests: the OAuth server the CLI signs in with (metadata, authorization redirect, code exchange, refresh with rotation and reuse detection, token exchange, device flow, session upgrade, revocation) plus the few account routes commands call right after a login. |