auth

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package auth обменивает ключ доступа cloud.ru на Bearer-токен и кэширует его.

Три части: IAMSource получает токен у IAM, CachedSource отдаёт его из хранилища, пока не истёк, FileStore хранит на диске. Ошибки — sentinel-значения; текст пользователю пишет верхний слой.

Токен живёт 1 час (https://cloud.ru/docs/clickhouse/ug/topics/api-ref__authentication), поэтому кэш избавляет от лишнего запроса к IAM на каждую команду.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoKey — ключ доступа не задан.
	ErrNoKey = i18n.Sentinel("auth.err.no_key")
	// ErrKeyRejected — IAM не принял ключ (401).
	ErrKeyRejected = i18n.Sentinel("auth.err.key_rejected")
	// ErrKeyForbidden — ключ распознан, но токен не выдан (403).
	ErrKeyForbidden = i18n.Sentinel("auth.err.key_forbidden")
	// ErrRateLimited — IAM ограничил частоту запросов (429).
	ErrRateLimited = i18n.Sentinel("auth.err.rate_limited")
)

Functions

func CacheKey

func CacheKey(keyID, secret, iamURL string) string

CacheKey — ключ кэша по KeyID, секрету и адресу IAM: смена любого из них не подхватит старый токен. Сам секрет в ключ не попадает.

Types

type CachedSource

type CachedSource struct {
	Fetch func(ctx context.Context) (Token, error)
	Store Store // nil — без кэша
	Key   string
	Now   func() time.Time
}

CachedSource отдаёт токен из Store, пока он действует, иначе берёт свежий через Fetch (обычно IAMSource.Fetch).

func (*CachedSource) Refresh

func (s *CachedSource) Refresh(ctx context.Context) (string, error)

Refresh берёт токен у IAM мимо хранилища и перезаписывает его. Нужен, когда API отверг токен из кэша раньше срока (например, токен отозван при живом ключе).

func (*CachedSource) Token

func (s *CachedSource) Token(ctx context.Context) (string, error)

Token возвращает действующий токен: из хранилища или свежий.

type FileStore

type FileStore struct {
	Dir string
}

FileStore хранит токены файлами token-<ключ>.json в Dir с правами 0600.

func (FileStore) Load

func (s FileStore) Load(key string) (Token, bool, error)

Load читает токен. Файл чужой (права шире 0600), ссылка или не обычный файл — как пустой кэш.

func (FileStore) Save

func (s FileStore) Save(key string, t Token) error

Save пишет токен через временный файл и rename: os.WriteFile не меняет права уже существующего файла, а CreateTemp создаёт новый с 0600.

type IAMError

type IAMError struct {
	Status int
	Body   string
}

IAMError — IAM ответил не 200. Unwrap отдаёт sentinel по коду (или nil для прочих кодов).

func (*IAMError) Error

func (e *IAMError) Error() string

func (*IAMError) Unwrap

func (e *IAMError) Unwrap() error

type IAMSource

type IAMSource struct {
	KeyID  string
	Secret string
	URL    string // адрес обмена ключа на токен, по умолчанию — из config
	HTTP   *http.Client
	Now    func() time.Time
}

IAMSource получает свежий токен у IAM — без кэша.

func (*IAMSource) Endpoint

func (s *IAMSource) Endpoint() string

Endpoint — адрес IAM, к которому идёт запрос.

func (*IAMSource) Fetch

func (s *IAMSource) Fetch(ctx context.Context) (Token, error)

Fetch обменивает ключ на токен.

type Store

type Store interface {
	Load(key string) (Token, bool, error)
	Save(key string, t Token) error
}

Store — где хранить токен между запусками. Ошибка Load — как пустой кэш: токен всегда можно получить заново.

type Token

type Token struct {
	AccessToken string
	ExpiresAt   time.Time
}

Token — токен доступа и момент, когда он перестаёт действовать.

Jump to

Keyboard shortcuts

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