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 EndServerSession(ctx context.Context, client *http.Client, authURL, refreshToken string) error
- func HasCredentials(profile, api string) bool
- func IsCIToken(s string) bool
- func LoadRefreshToken(profile, api string) (string, error)
- func LockProfile(ctx context.Context, dir, profile, api string, timeout time.Duration) (func(), error)
- func SaveAccessTokenUntil(profile, api, audience, orgID, token string, expiresAt time.Time) error
- func SaveRefreshToken(profile, api, token string) error
- 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 OrgAccessError
- type Organization
- type SessionState
- type Store
- type TokenSource
- type User
Constants ¶
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 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 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.
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.
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 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 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 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 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 SaveRefreshToken ¶
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
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"`
}
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:
- 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.
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
// 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 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 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 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
// 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 ¶
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.