Documentation ¶
Overview ¶
Package database manages database connections and ORM integration.
Index ¶
- Constants
- Variables
- func IsNotFound(err error) bool
- func IsUniqueViolation(err error, idx string) bool
- func IsValidationError(err error) bool
- func Paginate(query *gorm.DB, result interface{}, page, limit uint64) (*pagination.Paginator, error)
- func PaginateFn(query *gorm.DB, page, limit uint64, ...) (*pagination.Paginator, error)
- func ToCIDRList(s string) ([]string, error)
- type APIKeyType
- type AuditEntry
- type Auditable
- type AuthRequirement
- type AuthorizedApp
- func (a *AuthorizedApp) AuditDisplay() string
- func (a *AuthorizedApp) AuditID() string
- func (a *AuthorizedApp) BeforeSave(tx *gorm.DB) error
- func (a *AuthorizedApp) IsAdminType() bool
- func (a *AuthorizedApp) IsDeviceType() bool
- func (a *AuthorizedApp) IsStatsType() bool
- func (a *AuthorizedApp) Realm(db *Database) (*Realm, error)
- func (a *AuthorizedApp) Stats(db *Database) (AuthorizedAppStats, error)
- func (a *AuthorizedApp) StatsCached(ctx context.Context, db *Database, cacher cache.Cacher) (AuthorizedAppStats, error)
- func (a *AuthorizedApp) TouchLastUsedAt(db *Database) error
- type AuthorizedAppStat
- type AuthorizedAppStats
- type BulkPermission
- type BulkPermissionAction
- type CodeType
- type CodesInvalidByOSData
- type CompositeDay
- type CompositeStats
- type Config
- type Database
- func (db *Database) ActivateSecrets(typ SecretType, since time.Time) error
- func (db *Database) ActivateTokenSigningKey(id interface{}, actor Auditable) error
- func (db *Database) ActiveTokenSigningKey() (*TokenSigningKey, error)
- func (db *Database) ActiveTokenSigningKeyCached(ctx context.Context, cacher cache.Cacher) (*TokenSigningKey, error)
- func (db *Database) ClaimLock(current *LockStatus, lockTime time.Duration) (*LockStatus, error)
- func (db *Database) ClaimToken(t time.Time, authApp *AuthorizedApp, tokenID string, subject *Subject) error
- func (db *Database) Close() error
- func (db *Database) CreateLock(cType string) (*LockStatus, error)
- func (db *Database) CreateOrUpdateSMSFromNumbers(numbers []*SMSFromNumber) error
- func (db *Database) DeleteKeyServerStats(realmID uint) error
- func (db *Database) DeleteOldKeyServerStatsDays(maxAge time.Duration) (int64, error)
- func (db *Database) DeleteSecret(s *Secret, actor Auditable) error
- func (db *Database) DeleteUser(u *User, actor Auditable) error
- func (db *Database) DeleteUserReport(phoneNumber string) error
- func (db *Database) DeleteVerificationCode(id uint) error
- func (db *Database) E2ERealm() (*Realm, error)
- func (db *Database) ExpireCode(uuid string) (*VerificationCode, error)
- func (db *Database) FindAuthorizedApp(id interface{}) (*AuthorizedApp, error)
- func (db *Database) FindAuthorizedAppByAPIKey(apiKey string) (*AuthorizedApp, error)
- func (db *Database) FindLockStatus(cType string) (*LockStatus, error)
- func (db *Database) FindMobileApp(id interface{}) (*MobileApp, error)
- func (db *Database) FindRealm(id interface{}) (*Realm, error)
- func (db *Database) FindRealmByName(name string) (*Realm, error)
- func (db *Database) FindRealmByRegion(region string) (*Realm, error)
- func (db *Database) FindRealmByRegionOrID(val string) (*Realm, error)
- func (db *Database) FindSMSFromNumber(id interface{}) (*SMSFromNumber, error)
- func (db *Database) FindSMSSigningKey(id interface{}) (*SMSSigningKey, error)
- func (db *Database) FindSecret(id interface{}) (*Secret, error)
- func (db *Database) FindTokenByID(tokenID string) (*Token, error)
- func (db *Database) FindTokenSigningKey(id interface{}) (*TokenSigningKey, error)
- func (db *Database) FindTokenSigningKeyByUUID(uuidStr string) (*TokenSigningKey, error)
- func (db *Database) FindTokenSigningKeyByUUIDCached(ctx context.Context, cacher cache.Cacher, uuidStr string) (*TokenSigningKey, error)
- func (db *Database) FindUser(id interface{}) (*User, error)
- func (db *Database) FindUserByEmail(email string) (*User, error)
- func (db *Database) FindUserReport(tx *gorm.DB, phoneNumber string) (*UserReport, error)
- func (db *Database) FindVerificationCode(code string) (*VerificationCode, error)
- func (db *Database) GenerateAPIKey(realmID uint) (string, error)
- func (db *Database) GenerateAPIKeyHMAC(apiKey string) (string, error)
- func (db *Database) GenerateAPIKeySignature(apiKey string) (string, error)
- func (db *Database) GeneratePhoneNumberHMAC(phoneNumber string) (string, error)
- func (db *Database) GenerateVerificationCodeHMAC(verCode string) (string, error)
- func (db *Database) GetAPIKeyDatabaseHMAC() ([][]byte, error)
- func (db *Database) GetAPIKeySignatureHMAC() ([][]byte, error)
- func (db *Database) GetCookieHashAndEncryptionKeys() ([][]byte, error)
- func (db *Database) GetKeyServerStats(realmID uint) (*KeyServerStats, error)
- func (db *Database) GetKeyServerStatsCached(ctx context.Context, realmID uint, cacher cache.Cacher) (*KeyServerStats, error)
- func (db *Database) GetPhoneNumberDatabaseHMAC() ([][]byte, error)
- func (db *Database) GetVerificationCodeDatabaseHMAC() ([][]byte, error)
- func (db *Database) HasRealmChaffEventsMap() (map[uint]bool, error)
- func (db *Database) InsertSMSErrorStat(realmID uint, errorCode string) error
- func (db *Database) IsCodeExpired(v *VerificationCode, code string) (bool, CodeType, error)
- func (db *Database) KeyManager() keys.KeyManager
- func (db *Database) ListActiveApps(realmID uint, scopes ...Scope) ([]*MobileApp, error)
- func (db *Database) ListActiveAppsWithRealm(p *pagination.PageParams, scopes ...Scope) ([]*MobileApp, *pagination.Paginator, error)
- func (db *Database) ListAudits(p *pagination.PageParams, scopes ...Scope) ([]*AuditEntry, *pagination.Paginator, error)
- func (db *Database) ListDynamicTranslations() ([]*DynamicTranslation, error)
- func (db *Database) ListDynamicTranslationsCached(ctx context.Context, cacher cache.Cacher) ([]*DynamicTranslation, error)
- func (db *Database) ListKeyServerStats() ([]*KeyServerStats, error)
- func (db *Database) ListKeyServerStatsDays(realmID uint) ([]*KeyServerStatsDay, error)
- func (db *Database) ListKeyServerStatsDaysCached(ctx context.Context, realmID uint, cacher cache.Cacher) ([]*KeyServerStatsDay, error)
- func (db *Database) ListRealms(p *pagination.PageParams, scopes ...Scope) ([]*Realm, *pagination.Paginator, error)
- func (db *Database) ListRecentCodes(realm *Realm, user *User) ([]*VerificationCode, error)
- func (db *Database) ListSecrets(scopes ...Scope) ([]*Secret, error)
- func (db *Database) ListSecretsForType(typ SecretType, scopes ...Scope) ([]*Secret, error)
- func (db *Database) ListTokenSigningKeys() ([]*TokenSigningKey, error)
- func (db *Database) ListUsers(p *pagination.PageParams, scopes ...Scope) ([]*User, *pagination.Paginator, error)
- func (db *Database) MaxKeyVersions() int64
- func (db *Database) MigrateTo(ctx context.Context, target string, rollback bool) error
- func (db *Database) Migrations(ctx context.Context) []*gormigrate.Migration
- func (db *Database) NewUserReport(phone string, nonce []byte, nonceRequired bool) (*UserReport, error)
- func (db *Database) Open(ctx context.Context) error
- func (db *Database) OpenWithCacher(ctx context.Context, cacher cache.Cacher) error
- func (db *Database) PasswordChanged(email string, t time.Time) error
- func (db *Database) Ping(ctx context.Context) error
- func (db *Database) PurgeAuditEntries(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeAuthorizedAppStats(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeAuthorizedApps(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeClaimedUserReports(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeExternalIssuerStats(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeMobileApps(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeOrphanedMemberships() (int64, error)
- func (db *Database) PurgeRealmChaffEvents(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeRealmStats(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeSMSErrorStats(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeSMSSigningKeys(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeSecret(s *Secret, actor Auditable) error
- func (db *Database) PurgeSigningKeys(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeTokenSigningKeys(ctx context.Context, kms keys.KeyVersionDestroyer, maxAge time.Duration) (int64, error)
- func (db *Database) PurgeTokens(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeUnclaimedUserReports(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeUserStats(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeUsers(maxAge time.Duration) (int64, error)
- func (db *Database) PurgeVerificationCodes(maxAge time.Duration) (int64, error)
- func (db *Database) RawDB() *gorm.DB
- func (db *Database) RecycleVerificationCodes(maxAge time.Duration) (int64, error)
- func (db *Database) RotateTokenSigningKey(ctx context.Context, kms keys.KeyVersionCreator, parent string, ...) (*TokenSigningKey, error)
- func (db *Database) SMSFromNumbers(scopes ...Scope) ([]*SMSFromNumber, error)
- func (db *Database) SaveAuditEntry(a *AuditEntry) error
- func (db *Database) SaveAuthorizedApp(a *AuthorizedApp, actor Auditable) error
- func (db *Database) SaveEmailConfig(s *EmailConfig) error
- func (db *Database) SaveKeyServerStats(stats *KeyServerStats) error
- func (db *Database) SaveKeyServerStatsDay(day *KeyServerStatsDay) error
- func (db *Database) SaveMembership(m *Membership, actor Auditable) error
- func (db *Database) SaveMobileApp(a *MobileApp, actor Auditable) error
- func (db *Database) SaveRealm(r *Realm, actor Auditable) error
- func (db *Database) SaveSMSConfig(s *SMSConfig) error
- func (db *Database) SaveSecret(s *Secret, actor Auditable) error
- func (db *Database) SaveTokenSigningKey(key *TokenSigningKey, actor Auditable) error
- func (db *Database) SaveUser(u *User, actor Auditable) error
- func (db *Database) SaveUserStat(u *UserStat) error
- func (db *Database) SaveVerificationCode(vc *VerificationCode, realm *Realm) error
- func (db *Database) SetRawDB(tx *gorm.DB)
- func (db *Database) SetSecretResolver(r *SecretResolver)
- func (db *Database) SupportsPerRealmSigning() bool
- func (db *Database) SyncRealmTranslations(realmID uint, localizations []*appsync.Localization) (*TranslationSyncResult, error)
- func (db *Database) SystemEmailConfig() (*EmailConfig, error)
- func (db *Database) SystemSMSConfig() (*SMSConfig, error)
- func (db *Database) TouchUserRevokeCheck(u *User) error
- func (db *Database) TryLock(ctx context.Context, lockName string, lockDuration time.Duration) (bool, error)
- func (db *Database) UntouchUserRevokeCheck(u *User) error
- func (db *Database) UpdateStats(ctx context.Context, codes ...*VerificationCode)
- func (db *Database) VerifyAPIKeySignature(key string) (string, uint64, error)
- func (db *Database) VerifyCodeAndIssueToken(request *IssueTokenRequest) (*Token, error)
- type DurationSeconds
- type DynamicTranslation
- type EmailConfig
- type Errorable
- type ExternalIssuerStat
- type ExternalIssuerStats
- type GormZapLogger
- type IssueTokenRequest
- type JSONRealmStatStatsData
- type KeyServerStats
- type KeyServerStatsDay
- type LockStatus
- type ManagedKey
- type Membership
- type MobileApp
- type OSType
- type Realm
- func (r *Realm) AbusePreventionEffectiveLimit() uint
- func (r *Realm) AddUserReportToAllowedTestTypes()
- func (r *Realm) AfterFind(tx *gorm.DB) error
- func (r *Realm) AllowsUserReport() bool
- func (r *Realm) AuditDisplay() string
- func (r *Realm) AuditID() string
- func (r *Realm) BeforeSave(tx *gorm.DB) error
- func (r *Realm) BuildInviteEmail(inviteLink string) string
- func (r *Realm) BuildPasswordResetEmail(passwordResetLink string) string
- func (r *Realm) BuildSMSText(code, longCode string, enxDomain, templateLabel string) (string, error)
- func (r *Realm) BuildVerifyEmail(verifyLink string) string
- func (r *Realm) CanUpgradeToRealmSigningKeys() bool
- func (r *Realm) CodesClaimedRatioAnomalous() bool
- func (r *Realm) CreateAuthorizedApp(db *Database, app *AuthorizedApp, actor Auditable) (string, error)
- func (r *Realm) CreateSMSSigningKeyVersion(ctx context.Context, db *Database, actor Auditable) (string, error)
- func (r *Realm) CreateSigningKeyVersion(ctx context.Context, db *Database, actor Auditable) (string, error)
- func (r *Realm) CurrentSMSSigningKey(db *Database) (*SMSSigningKey, error)
- func (r *Realm) CurrentSigningKey(db *Database) (*SigningKey, error)
- func (r *Realm) DefaultSMSTextTemplate() string
- func (r *Realm) DefaultUserReportSMSTextTemplate() string
- func (r *Realm) DestroySMSSigningKeyVersion(ctx context.Context, db *Database, id interface{}, actor Auditable) error
- func (r *Realm) DestroySigningKeyVersion(ctx context.Context, db *Database, id interface{}, actor Auditable) error
- func (r *Realm) EffectiveMFAMode(t time.Time) AuthRequirement
- func (r *Realm) EmailConfig(db *Database) (*EmailConfig, error)
- func (r *Realm) EmailProvider(db *Database) (email.Provider, error)
- func (r *Realm) ExternalIssuerStats(db *Database) (ExternalIssuerStats, error)
- func (r *Realm) ExternalIssuerStatsCached(ctx context.Context, db *Database, cacher cache.Cacher) (ExternalIssuerStats, error)
- func (r *Realm) FindAuthorizedApp(db *Database, id interface{}) (*AuthorizedApp, error)
- func (r *Realm) FindMobileApp(db *Database, id interface{}) (*MobileApp, error)
- func (r *Realm) FindUser(db *Database, id interface{}) (*User, error)
- func (r *Realm) FindVerificationCodeByUUID(db *Database, uuidStr string) (*VerificationCode, error)
- func (r *Realm) GetCodeDurationMinutes() int
- func (r *Realm) GetLongCodeDurationHours() int
- func (r *Realm) HasSMSConfig(db *Database) (bool, error)
- func (r *Realm) HistoricalCodesIssued(db *Database, limit uint64) ([]uint64, error)
- func (r *Realm) ListAudits(db *Database, p *pagination.PageParams, scopes ...Scope) ([]*AuditEntry, *pagination.Paginator, error)
- func (r *Realm) ListAuthorizedApps(db *Database, p *pagination.PageParams, scopes ...Scope) ([]*AuthorizedApp, *pagination.Paginator, error)
- func (r *Realm) ListChaffEvents(db *Database) ([]*RealmChaffEvent, error)
- func (r *Realm) ListMemberships(db *Database, p *pagination.PageParams, scopes ...Scope) ([]*Membership, *pagination.Paginator, error)
- func (r *Realm) ListMobileApps(db *Database, p *pagination.PageParams, scopes ...Scope) ([]*MobileApp, *pagination.Paginator, error)
- func (r *Realm) ListSMSSigningKeys(db *Database) ([]*SMSSigningKey, error)
- func (r *Realm) ListSigningKeys(db *Database) ([]*SigningKey, error)
- func (r *Realm) MembershipPermissionMap(db *Database) (map[uint]rbac.Permission, error)
- func (r *Realm) QuotaKey(hmacKey []byte) (string, error)
- func (r *Realm) RecordChaffEvent(db *Database, t time.Time) error
- func (r *Realm) RenderWelcomeMessage() string
- func (r *Realm) ResetSMSTextTemplates()
- func (r *Realm) SMSConfig(db *Database) (*SMSConfig, error)
- func (r *Realm) SMSErrorStats(db *Database) (SMSErrorStats, error)
- func (r *Realm) SMSErrorStatsCached(ctx context.Context, db *Database, cacher cache.Cacher) (SMSErrorStats, error)
- func (r *Realm) SMSProvider(db *Database) (sms.Provider, error)
- func (r *Realm) SMSTemplateExpansionMax() int
- func (r *Realm) SMSTemplateMaxLength() int
- func (r *Realm) SetActiveSMSSigningKey(db *Database, id uint, actor Auditable) (string, error)
- func (r *Realm) SetActiveSigningKey(db *Database, id uint, actor Auditable) (string, error)
- func (r *Realm) Stats(db *Database) (RealmStats, error)
- func (r *Realm) StatsCached(ctx context.Context, db *Database, cacher cache.Cacher) (RealmStats, error)
- func (r *Realm) UserStats(db *Database) (RealmUserStats, error)
- func (r *Realm) UserStatsCached(ctx context.Context, db *Database, cacher cache.Cacher) (RealmUserStats, error)
- func (r *Realm) ValidTestType(typ string) bool
- type RealmChaffEvent
- type RealmManagedKey
- type RealmStat
- type RealmStats
- type RealmUserStat
- type RealmUserStats
- type SMSConfig
- type SMSErrorStat
- type SMSErrorStats
- type SMSFromNumber
- type SMSSigningKey
- func (s *SMSSigningKey) AuditDisplay() string
- func (s *SMSSigningKey) AuditID() string
- func (s *SMSSigningKey) GetKID() string
- func (s *SMSSigningKey) IsActive() bool
- func (s *SMSSigningKey) ManagedKeyID() string
- func (s *SMSSigningKey) Purpose() string
- func (s *SMSSigningKey) SetActive(active bool)
- func (s *SMSSigningKey) SetManagedKeyID(keyID string)
- func (s *SMSSigningKey) SetRealmID(id uint)
- func (s *SMSSigningKey) Table() string
- type Scope
- func InConsumableSecretOrder() Scope
- func OnlySystemAdmins() Scope
- func Unscoped() Scope
- func WithAppOS(os OSType) Scope
- func WithAuditRealmID(id uint) Scope
- func WithAuditTime(from, to string) Scope
- func WithAuthorizedAppSearch(q string) Scope
- func WithAuthorizedAppType(typ APIKeyType) Scope
- func WithMobileAppSearch(q string) Scope
- func WithPermissionSearch(p rbac.Permission) Scope
- func WithRealmAutoKeyRotationEnabled(b bool) Scope
- func WithRealmSearch(q string) Scope
- func WithUserSearch(q string) Scope
- func WithoutAuditTest() Scope
- func WithoutPermissionSearch(p rbac.Permission) Scope
- type Secret
- type SecretResolver
- func (r *SecretResolver) ClearCaches()
- func (r *SecretResolver) Resolve(ctx context.Context, db *Database, sm secrets.SecretManager, typ SecretType) ([][]byte, error)
- func (r *SecretResolver) ResolveReferences(db *Database, typ SecretType) ([]string, error)
- func (r *SecretResolver) ResolveValue(ctx context.Context, sm secrets.SecretManager, ref string) ([]byte, error)
- type SecretType
- type SigningKey
- func (s *SigningKey) AuditDisplay() string
- func (s *SigningKey) AuditID() string
- func (s *SigningKey) GetKID() string
- func (s *SigningKey) IsActive() bool
- func (s *SigningKey) ManagedKeyID() string
- func (s *SigningKey) Purpose() string
- func (s *SigningKey) SetActive(active bool)
- func (s *SigningKey) SetManagedKeyID(keyID string)
- func (s *SigningKey) SetRealmID(id uint)
- func (s *SigningKey) Table() string
- type Subject
- type TestInstance
- type TestType
- type Token
- type TokenSigningKey
- type TranslationSyncResult
- type User
- func (u *User) AddToRealm(db *Database, r *Realm, permissions rbac.Permission, actor Auditable) error
- func (u *User) AuditDisplay() string
- func (u *User) AuditID() string
- func (u *User) BeforeSave(tx *gorm.DB) error
- func (u *User) DeleteFromRealm(db *Database, r *Realm, actor Auditable) error
- func (u *User) FindMembership(db *Database, realmID interface{}) (*Membership, error)
- func (u *User) ListMemberships(db *Database) ([]*Membership, error)
- func (u *User) PasswordAgeString() string
- func (u *User) PasswordChanged() time.Time
- func (u *User) SelectFirstMembership(db *Database) (*Membership, error)
- func (u *User) Stats(db *Database, realm *Realm) (UserStats, error)
- func (u *User) StatsCached(ctx context.Context, db *Database, cacher cache.Cacher, realm *Realm) (UserStats, error)
- type UserReport
- type UserStat
- type UserStats
- type UtilOption
- type VerificationCode
Constants ¶
const ( VerCodesCodeUniqueIndex = "uix_verification_codes_realm_code" VerCodesLongCodeUniqueIndex = "uix_verification_codes_realm_long_code" )
const ( DefaultShortCodeLength = 8 DefaultShortCodeExpirationMinutes = 15 DefaultLongCodeLength = 16 DefaultLongCodeExpirationHours = 24 DefaultMaxShortCodeMinutes = 60 DefaultSMSRegion = "us" DefaultLanguage = "en" SMSRegion = "[region]" SMSCode = "[code]" SMSExpires = "[expires]" SMSLongCode = "[longcode]" SMSLongExpires = "[longexpires]" SMSENExpressLink = "[enslink]" SMSTemplateMaxLength = 800 SMSTemplateExpansionMax = 918 DefaultTemplateLabel = "Default SMS template" DefaultSMSTextTemplate = "This is your Exposure Notifications Verification code: [longcode] Expires in [longexpires] hours" DefaultENXSMSTextTemplate = "Your Exposure Notifications verification link: [enslink] Expires in [longexpires] hours (click for mobile device only)" UserReportTemplateLabel = "User Report" UserReportDefaultText = "" /* 142-byte string literal not displayed */ UserReportDefaultENXText = "" /* 145-byte string literal not displayed */ EmailInviteLink = "[invitelink]" EmailPasswordResetLink = "[passwordresetlink]" EmailVerifyLink = "[verifylink]" RealmName = "[realmname]" // MaxPageSize is the maximum allowed page size for a list query. MaxPageSize = 1000 )
const ( SecretTypeAPIKeyDatabaseHMAC = SecretType("api_key_database_hmac") SecretTypeAPIKeySignatureHMAC = SecretType("api_key_signature_hmac") SecretTypeCookieKeys = SecretType("cookie_keys") SecretTypePhoneNumberDatabaseHMAC = SecretType("phone_number_database_hmac") SecretTypeVerificationCodeDatabaseHMAC = SecretType("verification_code_database_hmac") )
const (
// MinCodeLength defines the minimum number of digits in a code.
MinCodeLength = 6
)
const ( // NonceLength is the required length of an associated user-report request. // Changing this could break outstanding codes in the system. // If the value were to be lowered, uses should change to >= instead of exact match, // including updating associated documentation. NonceLength = 256 )
Variables ¶
var ( // ErrNoSigningKeyManager is the error returned when the key manager cannot be // used as a SigningKeyManager. ErrNoSigningKeyManager = errors.New("configured key manager cannot be used to manage per-realm keys") // ErrValidationFailed is the error returned when validation failed. This // should always be considered user error. ErrValidationFailed = errors.New("validation failed") )
var ( ErrNoSigningKeyManagement = errors.New("no signing key management") ErrBadDateRange = errors.New("bad date range") ENXRedirectDomain = os.Getenv("ENX_REDIRECT_DOMAIN") )
var ( ErrVerificationCodeNotFound = errors.New("verification code not found") ErrVerificationCodeExpired = errors.New("verification code expired") ErrVerificationCodeUsed = errors.New("verification code used") ErrTokenExpired = errors.New("verification token expired") ErrTokenUsed = errors.New("verification token used") ErrTokenMetadataMismatch = errors.New("verification token test metadata mismatch") ErrUnsupportedTestType = errors.New("verification code has unsupported test type") )
var ( // ValidTestTypes is a map containing the valid test types. ValidTestTypes = map[string]struct{}{ "confirmed": {}, "likely": {}, "negative": {}, "user-report": {}, } ErrInvalidTestType = errors.New("invalid test type, must be confirmed, likely, negative, or self_report") ErrCodeAlreadyExpired = errors.New("code already expired") ErrCodeAlreadyClaimed = errors.New("code already claimed") ErrCodeTooShort = errors.New("verification code is too short") ErrAlreadyReported = errors.New("phone number not eligible for user report, try again later") ErrRequiresPhoneNumber = errors.New("phone number is required for user report requests") )
var ApproxTime = cmp.Options{cmpopts.EquateApproxTime(1 * time.Second)}
ApproxTime is a compare helper for clock skew.
var Countries = map[string]string{}/* 242 elements not displayed */
var ErrWrongGeneration = errors.New("wrong generation")
Functions ¶
func IsNotFound ¶ added in v0.3.0
IsNotFound determines if an error is a record not found.
func IsUniqueViolation ¶ added in v0.34.2
IsUniqueViolation returns true if the given error corresponds to a "duplicate index" error on the given index.
func IsValidationError ¶ added in v0.19.0
IsValidationError returns true if the error is a validation error (user error), or false otherwise.
func Paginate ¶ added in v0.16.0
func Paginate(query *gorm.DB, result interface{}, page, limit uint64) (*pagination.Paginator, error)
Paginate is a helper that paginates a gorm query into the given result. In addition to reflecting into the provided result, it returns a pagination struct.
If page is 0, it defaults to 1. If limit is 0, it defaults to the global pagination default limit.
func PaginateFn ¶ added in v0.16.0
func PaginateFn(query *gorm.DB, page, limit uint64, populateFn func(query *gorm.DB, offset uint64) error) (*pagination.Paginator, error)
PaginateFn paginates with a custom function for returning results.
func ToCIDRList ¶ added in v0.10.0
ToCIDRList converts the newline-separated and/or comma-separated CIDR list into an array of strings.
Types ¶
type APIKeyType ¶ added in v0.11.0
type APIKeyType int
const ( APIKeyTypeInvalid APIKeyType = iota - 1 APIKeyTypeDevice APIKeyTypeAdmin APIKeyTypeStats )
func (APIKeyType) Display ¶ added in v0.11.0
func (a APIKeyType) Display() string
type AuditEntry ¶ added in v0.11.0
type AuditEntry struct { Errorable // ID is the entry's ID. ID uint `gorm:"primary_key;"` // RealmID is the ID of the realm against which this event took place, if the // event took place against a realm. This can be 0 in situations where the // event took place outside of a realm (e.g. user creation), which means it's // a system event. RealmID uint `gorm:"column:realm_id; type:integer; not null;"` // ActorID is the ID of the actor which performed this event. It's usually of // the form `model:id` (e.g. users:1), but there's no guarantee that the // underlying resource still exists when the audit is read. It's primarily // used for sorting/filtering where an audit viewer wants to see all events a // particular entity took. // // ActorDisplay is the display name of the actor. The actor defines how it // will be displayed in audit logs. ActorID string `gorm:"column:actor_id; type:text; not null;"` ActorDisplay string `gorm:"column:actor_display; type:text; not null;"` // Action is the auditable action. Action string `gorm:"column:action; type:text; not null;"` // TargetID and TargetDisplay are the same as the actor, but are for the // target of the action. TargetID string `gorm:"column:target_id; type:text; not null;"` TargetDisplay string `gorm:"column:target_display; type:text; not null;"` // Diff is the change of structure that occurred, if any. Diff string `gorm:"column:diff; type:text;"` // CreatedAt is when the entry was created. CreatedAt time.Time }
AuditEntry represents an event in the system. These records are purged after a configurable number of days by the cleanup job. The AuditEntry specifically does NOT make use of foreign keys or relationships to avoid breaking an audit entry if the upstream data which was audited is removed or changed. These records should be considered immutable.
func BuildAuditEntry ¶ added in v0.11.0
func BuildAuditEntry(actor Auditable, action string, target Auditable, realmID uint) *AuditEntry
BuildAuditEntry builds an AuditEntry from the given parameters. For actions that don't take place on a realm, use a realmID of 0.
func (*AuditEntry) BeforeSave ¶ added in v0.19.0
func (a *AuditEntry) BeforeSave(tx *gorm.DB) error
BeforeSave runs validations. If there are errors, the save fails.
type Auditable ¶ added in v0.11.0
type Auditable interface { // AuditID returns the id for this resource as it will be stored in audit // logs. This ID is usually of the format `table:id`. AuditID() string // AuditDisplay returns how this resource should appear in audit logs. AuditDisplay() string }
Auditable represents a resource that can be audited as an actor or actee.
System represents the system and actions it has taken. It's not stored in the database.
type AuthRequirement ¶ added in v0.9.0
type AuthRequirement int16
AuthRequirement represents authentication requirements for the realm
const ( // MFAOptionalPrompt will prompt users for MFA on login. MFAOptionalPrompt AuthRequirement = iota // MFARequired will not allow users to proceed without MFA on their account. MFARequired // MFAOptional will not prompt users to enable MFA. MFAOptional )
func (AuthRequirement) String ¶ added in v0.9.0
func (r AuthRequirement) String() string
type AuthorizedApp ¶
type AuthorizedApp struct { gorm.Model Errorable // AuthorizedApps belong to exactly one realm. RealmID uint `gorm:"unique_index:realm_apikey_name"` // Name is the name of the authorized app. Name string `gorm:"type:varchar(100);unique_index:realm_apikey_name"` // APIKeyPreview is the first few characters of the API key for display // purposes. This can help admins in the UI when determining which API key is // in use. APIKeyPreview string `gorm:"type:varchar(32)"` // APIKey is the HMACed API key. APIKey string `gorm:"type:varchar(512);unique_index"` // APIKeyType is the API key type. APIKeyType APIKeyType `gorm:"column:api_key_type; type:integer; not null;"` // LastUsedAt is the estimated time at which the API key was last used. For // performance reasons, this not incremented on each use but rather in short // buckets to avoid a write on every read. LastUsedAt *time.Time `gorm:"column:last_used_at; type:timestamp with time zone;"` }
AuthorizedApp represents an application that is authorized to verify verification codes and perform token exchanges. This is controlled via a generated API key.
Admin Keys are able to issue diagnosis keys and are not able to participate the verification protocol.
func (*AuthorizedApp) AuditDisplay ¶ added in v0.11.0
func (a *AuthorizedApp) AuditDisplay() string
func (*AuthorizedApp) AuditID ¶ added in v0.11.0
func (a *AuthorizedApp) AuditID() string
func (*AuthorizedApp) BeforeSave ¶ added in v0.4.0
func (a *AuthorizedApp) BeforeSave(tx *gorm.DB) error
BeforeSave runs validations. If there are errors, the save fails.
func (*AuthorizedApp) IsAdminType ¶
func (a *AuthorizedApp) IsAdminType() bool
func (*AuthorizedApp) IsDeviceType ¶
func (a *AuthorizedApp) IsDeviceType() bool
func (*AuthorizedApp) IsStatsType ¶ added in v0.19.0
func (a *AuthorizedApp) IsStatsType() bool
func (*AuthorizedApp) Realm ¶
func (a *AuthorizedApp) Realm(db *Database) (*Realm, error)
Realm returns the associated realm for this app. If you only need the ID, call .RealmID instead of a full database lookup.
func (*AuthorizedApp) Stats ¶ added in v0.5.0
func (a *AuthorizedApp) Stats(db *Database) (AuthorizedAppStats, error)
Stats returns the usage statistics for this app. If no stats exist, it returns an empty array.
func (*AuthorizedApp) StatsCached ¶ added in v0.21.0
func (a *AuthorizedApp) StatsCached(ctx context.Context, db *Database, cacher cache.Cacher) (AuthorizedAppStats, error)
StatsCached is stats, but cached.
func (*AuthorizedApp) TouchLastUsedAt ¶ added in v0.27.0
func (a *AuthorizedApp) TouchLastUsedAt(db *Database) error
TouchLastUsedAt updates the timestamp at which the authorized app was last used. It does not write an audit entry.
type AuthorizedAppStat ¶ added in v0.18.0
type AuthorizedAppStat struct { Date time.Time `gorm:"date; not null;"` AuthorizedAppID uint `gorm:"column:authorized_app_id; type:integer; not null; not null;"` // CodesIssued is the number of codes issued. Only keys of type "admin" can // issue codes. CodesClaimed and CodesInvalid are the number of codes claimed // and valid, respectively. These fields are only valid for "device" API keys. CodesIssued uint `gorm:"column:codes_issued; type:integer; not null; default: 0;"` CodesClaimed uint `gorm:"column:codes_claimed; type:integer; not null; default: 0;"` CodesInvalid uint `gorm:"column:codes_invalid; type:integer; not null; default:0;"` // TokensClaimed and TokensInvalid are the number of tokens exchanged for a // certificate or failures. These fields are only valid for "device" API keys. TokensClaimed uint `gorm:"column:tokens_claimed; type:integer; not null; default:0;"` TokensInvalid uint `gorm:"column:tokens_invalid; type:integer; not null; default:0;"` // Non-database fields, these are added via the stats lookup using the join // table. AuthorizedAppName string `gorm:"-"` AuthorizedAppType string `gorm:"-"` }
AuthorizedAppStat represents statistics related to an API key in the database.
type AuthorizedAppStats ¶ added in v0.3.0
type AuthorizedAppStats []*AuthorizedAppStat
AuthorizedAppStats represents a logical collection of stats for an authorized app.
func (AuthorizedAppStats) MarshalCSV ¶ added in v0.18.0
func (s AuthorizedAppStats) MarshalCSV() ([]byte, error)
MarshalCSV returns bytes in CSV format.
func (AuthorizedAppStats) MarshalJSON ¶ added in v0.18.0
func (s AuthorizedAppStats) MarshalJSON() ([]byte, error)
MarshalJSON is a custom JSON marshaller.
func (*AuthorizedAppStats) UnmarshalJSON ¶ added in v0.18.0
func (s *AuthorizedAppStats) UnmarshalJSON(b []byte) error
type BulkPermission ¶ added in v0.19.1
type BulkPermission struct { Errorable RealmID uint UserIDs []uint Permissions rbac.Permission Action BulkPermissionAction }
BulkPermission represents a bulk permission operation. This is not actually a table in the database.
func (*BulkPermission) Apply ¶ added in v0.19.1
func (b *BulkPermission) Apply(db *Database, actor Auditable) error
Apply converges the bulk operation. If a user isn't in the realm, no action is taken.
For add operations, if the user already has the permission, no action is taken. For remove operations, if the user does not have the permission, no action is taken.
Other permissions not in the list are unchanged.
type BulkPermissionAction ¶ added in v0.19.1
type BulkPermissionAction uint8
BulkPermissionAction is the permission action to take.
const ( BulkPermissionActionAdd BulkPermissionAction BulkPermissionActionRemove )
type CodesInvalidByOSData ¶ added in v0.26.0
type CompositeDay ¶ added in v0.24.0
CompositeDay represents a single day of composite stats.
func (*CompositeDay) IsEmpty ¶ added in v0.35.0
func (c *CompositeDay) IsEmpty() bool
type CompositeStats ¶ added in v0.24.0
type CompositeStats []*CompositeDay
CompositeStats is an internal type for collecting unifed realm and key server stats.
func (CompositeStats) MarshalCSV ¶ added in v0.24.0
func (c CompositeStats) MarshalCSV() ([]byte, error)
MarshalCSV returns bytes in CSV format.
func (CompositeStats) MarshalJSON ¶ added in v0.24.0
func (c CompositeStats) MarshalJSON() ([]byte, error)
MarshalJSON is a custom JSON marshaller.
func (*CompositeStats) UnmarshalJSON ¶ added in v0.24.0
func (c *CompositeStats) UnmarshalJSON(b []byte) error
type Config ¶
type Config struct { Name string `env:"DB_NAME" json:",omitempty"` User string `env:"DB_USER" json:",omitempty"` Host string `env:"DB_HOST, default=localhost" json:",omitempty"` Port string `env:"DB_PORT, default=5432" json:",omitempty"` SSLMode string `env:"DB_SSLMODE, default=require" json:",omitempty"` ConnectionTimeout uint `env:"DB_CONNECT_TIMEOUT" json:",omitempty"` Password string `env:"DB_PASSWORD" json:"-"` // ignored by zap's JSON formatter SSLCertPath string `env:"DB_SSLCERT" json:",omitempty"` SSLKeyPath string `env:"DB_SSLKEY" json:",omitempty"` SSLRootCertPath string `env:"DB_SSLROOTCERT" json:",omitempty"` // MaxConnectionLifetime and MaxConnectionIdleTime determine the connection // configuration. Note that MaxConnectionIdleTime must be less than // MaxConnectionLifetime. MaxConnectionLifetime time.Duration `env:"DB_MAX_CONN_LIFETIME, default=5m" json:",omitempty"` MaxConnectionIdleTime time.Duration `env:"DB_MAX_CONN_IDLE_TIME, default=1m" json:",omitempty"` // Debug is a boolean that indicates whether the database should log SQL // commands. Debug bool `env:"DB_DEBUG,default=false"` // Keys is the key management configuration. This is used to resolve values // that are encrypted via a KMS. Keys keys.Config `env:",prefix=DB_"` // KeyRing is the KMS keyring to use for managing KMS keys. KeyRing string `env:"DB_KEYRING"` // MaxKeyVersions is the maximum number of signing key versions for a type, // per realm. This is enforced at the database layer, not the upstream KMS. MaxKeyVersions int64 `env:"DB_MAX_KEY_VERSIONS, default=5"` // EncryptionKey is the reference to an encryption/decryption key to use when // for application-layer encryption before values are persisted to the // database. EncryptionKey string `env:"DB_ENCRYPTION_KEY,required" json:"-"` // Secrets is the secret configuration. This is used to resolve values that // are actually pointers to secrets before returning them to the caller. The // table implementation is the source of truth for which values are secrets // and which are plaintext. Secrets secrets.Config }
Config represents the env var based configuration for database connections.
func (*Config) ConnectionString ¶
ConnectionString returns the postgresql connection string based on this config.
While this package could be adapted to different databases easily, this file and method in particular would need to change.
type Database ¶
type Database struct {
// contains filtered or unexported fields
}
Database is a handle to the database layer for the Exposure Notifications Verification Server.
func (*Database) ActivateSecrets ¶ added in v0.27.0
func (db *Database) ActivateSecrets(typ SecretType, since time.Time) error
ActivateSecrets activates all secrets that are not currently activate but have been created for since the provided timestamp.
func (*Database) ActivateTokenSigningKey ¶ added in v0.20.0
ActivateTokenSigningKey activates the signing key with the provided database ID. If no record corresponds to the given ID, an error is returned. If the given ID is already active, no action is taken. Otherwise, all existing key versions are marked as inactive and this key is marked as active.
func (*Database) ActiveTokenSigningKey ¶ added in v0.20.0
func (db *Database) ActiveTokenSigningKey() (*TokenSigningKey, error)
ActiveTokenSigningKey returns the currently-active token signing key. If no key is currently marked as active, it returns NotFound.
func (*Database) ActiveTokenSigningKeyCached ¶ added in v0.20.0
func (db *Database) ActiveTokenSigningKeyCached(ctx context.Context, cacher cache.Cacher) (*TokenSigningKey, error)
ActiveTokenSigningKeyCached is like ActiveTokenSigningKey, but the results are cached for a short period to alleviate load on the database.
func (*Database) ClaimLock ¶ added in v0.20.0
func (db *Database) ClaimLock(current *LockStatus, lockTime time.Duration) (*LockStatus, error)
ClaimLock attempts to obtain a lock for the specified `lockTime` so that that type of cleanup can be performed exclusively by the owner.
func (*Database) ClaimToken ¶
func (db *Database) ClaimToken(t time.Time, authApp *AuthorizedApp, tokenID string, subject *Subject) error
ClaimToken looks up the token by ID, verifies that it is not expired and that the specified subject matches the parameters that were configured when issued.
func (*Database) Close ¶
Close will close the database connection. Should be deferred right after Open.
func (*Database) CreateLock ¶ added in v0.20.0
func (db *Database) CreateLock(cType string) (*LockStatus, error)
CreateLock is used to create a new 'cleanup' type/row in the database.
func (*Database) CreateOrUpdateSMSFromNumbers ¶ added in v0.19.0
func (db *Database) CreateOrUpdateSMSFromNumbers(numbers []*SMSFromNumber) error
CreateOrUpdateSMSFromNumbers takes the list of SMS numbers and creates new records, updates existing records, and deletes records that are not present in the list.
func (*Database) DeleteKeyServerStats ¶ added in v0.20.0
DeleteKeyServerStats disables gathering key-server statistics and removes the entry
func (*Database) DeleteOldKeyServerStatsDays ¶ added in v0.20.0
DeleteOldKeyServerStatsDays deletes rows from KeyServerStatsDays that are older than maxAge (default 90d)
func (*Database) DeleteSecret ¶ added in v0.27.0
DeleteSecret performs a soft delete on the provided secret.
func (*Database) DeleteUser ¶
DeleteUser deletes the user entry.
func (*Database) DeleteUserReport ¶ added in v0.27.0
DeleteUserReport removes a specific phone number from the user report de-duplication table.
func (*Database) DeleteVerificationCode ¶
DeleteVerificationCode deletes the code by ID, this is a hard delete.
func (*Database) E2ERealm ¶ added in v0.27.0
E2ERealm gets the end-to-end realm. The end-to-end realm is defined as the realm that has a region_code beginning with E2E-* or a name beginning with e2e-test-*.
If no e2e realm is defined, it returns NotFound.
func (*Database) ExpireCode ¶ added in v0.5.1
func (db *Database) ExpireCode(uuid string) (*VerificationCode, error)
ExpireCode saves a verification code as expired.
func (*Database) FindAuthorizedApp ¶ added in v0.18.0
func (db *Database) FindAuthorizedApp(id interface{}) (*AuthorizedApp, error)
FindAuthorizedApp finds the authorized app by the given id.
func (*Database) FindAuthorizedAppByAPIKey ¶
func (db *Database) FindAuthorizedAppByAPIKey(apiKey string) (*AuthorizedApp, error)
FindAuthorizedAppByAPIKey located an authorized app based on API key.
func (*Database) FindLockStatus ¶ added in v0.20.0
func (db *Database) FindLockStatus(cType string) (*LockStatus, error)
FindLockStatus looks up the current cleanup state in the database by cleanup type.
func (*Database) FindMobileApp ¶ added in v0.32.0
func (*Database) FindRealmByName ¶ added in v0.5.0
func (*Database) FindRealmByRegion ¶ added in v0.12.0
func (*Database) FindRealmByRegionOrID ¶ added in v0.20.0
FindRealmByRegionOrID finds the realm by the given ID or region code.
func (*Database) FindSMSFromNumber ¶ added in v0.19.0
func (db *Database) FindSMSFromNumber(id interface{}) (*SMSFromNumber, error)
FindSMSFromNumber finds the given SMS from number by ID.
func (*Database) FindSMSSigningKey ¶ added in v0.21.0
func (db *Database) FindSMSSigningKey(id interface{}) (*SMSSigningKey, error)
FindSMSSigningKey finds an SMS signing key by the provided database id.
func (*Database) FindSecret ¶ added in v0.27.0
FindSecret gets a specific secret by its database ID.
func (*Database) FindTokenSigningKey ¶ added in v0.20.0
func (db *Database) FindTokenSigningKey(id interface{}) (*TokenSigningKey, error)
FindTokenSigningKey finds the given key by database ID. It returns an error if the record is not found.
func (*Database) FindTokenSigningKeyByUUID ¶ added in v0.20.0
func (db *Database) FindTokenSigningKeyByUUID(uuidStr string) (*TokenSigningKey, error)
FindTokenSigningKeyByUUID finds the given key by database ID. It returns an error if the record is not found.
func (*Database) FindTokenSigningKeyByUUIDCached ¶ added in v0.20.0
func (db *Database) FindTokenSigningKeyByUUIDCached(ctx context.Context, cacher cache.Cacher, uuidStr string) (*TokenSigningKey, error)
FindTokenSigningKeyByUUIDCached is like FindTokenSigningKeyByUUID, but the results are cached for a short period to alleviate load on the database.
func (*Database) FindUser ¶
FindUser finds a user by the given id, if one exists. The id can be a string or integer value. It returns an error if the record is not found.
func (*Database) FindUserByEmail ¶ added in v0.4.0
FindUserByEmail reads back a User struct by email address. It returns an error if the record is not found.
func (*Database) FindUserReport ¶ added in v0.25.0
FindUserReport finds a user report by phone number using any of the currently valid HMAC keys.
func (*Database) FindVerificationCode ¶
func (db *Database) FindVerificationCode(code string) (*VerificationCode, error)
FindVerificationCode find a verification code by the code number (can be short code or long code).
func (*Database) GenerateAPIKey ¶ added in v0.3.0
GenerateAPIKey generates a new API key that is bound to the given realm. This API key is NOT stored in the database. API keys are of the format:
key:realmID:hex(hmac)
func (*Database) GenerateAPIKeyHMAC ¶ added in v0.7.0
GenerateAPIKeyHMAC generates the HMAC of the provided API key using the latest HMAC key.
func (*Database) GenerateAPIKeySignature ¶ added in v0.3.0
GenerateAPIKeySignature returns all possible signatures of the given key.
func (*Database) GeneratePhoneNumberHMAC ¶ added in v0.25.0
GeneratePhoneNumberHMAC generates the HMAC of the phone number using the latest key.
func (*Database) GenerateVerificationCodeHMAC ¶ added in v0.7.0
GenerateVerificationCodeHMAC generates the HMAC of the code using the latest key.
func (*Database) GetAPIKeyDatabaseHMAC ¶ added in v0.27.0
GetAPIKeyDatabaseHMAC returns the HMAC keys for storing API keys in the database.
func (*Database) GetAPIKeySignatureHMAC ¶ added in v0.27.0
GetAPIKeySignatureHMAC returns the HMAC keys for signing API keys in the database.
func (*Database) GetCookieHashAndEncryptionKeys ¶ added in v0.27.0
GetCookieHashAndEncryptionKeys gets the cookie hash and encryption keys. The first 32 bytes are the encryption key and the remaining bytes are the HMAC key.
func (*Database) GetKeyServerStats ¶ added in v0.20.0
func (db *Database) GetKeyServerStats(realmID uint) (*KeyServerStats, error)
GetKeyServerStats retrieves the configuration for gathering key-server statistics
func (*Database) GetKeyServerStatsCached ¶ added in v0.23.0
func (db *Database) GetKeyServerStatsCached(ctx context.Context, realmID uint, cacher cache.Cacher) (*KeyServerStats, error)
GetKeyServerStatsCached returns true if the provided realm has key server stats enabled.
func (*Database) GetPhoneNumberDatabaseHMAC ¶ added in v0.27.0
GetPhoneNumberDatabaseHMAC returns the HMAC keys for storing phone numbers in the database.
func (*Database) GetVerificationCodeDatabaseHMAC ¶ added in v0.27.0
GetVerificationCodeDatabaseHMAC returns the HMAC keys for storing verification codes in the database.
func (*Database) HasRealmChaffEventsMap ¶ added in v0.24.0
HasRealmChaffEventsMap returns a map of realm IDs that have any chaff events.
func (*Database) InsertSMSErrorStat ¶ added in v1.1.0
InsertSMSErrorStat inserts a new SMS error stat for the given realm and error code.
func (*Database) IsCodeExpired ¶ added in v0.5.0
IsCodeExpired checks to see if the actual code provided is the short or long code, and determines if it is expired based on that.
func (*Database) KeyManager ¶ added in v0.5.0
func (db *Database) KeyManager() keys.KeyManager
func (*Database) ListActiveApps ¶ added in v0.17.1
ListActiveApps finds mobile apps by their realm.
func (*Database) ListActiveAppsWithRealm ¶ added in v0.16.0
func (db *Database) ListActiveAppsWithRealm(p *pagination.PageParams, scopes ...Scope) ([]*MobileApp, *pagination.Paginator, error)
ListActiveAppsWithRealm finds all active mobile apps with their associated realm preloaded. Refine the search with scopes.
func (*Database) ListAudits ¶ added in v0.16.0
func (db *Database) ListAudits(p *pagination.PageParams, scopes ...Scope) ([]*AuditEntry, *pagination.Paginator, error)
ListAudits returns the list audit events which match the given criteria. Warning: This list may be large. Use Realm.Audits() to get users scoped to a realm.
func (*Database) ListDynamicTranslations ¶ added in v0.30.0
func (db *Database) ListDynamicTranslations() ([]*DynamicTranslation, error)
ListDynamicTranslations returns all of the dynamic translations for all realms. The result of this read should be cached for some period of time.
func (*Database) ListDynamicTranslationsCached ¶ added in v0.30.0
func (db *Database) ListDynamicTranslationsCached(ctx context.Context, cacher cache.Cacher) ([]*DynamicTranslation, error)
ListDynamicTranslationsCached is ListDynamicTranslations, but cached.
func (*Database) ListKeyServerStats ¶ added in v0.21.0
func (db *Database) ListKeyServerStats() ([]*KeyServerStats, error)
ListKeyServerStats retrieves the key-server statistics configuration for all realms
func (*Database) ListKeyServerStatsDays ¶ added in v0.20.0
func (db *Database) ListKeyServerStatsDays(realmID uint) ([]*KeyServerStatsDay, error)
ListKeyServerStatsDays retrieves the last 90 days of key-server statistics
func (*Database) ListKeyServerStatsDaysCached ¶ added in v0.21.0
func (db *Database) ListKeyServerStatsDaysCached(ctx context.Context, realmID uint, cacher cache.Cacher) ([]*KeyServerStatsDay, error)
ListKeyServerStatsDaysCached retrieves the last 90 days of key-server statistics
func (*Database) ListRealms ¶ added in v0.16.0
func (db *Database) ListRealms(p *pagination.PageParams, scopes ...Scope) ([]*Realm, *pagination.Paginator, error)
ListRealms lists all available realms in the system.
func (*Database) ListRecentCodes ¶ added in v0.12.0
func (db *Database) ListRecentCodes(realm *Realm, user *User) ([]*VerificationCode, error)
ListRecentCodes shows the last 5 recently issued codes for a given issuing user. The code and longCode are removed, this is only intended to show metadata.
func (*Database) ListSecrets ¶ added in v0.27.0
ListSecrets lists all secrets in the database.
func (*Database) ListSecretsForType ¶ added in v0.27.0
func (db *Database) ListSecretsForType(typ SecretType, scopes ...Scope) ([]*Secret, error)
ListSecretsForType lists all secrets for the given type, ordered by their creation date, but with inactive secrets (ones not ready to be used as primary) at the end of the list, allowing for propagation over time.
func (*Database) ListTokenSigningKeys ¶ added in v0.20.0
func (db *Database) ListTokenSigningKeys() ([]*TokenSigningKey, error)
ListTokenSigningKeys lists all keys sorted by their active state, then creation state descending. If there are no keys, it returns an empty list. To get the current active signing key, use ActiveTokenSigningKey.
func (*Database) ListUsers ¶
func (db *Database) ListUsers(p *pagination.PageParams, scopes ...Scope) ([]*User, *pagination.Paginator, error)
ListUsers returns a list of all users sorted by name. Warning: This list may be large. Use Realm.ListUsers() to get users scoped to a realm.
func (*Database) MaxKeyVersions ¶ added in v0.21.0
MaxKeyVersions returns the configured maximum.
func (*Database) Migrations ¶ added in v0.19.0
func (*Database) NewUserReport ¶ added in v0.25.0
func (db *Database) NewUserReport(phone string, nonce []byte, nonceRequired bool) (*UserReport, error)
NewUserReport creates a new UserReport by calculating the current HMAC of the provided phone number and encoding the nonce. It does NOT save it to the database.
func (*Database) Open ¶ added in v0.4.0
Open creates a database connection. This should only be called once.
func (*Database) OpenWithCacher ¶ added in v0.5.0
OpenWithCacher creates a database connection with the cacher. This should only be called once.
func (*Database) PasswordChanged ¶ added in v0.9.0
PasswordChanged updates the last password change timestamp of the user.
func (*Database) PurgeAuditEntries ¶ added in v0.11.0
PurgeAuditEntries will delete audit entries which were created longer than maxAge ago.
func (*Database) PurgeAuthorizedAppStats ¶ added in v0.31.0
PurgeAuthorizedAppStats will delete stats that were created longer than maxAge ago.
func (*Database) PurgeAuthorizedApps ¶ added in v0.15.0
PurgeAuthorizedApps will delete authorized apps that have been deleted for more than the specified time.
func (*Database) PurgeClaimedUserReports ¶ added in v0.25.0
PurgeClaimedUserReports removes expired user reports.
func (*Database) PurgeExternalIssuerStats ¶ added in v0.31.0
PurgeExternalIssuerStats will delete stats that were created longer than maxAge ago.
func (*Database) PurgeMobileApps ¶ added in v0.10.0
PurgeMobileApps will delete mobile apps that have been deleted for more than the specified time.
func (*Database) PurgeOrphanedMemberships ¶ added in v0.36.1
PurgeOrphanedMemberships will delete memberships that have no permissions. This exists to fix a bug that existed since 2021-08-24. It should be safe to remove this code in 0.40.0+, but it's also not hurting anything to stick around.
func (*Database) PurgeRealmChaffEvents ¶ added in v0.24.0
PurgeRealmChaffEvents will delete realm chaff events that have exceeded the storage lifetime.
func (*Database) PurgeRealmStats ¶ added in v0.31.0
PurgeRealmStats will delete stats that were created longer than maxAge ago.
func (*Database) PurgeSMSErrorStats ¶ added in v1.1.0
PurgeSMSErrorStats will delete stats that were created longer than maxAge ago.
func (*Database) PurgeSMSSigningKeys ¶ added in v0.21.0
PurgeSMSSigningKeys will purge soft deleted keys that have been soft deleted for maxAge duration.
func (*Database) PurgeSecret ¶ added in v0.27.0
PurgeSecret deletes the secret for real.
func (*Database) PurgeSigningKeys ¶ added in v0.20.0
PurgeSigningKeys will purge soft deleted keys that have been soft deleted for maxAge duration.
func (*Database) PurgeTokenSigningKeys ¶ added in v0.20.0
func (db *Database) PurgeTokenSigningKeys(ctx context.Context, kms keys.KeyVersionDestroyer, maxAge time.Duration) (int64, error)
PurgeTokenSigningKeys will delete token signing keys that have been rotated more than the provided max age.
func (*Database) PurgeTokens ¶
PurgeTokens will delete tokens that have expired since at least the provided maxAge ago. This is a hard delete, not a soft delete.
func (*Database) PurgeUnclaimedUserReports ¶ added in v0.25.0
PurgeUnclaimedUserReports deletes record from the database if the phone number was used in a user report, but the code was never claimed.
func (*Database) PurgeUserStats ¶ added in v0.31.0
PurgeUserStats will delete stats that were created longer than maxAge ago.
func (*Database) PurgeUsers ¶ added in v0.17.0
PurgeUsers will delete users who are not a system admin, not a member of any realms and have not been modified before the expiry time.
func (*Database) PurgeVerificationCodes ¶
PurgeVerificationCodes will delete verifications that have expired since at least the provided maxAge ago. This is a hard delete, not a soft delete.
func (*Database) RawDB ¶ added in v0.9.0
RawDB returns the underlying gorm database. This is publicly exposed for tests.
func (*Database) RecycleVerificationCodes ¶ added in v0.16.0
RecycleVerificationCodes sets to null code and long_code values so that status can be retained longer, but the codes are recycled into the pool.
func (*Database) RotateTokenSigningKey ¶ added in v0.20.0
func (db *Database) RotateTokenSigningKey(ctx context.Context, kms keys.KeyVersionCreator, parent string, actor Auditable) (*TokenSigningKey, error)
RotateTokenSigningKey creates a new key in the upstream kms provider. If creating the upstream key fails, an error is returned. If the upstream key is successfully created, a new TokenSigningKey record is created in the database (not yet active). Finally, the new key is set as the active key.
func (*Database) SMSFromNumbers ¶ added in v0.19.0
func (db *Database) SMSFromNumbers(scopes ...Scope) ([]*SMSFromNumber, error)
SMSFromNumbers returns the list of SMS from numbers in the system.
func (*Database) SaveAuditEntry ¶ added in v0.17.0
func (db *Database) SaveAuditEntry(a *AuditEntry) error
SaveAuditEntry saves the audit entry.
func (*Database) SaveAuthorizedApp ¶ added in v0.3.0
func (db *Database) SaveAuthorizedApp(a *AuthorizedApp, actor Auditable) error
SaveAuthorizedApp saves the authorized app.
func (*Database) SaveEmailConfig ¶ added in v0.14.0
func (db *Database) SaveEmailConfig(s *EmailConfig) error
SaveEmailConfig creates or updates an email configuration record.
func (*Database) SaveKeyServerStats ¶ added in v0.20.0
func (db *Database) SaveKeyServerStats(stats *KeyServerStats) error
SaveKeyServerStats stores the configuration for gathering key-server statistics
func (*Database) SaveKeyServerStatsDay ¶ added in v0.20.0
func (db *Database) SaveKeyServerStatsDay(day *KeyServerStatsDay) error
SaveKeyServerStatsDay stores a single day of key-server statistics
func (*Database) SaveMembership ¶ added in v0.19.0
func (db *Database) SaveMembership(m *Membership, actor Auditable) error
SaveMembership saves the membership details. Should have a userID and a realmID to identify it.
func (*Database) SaveMobileApp ¶ added in v0.10.0
SaveMobileApp saves the mobile app.
func (*Database) SaveSMSConfig ¶
SaveSMSConfig creates or updates an SMS configuration record.
func (*Database) SaveSecret ¶ added in v0.27.0
SaveSecret creates or updates the secret.
func (*Database) SaveTokenSigningKey ¶ added in v0.20.0
func (db *Database) SaveTokenSigningKey(key *TokenSigningKey, actor Auditable) error
SaveTokenSigningKey saves the token signing key.
func (*Database) SaveUserStat ¶ added in v0.18.0
SaveUserStat saves some UserStats to the database. This function is provided for testing only.
func (*Database) SaveVerificationCode ¶
func (db *Database) SaveVerificationCode(vc *VerificationCode, realm *Realm) error
SaveVerificationCode created or updates a verification code in the database. Max age represents the maximum age of the test date [optional] in the record.
func (*Database) SetRawDB ¶ added in v0.19.0
SetRawDB sets the underlying gorm database. This is publicly exposed for tests.
func (*Database) SetSecretResolver ¶ added in v0.27.0
func (db *Database) SetSecretResolver(r *SecretResolver)
SetSecretResolver sets the underlying secret resolver. This is publicly exposed for tests.
func (*Database) SupportsPerRealmSigning ¶ added in v0.5.0
SupportsPerRealmSigning returns true if the configuration supports application managed signing keys.
func (*Database) SyncRealmTranslations ¶ added in v0.30.0
func (db *Database) SyncRealmTranslations(realmID uint, localizations []*appsync.Localization) (*TranslationSyncResult, error)
func (*Database) SystemEmailConfig ¶ added in v0.14.0
func (db *Database) SystemEmailConfig() (*EmailConfig, error)
SystemEmailConfig returns the system email config, if one exists
func (*Database) SystemSMSConfig ¶ added in v0.10.0
SystemSMSConfig returns the system SMS config, if one exists
func (*Database) TouchUserRevokeCheck ¶ added in v0.5.0
TouchUserRevokeCheck updates the revoke check time on the user. It updates the column directly and does not invoke callbacks.
func (*Database) TryLock ¶ added in v0.20.0
func (db *Database) TryLock(ctx context.Context, lockName string, lockDuration time.Duration) (bool, error)
TryLock is used to ensure that only one app sync process runs per AppSyncPeriod duration.
func (*Database) UntouchUserRevokeCheck ¶ added in v0.17.0
UntouchUserRevokeCheck removes the last revoke check, forcing it to occur on next auth.
func (*Database) UpdateStats ¶ added in v0.21.0
func (db *Database) UpdateStats(ctx context.Context, codes ...*VerificationCode)
UpdateStats increments VerificationCode statistics incrementing stats but the number issued.
func (*Database) VerifyAPIKeySignature ¶ added in v0.3.0
VerifyAPIKeySignature verifies the signature matches the expected value for the key. It does this by computing the expected signature and then doing a constant-time comparison against the provided signature.
func (*Database) VerifyCodeAndIssueToken ¶
func (db *Database) VerifyCodeAndIssueToken(request *IssueTokenRequest) (*Token, error)
VerifyCodeAndIssueToken takes a previously issued verification code and exchanges it for a long term token. The verification code must not have expired and must not have been previously used. Both acctions are done in a single database transaction. The verCode can be the "short code" or the "long code" which impacts expiry time.
The long term token can be used later to sign keys when they are submitted.
type DurationSeconds ¶ added in v0.4.0
type DurationSeconds struct { Duration time.Duration // AsString allows this value to be updated and parsed using the Update() method. AsString string }
DurationSeconds is a custom type for writing and reading a time.Duration to be stored as seconds in the database.
func FromDuration ¶ added in v0.5.0
func FromDuration(d time.Duration) DurationSeconds
func (*DurationSeconds) Days ¶ added in v0.11.0
func (d *DurationSeconds) Days() int64
func (*DurationSeconds) Scan ¶ added in v0.4.0
func (d *DurationSeconds) Scan(src interface{}) error
Scan takes a int64 value in seconds and converts that to a time.Duration
func (*DurationSeconds) Update ¶ added in v0.5.0
func (d *DurationSeconds) Update() error
Update attempts to parse the AsString value and set is as the duration
type DynamicTranslation ¶ added in v0.30.0
type DynamicTranslation struct { Errorable // ID is an auto-increment primary key ID uint // RealmID realm that this translation belongs to. RealmID uint // MessageID is the ID of the message. MessageID string // Local is the local / language represented. Locale string // Message is the localized message Message string CreatedAt time.Time UpdatedAt time.Time }
DynamicTranslation stores a per-realm localized string that can be used for user-facing content (currently only user-report webview).
func (*DynamicTranslation) Key ¶ added in v0.30.0
func (d *DynamicTranslation) Key() string
Key returns the key for this translation, realmID-locale-msgID
type EmailConfig ¶ added in v0.14.0
type EmailConfig struct { gorm.Model Errorable // email Config belongs to exactly one realm. RealmID uint `gorm:"type:integer"` // ProviderType is the email provider type - it's used to determine the // underlying configuration. ProviderType email.ProviderType `gorm:"type:varchar(100)"` SMTPAccount string `gorm:"type:varchar(250)"` SMTPHost string `gorm:"type:varchar(250)"` SMTPPort string `gorm:"type:varchar(250)"` // SMTPPassword is encrypted/decrypted automatically by callbacks. The // cache fields exist as optimizations. SMTPPassword string `gorm:"type:varchar(250)" json:"-"` // ignored by zap's JSON formatter SMTPPasswordPlaintextCache string `gorm:"-"` SMTPPasswordCiphertextCache string `gorm:"-"` // IsSystem determines if this is a system-level email configuration. There can // only be one system-level email configuration. IsSystem bool `gorm:"type:bool; not null; default:false;"` }
EmailConfig represents and email configuration.
func (*EmailConfig) BeforeSave ¶ added in v0.14.0
func (e *EmailConfig) BeforeSave(tx *gorm.DB) error
type Errorable ¶ added in v0.4.0
type Errorable struct {
// contains filtered or unexported fields
}
Errorable defines an embeddable struct for managing errors on models.
func (*Errorable) ErrorMessages ¶ added in v0.4.0
ErrorMessages returns the list of error messages.
func (*Errorable) ErrorOrNil ¶ added in v0.19.0
ErrorOrNil returns ErrValidationFailed if there are any errors, or nil if there are none.
type ExternalIssuerStat ¶ added in v0.17.1
type ExternalIssuerStat struct { Date time.Time `gorm:"column:date; type:date;"` RealmID uint `gorm:"column:realm_id; type:int"` IssuerID string `gorm:"column:issuer_id; type:varchar(255)"` CodesIssued uint `gorm:"column:codes_issued; type:int;"` }
ExternalIssuerStat represents statistics related to a user in the database.
type ExternalIssuerStats ¶ added in v0.17.1
type ExternalIssuerStats []*ExternalIssuerStat
ExternalIssuerStats is a collection of external issuer stats.
func (ExternalIssuerStats) MarshalCSV ¶ added in v0.17.1
func (s ExternalIssuerStats) MarshalCSV() ([]byte, error)
MarshalCSV returns bytes in CSV format.
func (ExternalIssuerStats) MarshalJSON ¶ added in v0.17.1
func (s ExternalIssuerStats) MarshalJSON() ([]byte, error)
MarshalJSON is a custom JSON marshaller.
func (*ExternalIssuerStats) UnmarshalJSON ¶ added in v0.17.1
func (s *ExternalIssuerStats) UnmarshalJSON(b []byte) error
type GormZapLogger ¶ added in v0.23.0
type GormZapLogger struct {
// contains filtered or unexported fields
}
GormZapLogger is a gorm logger than writes to a zap logger for structured logging.
func NewGormZapLogger ¶ added in v0.23.0
func NewGormZapLogger(logger *zap.SugaredLogger) (*GormZapLogger, error)
NewGormZapLogger creates a new gorm logger.
func (*GormZapLogger) Print ¶ added in v0.23.0
func (l *GormZapLogger) Print(v ...interface{})
Print satisfies gorm's interface for a logger.
type IssueTokenRequest ¶ added in v0.25.0
type IssueTokenRequest struct { Time time.Time AuthApp *AuthorizedApp VerCode string Nonce []byte AcceptTypes api.AcceptTypes ExpireAfter time.Duration OS OSType }
IssueTokenRequest is used to request the validation of a verification code in order to issue a token
type JSONRealmStatStatsData ¶ added in v0.23.0
type JSONRealmStatStatsData struct { CodesIssued uint `json:"codes_issued"` CodesClaimed uint `json:"codes_claimed"` CodesInvalid uint `json:"codes_invalid"` CodesInvalidByOS CodesInvalidByOSData `json:"codes_invalid_by_os"` UserReportsIssued uint `json:"user_reports_issued"` UserReportsClaimed uint `json:"user_reports_claimed"` TokensClaimed uint `json:"tokens_claimed"` TokensInvalid uint `json:"tokens_invalid"` UserReportTokensClaimed uint `json:"user_report_tokens_claimed"` CodeClaimMeanAge uint `json:"code_claim_mean_age_seconds"` CodeClaimDistribution []int32 `json:"code_claim_age_distribution"` }
type KeyServerStats ¶ added in v0.20.0
type KeyServerStats struct { Errorable // RealmId that these stats belong to. RealmID uint `gorm:"column:realm_id; primary_key; type:integer; not null;"` // KeyServerURLOverride allows a realm to override the system's URL with its own KeyServerURLOverride string `gorm:"column:key_server_url_override; type:text;"` // KeyServerAudience allows a realm to override the system's audience KeyServerAudienceOverride string `gorm:"column:key_server_audience_override; type:text;"` }
KeyServerStats represents statistics for a key-server for this realm
func (*KeyServerStats) BeforeSave ¶ added in v0.20.0
func (kss *KeyServerStats) BeforeSave(tx *gorm.DB) error
BeforeSave runs validations. If there are errors, the save fails.
type KeyServerStatsDay ¶ added in v0.20.0
type KeyServerStatsDay struct { Errorable // RealmId that these stats belong to. RealmID uint `gorm:"column:realm_id; primary_key; type:integer; not null;"` // Day will be set to midnight UTC of the day represented. An individual day // isn't released until there is a minimum threshold for updates has been met. Day time.Time `gorm:"column:day; primary_key;"` // PublishRequests is a count of requests per OS // where the index corresponds to the value of OSType PublishRequests pq.Int64Array `gorm:"column:publish_requests; type:bigint[];"` TotalTEKsPublished int64 `gorm:"column:total_teks_published; type:bigint; not null; default: 0;"` // RevisionRequests is the number of publish requests that contained at least one TEK revision. RevisionRequests int64 `gorm:"column:revision_requests; type:bigint; not null; default: 0;"` // TEKAgeDistribution shows a distribution of the oldest tek in an upload. // The count at index 0-15 represent the number of uploads there the oldest TEK is that value. // Index 16 represents > 15 days. TEKAgeDistribution pq.Int64Array `gorm:"column:tek_age_distribution; type:bigint[];"` // OnsetToUploadDistribution shows a distribution of onset to upload, the index is in days. // The count at index 0-29 represents the number of uploads with that symptom onset age. // Index 30 represents > 29 days. OnsetToUploadDistribution pq.Int64Array `gorm:"column:onset_to_upload_distribution; type:bigint[];"` // RequestsMissingOnsetDate is the number of publish requests where no onset date // was provided. These request are not included in the onset to upload distribution. RequestsMissingOnsetDate int64 `gorm:"column:request_missing_onset_date; type:bigint; not null; default: 0;"` }
KeyServerStatsDay represents statistics for each day
func MakeKeyServerStatsDay ¶ added in v0.21.0
func MakeKeyServerStatsDay(realmID uint, d *keyserver.StatsDay) *KeyServerStatsDay
MakeKeyServerStatsDay creates a storage struct from a key-server StatsDay response
func (*KeyServerStatsDay) BeforeSave ¶ added in v0.20.0
func (kssd *KeyServerStatsDay) BeforeSave(tx *gorm.DB) error
BeforeSave runs validations. If there are errors, the save fails.
func (*KeyServerStatsDay) ToResponse ¶ added in v0.21.0
func (kssd *KeyServerStatsDay) ToResponse() *keyserver.StatsDay
ToResponse makes a json-marshallable StatsDay from a KetServerStatsDay
func (*KeyServerStatsDay) TotalPublishRequests ¶ added in v0.23.0
func (kssd *KeyServerStatsDay) TotalPublishRequests() int64
TotalPublishRequests returns the sum of all publish requests for this day, which are stored by operating system.
type LockStatus ¶ added in v0.25.0
type LockStatus struct { gorm.Model Type string `gorm:"type:varchar(50);unique_index"` Generation uint NotBefore time.Time }
LockStatus represents a distributed lock that spaces operations out. These are only self expring locks (NotBefore) and are not explicitly released.
type ManagedKey ¶ added in v0.21.0
type ManagedKey interface { Auditable // GetKID returns the public key version string GetKID() string // ManagedKeyID returns the reference to the key ID in the KMS. ManagedKeyID() string // IsActive() returns true if this key is active IsActive() bool SetManagedKeyID(keyID string) SetActive(active bool) // These are expected to be static across all instances of an implementing type. Table() string Purpose() string }
ManagedKey is an interface that allows for a realm to manage signing keys for different purposes.
type Membership ¶ added in v0.19.0
type Membership struct { Errorable UserID uint User *User RealmID uint Realm *Realm // DefaultSMSTemplateLabel is the label of realm.SMSTextAlternateTemplates or "Default SMS template" // that the user last used to issue codes. This helps the UI remember the default user preference. // Note: This label may not exist if it has been deleted or modified on the realm. DefaultSMSTemplateLabel string `gorm:"type:varchar(255);"` Permissions rbac.Permission // CreatedAt is when the user was added to the realm. UpdatedAt is when the // user's permissions were last updated. Note that UpdatedAt only applies to // the membership's fields, not the user fields (e.g. email, name). CreatedAt time.Time UpdatedAt time.Time }
Membership represents a user's membership in a realm.
func (*Membership) AfterFind ¶ added in v0.19.0
func (m *Membership) AfterFind() error
AfterFind does a sanity check to ensure the User and Realm properties were preloaded and the referenced values exist.
func (*Membership) Can ¶ added in v0.19.0
func (m *Membership) Can(p rbac.Permission) bool
Can returns true if the membership has the checked permission on the realm, false otherwise.
func (*Membership) Cannot ¶ added in v0.19.0
func (m *Membership) Cannot(p rbac.Permission) bool
Cannot returns the opposite of Can
type MobileApp ¶ added in v0.10.0
type MobileApp struct { gorm.Model Errorable // Name is the name of the app. Name string `gorm:"column:name; type:citext;"` // RealmID is the id of the mobile app. RealmID uint `gorm:"column:realm_id;"` Realm *Realm // URL is the link to the app in it's appstore. URL string `gorm:"-"` URLPtr *string `gorm:"column:url; type:text"` // DisableRedirect disables URL redirection in the redirector service for this // app. DisableRedirect bool `gorm:"column:disable_redirect; type:bool; default:false; not null"` // OS is the type of the application we're using (eg, iOS, Android). OS OSType `gorm:"column:os; type:int;"` // Headless indicates that this an and android EN Express headless app. // This is only settable through the app sync service. Headless bool `gorm:"column:headless; type:bool; default:false; not null"` // AppID is a unique string representing the app. // // For iOS this should include the team ID or app ID prefix followed by // the bundle ID. eg. ABCD1234.com.google.test.application AppID string `gorm:"column:app_id; type:varchar(512);"` // SHA is a unique hash of the app. // It is only present for Android devices, and should be of the form: // AA:BB:CC:DD... SHA string `gorm:"column:sha; type:text;"` }
func (*MobileApp) AuditDisplay ¶ added in v0.11.0
type OSType ¶ added in v0.10.0
type OSType int
type Realm ¶
type Realm struct { gorm.Model Errorable // Name is the name of the realm. Name string `gorm:"type:varchar(200);unique_index;"` // RegionCode is both a display attribute and required field for ENX. To // handle NULL and uniqueness, the field is converted from it's ptr type to a // concrete type in callbacks. Do not modify RegionCodePtr directly. RegionCode string `gorm:"-"` RegionCodePtr *string `gorm:"column:region_code; type:varchar(10);"` // WelcomeMessage is arbitrary realm-defined data to display to users after // selecting this realm. If empty, nothing is displayed. The format is // markdown. Do not modify WelcomeMessagePtr directly. WelcomeMessage string `gorm:"-"` WelcomeMessagePtr *string `gorm:"column:welcome_message; type:text;"` // AgencyBackgroundColor, AgencyImage, DefaultLocale are synced from the Google // ENX-Express sync source AgencyBackgroundColor string `gorm:"-"` AgencyBackgroundColorPtr *string `gorm:"column:agency_background_color; type:text;"` AgencyImage string `gorm:"-"` AgencyImagePtr *string `gorm:"column:agency_image; type:text;"` DefaultLocale string `gorm:"-"` DefaultLocalePtr *string `gorm:"column:default_locale; type:text;"` UserReportLearnMoreURL string `gorm:"-"` UserReportLearnMoreURLPtr *string `gorm:"column:user_report_learn_more_url; type:text;"` // UserReportWebhookURL and UserReportWebhookSecret are used as callbacks for // user reports. UserReportWebhookURL string `gorm:"-"` UserReportWebhookURLPtr *string `gorm:"column:user_report_webhook_url; type:text;"` UserReportWebhookSecret string `gorm:"-" json:"-"` UserReportWebhookSecretPtr *string `gorm:"column:user_report_webhook_secret; type:text;" json:"-"` UserReportWebhookSecretPlaintextCache string `gorm:"-"` UserReportWebhookSecretCiphertextCache string `gorm:"-"` // AllowBulkUpload allows users to issue codes from a batch file of test results. AllowBulkUpload bool `gorm:"type:boolean; not null; default:false;"` // Code configuration CodeLength uint `gorm:"type:smallint; not null; default: 8;"` CodeDuration DurationSeconds `gorm:"type:bigint; not null; default: 900;"` // default 15m (in seconds) LongCodeLength uint `gorm:"type:smallint; not null; default: 16;"` LongCodeDuration DurationSeconds `gorm:"type:bigint; not null; default: 86400;"` // default 24h // ShortCodeMaxMinutes can only be set by system admins and allows for a // realm to have a higher max short code duration ShortCodeMaxMinutes uint `gorm:"column:short_code_max_minutes; type:smallint; not null; default: 60;"` // ENXCodeExpirationConfigurable can only be set by system admins and allows // for an ENX realm to change the short code expiration time (normally fixed) ENXCodeExpirationConfigurable bool `gorm:"column:enx_code_expiration_configurable; type:bool; not null; default: false;"` // SMS configuration SMSTextTemplate string `` /* 136-byte string literal not displayed */ SMSTextAlternateTemplates postgres.Hstore `gorm:"column:alternate_sms_templates; type:hstore;"` // SMSCountry is an optional field to hint the default phone picker country // code. SMSCountry string `gorm:"-"` SMSCountryPtr *string `gorm:"column:sms_country; type:varchar(5);"` // CanUseSystemSMSConfig is configured by system administrators to share the // system SMS config with this realm. Note that the system SMS config could be // empty and a local SMS config is preferred over the system value. CanUseSystemSMSConfig bool `gorm:"column:can_use_system_sms_config; type:bool; not null; default:false;"` // UseSystemSMSConfig is a realm-level configuration that lets a realm opt-out // of sending SMS messages using the system-provided SMS configuration. // Without this, a realm would always fallback to the system-level SMS // configuration, making it impossible to opt out of text message sending. UseSystemSMSConfig bool `gorm:"column:use_system_sms_config; type:bool; not null; default:false;"` // SMSFromNumberID is a realm-level configuration that only applies when using // the system SMS configuration. It determines which of the system SMS numbers // to use as the sender when sending text messages. SMSFromNumberID uint `gorm:"-"` SMSFromNumberIDPtr *uint `gorm:"column:sms_from_number_id; type:integer;"` // UseAuthenticatedSMS indicates if this realm wants to sign text messages that are sent // containing verification codes. UseAuthenticatedSMS bool `gorm:"column:use_authenticated_sms; type:bool; not null; default:false;"` // AllowGeneratedSMS indicates if this realm can request generated SMS // messages via the API. If enabled, callers can request a fully-compiled and // signed (if Authenticated SMS is enabled) SMS message to be returned when // calling the issue API. AllowGeneratedSMS bool `gorm:"column:allow_generated_sms; type:bool; not null; default:false;"` // EmailInviteTemplate is the template for inviting new users. EmailInviteTemplate string `gorm:"type:text;"` // EmailPasswordResetTemplate is the template for resetting password. EmailPasswordResetTemplate string `gorm:"type:text;"` // EmailVerifyTemplate is the template used for email verification. EmailVerifyTemplate string `gorm:"type:text;"` // CanUseSystemEmailConfig is configured by system administrators to share the // system email config with this realm. Note that the system email config could be // empty and a local email config is preferred over the system value. CanUseSystemEmailConfig bool `gorm:"column:can_use_system_email_config; type:bool; not null; default:false;"` // UseSystemEmailConfig is a realm-level configuration that lets a realm opt-out // of sending email messages using the system-provided email configuration. // Without this, a realm would always fallback to the system-level email // configuration, making it impossible to opt out of text message sending. UseSystemEmailConfig bool `gorm:"column:use_system_email_config; type:bool; not null; default:false;"` // MFAMode represents the mode for Multi-Factor-Authorization requirements for the realm. MFAMode AuthRequirement `gorm:"type:smallint; not null; default: 0;"` // MFARequiredGracePeriod defines how long after creation a user may skip adding // a second auth factor before the server requires it. MFARequiredGracePeriod DurationSeconds `gorm:"type:bigint; not null; default: 0;"` // EmailVerifiedMode represents the mode for email verification requirements for the realm. EmailVerifiedMode AuthRequirement `gorm:"type:smallint; not null; default: 0;"` // PasswordRotationPeriodDays is the number of days before the user must // rotate their password. PasswordRotationPeriodDays uint `gorm:"type:smallint; not null; default: 0;"` // PasswordRotationWarningDays is the number of days before Password expiry // that the user should receive a warning. PasswordRotationWarningDays uint `gorm:"type:smallint; not null; default: 0;"` // AllowedCIDRs is the list of allowed IPs to the various services. AllowedCIDRsAdminAPI pq.StringArray `gorm:"column:allowed_cidrs_adminapi; type:varchar(50)[];"` AllowedCIDRsAPIServer pq.StringArray `gorm:"column:allowed_cidrs_apiserver; type:varchar(50)[];"` AllowedCIDRsServer pq.StringArray `gorm:"column:allowed_cidrs_server; type:varchar(50)[];"` // AllowedTestTypes is the type of tests that this realm permits. The default // value is to allow all test types. AllowedTestTypes TestType `gorm:"type:smallint; not null; default: 14;"` // AllowUserReportWebView - if enabled, will use the user report web view // on the redirect server for this realm. If disabled, it will 404. AllowUserReportWebView bool `gorm:"column:allow_user_report_web_view; type:bool; not null; default:false"` // AllowAdminUserReport - is the adminapi:/api/issue allowed to use the user-report // test type if enabled on the realm. AllowAdminUserReport bool `gorm:"column:allow_admin_user_report; type:bool; not null; default:false"` // RequireDate requires that verifications on this realm require a test or // symptom date (either). The default behavior is to not require a date. RequireDate bool `gorm:"type:boolean; not null; default:false;"` // Signing Key Settings UseRealmCertificateKey bool `gorm:"type:boolean; default: false;"` CertificateIssuer string `gorm:"type:varchar(150); default: '';"` CertificateAudience string `gorm:"type:varchar(150); default: '';"` CertificateDuration DurationSeconds `gorm:"type:bigint; default: 900;"` // 15m AutoRotateCertificateKey bool `gorm:"type:boolean; default: false;"` // EN Express EnableENExpress bool `gorm:"type:boolean; default: false;"` // AbusePreventionEnabled determines if abuse protection is enabled. AbusePreventionEnabled bool `gorm:"type:boolean; not null; default:false;"` // AbusePreventionLimit is the configured daily limit for the realm. This value is populated // by the nightly aggregation job and is based on a statistical model from // historical code issuance data. AbusePreventionLimit uint `gorm:"type:integer; not null; default:10;"` // AbusePreventionLimitFactor is the factor against the predicted model for the day which // determines the total number of codes that can be issued for the realm on // the day. For example, if the predicted value was 50 and this value was 1.5, // the realm could generate 75 codes today before triggering abuse prevention. // Similarly, if this value was 0.5, the realm could only generate 25 codes // before triggering abuse protections. AbusePreventionLimitFactor float32 `gorm:"type:numeric(6, 3); not null; default:1.0;"` // LastCodesClaimedRatio is the percentage of codes claimed (out of all codes // issued) for the most recent completely full UTC day. CodesClaimedRatioMean and // CodesClaimedRatioStddev represent the mean and standard deviation for the // previous N days of statistics (see modeler for exact numbers). // // The *Tokens fields are identical, except the represent the ratio between // codes claimed and tokens claimed (aka app-side redemption). A high // deviation here likely indicates some kind of application-level issue. // // These fields are set by the modeler. LastCodesClaimedRatio float64 `gorm:"column:last_codes_claimed_ratio; type:numeric(10,8); not null; default:0.0;"` CodesClaimedRatioMean float64 `gorm:"column:codes_claimed_ratio_mean; type:numeric(10,8); not null; default:0.0;"` CodesClaimedRatioStddev float64 `gorm:"column:codes_claimed_ratio_stddev; type:numeric(10,8); not null; default:0.0;"` // Relations to items that belong to a realm. Codes []*VerificationCode `gorm:"PRELOAD:false; SAVE_ASSOCIATIONS:false; ASSOCIATION_AUTOUPDATE:false, ASSOCIATION_SAVE_REFERENCE:false;"` Tokens []*Token `gorm:"PRELOAD:false; SAVE_ASSOCIATIONS:false; ASSOCIATION_AUTOUPDATE:false, ASSOCIATION_SAVE_REFERENCE:false;"` // contains filtered or unexported fields }
Realm represents a tenant in the system. Typically this corresponds to a geography or a public health authority scope. This is used to manage user logins.
func NewRealmWithDefaults ¶ added in v0.4.0
NewRealmWithDefaults initializes a new Realm with the default settings populated, and the provided name. It does NOT save the Realm to the database.
func (*Realm) AbusePreventionEffectiveLimit ¶ added in v0.9.0
AbusePreventionEffectiveLimit returns the effective limit, multiplying the limit by the limit factor and rounding up.
func (*Realm) AddUserReportToAllowedTestTypes ¶ added in v0.25.0
func (r *Realm) AddUserReportToAllowedTestTypes()
AddUserReportToAllowedTestTypes adds the TestTypeUserReport to this realm. This does not save the realm to the database.
func (*Realm) AllowsUserReport ¶ added in v0.25.0
AllowsUserReport returns true if this realm has enabled user initiated test reporting.
func (*Realm) AuditDisplay ¶ added in v0.11.0
func (*Realm) BeforeSave ¶ added in v0.4.0
BeforeSave runs validations. If there are errors, the save fails.
func (*Realm) BuildInviteEmail ¶ added in v0.15.0
BuildInviteEmail replaces certain strings with the right values for invitations.
func (*Realm) BuildPasswordResetEmail ¶ added in v0.15.0
BuildPasswordResetEmail replaces certain strings with the right values for password reset.
func (*Realm) BuildSMSText ¶ added in v0.4.0
func (r *Realm) BuildSMSText(code, longCode string, enxDomain, templateLabel string) (string, error)
BuildSMSText replaces certain strings with the right values.
func (*Realm) BuildVerifyEmail ¶ added in v0.15.0
BuildVerifyEmail replaces certain strings with the right values for email verification.
func (*Realm) CanUpgradeToRealmSigningKeys ¶ added in v0.5.0
func (*Realm) CodesClaimedRatioAnomalous ¶ added in v1.1.0
CodesClaimedRatioAnomalous returns true if the ratio of codes issued to codes claimed is less than the predicted mean by more than one standard deviation.
func (*Realm) CreateAuthorizedApp ¶ added in v0.4.0
func (r *Realm) CreateAuthorizedApp(db *Database, app *AuthorizedApp, actor Auditable) (string, error)
CreateAuthorizedApp generates a new API key and assigns it to the specified app. Note that the API key is NOT stored in the database, only a hash. The only time the API key is available is as the string return parameter from invoking this function.
func (*Realm) CreateSMSSigningKeyVersion ¶ added in v0.21.0
func (r *Realm) CreateSMSSigningKeyVersion(ctx context.Context, db *Database, actor Auditable) (string, error)
CreateSMSSigningKeyVersion creates a new SMS signing key version on the key manager and saves a reference to the new key version in the database.
func (*Realm) CreateSigningKeyVersion ¶ added in v0.5.1
func (r *Realm) CreateSigningKeyVersion(ctx context.Context, db *Database, actor Auditable) (string, error)
CreateSigningKeyVersion creates a new signing key version on the key manager and saves a reference to the new key version in the database. If creating the key in the key manager fails, the database is not updated. However, if updating the signing key in the database fails, the key is NOT deleted from the key manager.
func (*Realm) CurrentSMSSigningKey ¶ added in v0.21.0
func (r *Realm) CurrentSMSSigningKey(db *Database) (*SMSSigningKey, error)
CurrentSMSSigningKey returns the currently active SMS signing key, the one marked active in the database. There cannot be more than one active key due to a database-level constraint.
func (*Realm) CurrentSigningKey ¶ added in v0.21.0
func (r *Realm) CurrentSigningKey(db *Database) (*SigningKey, error)
CurrentSigningKey returns the currently active certificate signing key, the one marked active in the database. If there is more than one active, the most recently created one wins. Should not occur due to transactional update.
func (*Realm) DefaultSMSTextTemplate ¶ added in v0.32.0
DefaultSMSTextTemplate returns correct default SMS Template for the realm.
func (*Realm) DefaultUserReportSMSTextTemplate ¶ added in v0.32.0
DefaultUserReportSMSTextTemplate returns the correct default User Report template for the realm.
func (*Realm) DestroySMSSigningKeyVersion ¶ added in v0.21.0
func (*Realm) DestroySigningKeyVersion ¶ added in v0.5.1
func (r *Realm) DestroySigningKeyVersion(ctx context.Context, db *Database, id interface{}, actor Auditable) error
DestroySigningKeyVersion destroys the given key version in both the database and the key manager. ID is the primary key ID from the database. If the id does not exist, it does nothing.
func (*Realm) EffectiveMFAMode ¶ added in v0.11.0
func (r *Realm) EffectiveMFAMode(t time.Time) AuthRequirement
EffectiveMFAMode returns the realm's default MFAMode but first checks if the time is in the grace-period (if so, required becomes prompt).
func (*Realm) EmailConfig ¶ added in v0.14.0
func (r *Realm) EmailConfig(db *Database) (*EmailConfig, error)
EmailConfig returns the email configuration for this realm, if one exists. If the realm is configured to use the system email configuration, that configuration is preferred.
func (*Realm) EmailProvider ¶ added in v0.14.0
EmailProvider returns the email provider for the realm. If no email configuration exists, it returns nil. If any errors occur creating the provider, they are returned.
func (*Realm) ExternalIssuerStats ¶ added in v0.17.1
func (r *Realm) ExternalIssuerStats(db *Database) (ExternalIssuerStats, error)
ExternalIssuerStats returns the external issuer stats for this realm. If no stats exist, returns an empty slice.
func (*Realm) ExternalIssuerStatsCached ¶ added in v0.19.0
func (r *Realm) ExternalIssuerStatsCached(ctx context.Context, db *Database, cacher cache.Cacher) (ExternalIssuerStats, error)
ExternalIssuerStatsCached is stats, but cached.
func (*Realm) FindAuthorizedApp ¶ added in v0.3.0
func (r *Realm) FindAuthorizedApp(db *Database, id interface{}) (*AuthorizedApp, error)
FindAuthorizedApp finds the authorized app by the given id associated to the realm.
func (*Realm) FindMobileApp ¶ added in v0.10.0
FindMobileApp finds the mobile app by the given id associated with the realm.
func (*Realm) FindVerificationCodeByUUID ¶ added in v0.16.0
func (r *Realm) FindVerificationCodeByUUID(db *Database, uuidStr string) (*VerificationCode, error)
FindVerificationCodeByUUID find a verification codes by UUID. It returns NotFound if the UUID is invalid.
func (*Realm) GetCodeDurationMinutes ¶ added in v0.4.0
GetCodeDurationMinutes is a helper for the HTML rendering to get a round minutes value.
func (*Realm) GetLongCodeDurationHours ¶ added in v0.4.0
GetLongCodeDurationHours is a helper for the HTML rendering to get a round hours value.
func (*Realm) HasSMSConfig ¶ added in v0.3.0
HasSMSConfig returns true if the realm has an SMS config, false otherwise. This does not perform the KMS encryption/decryption, so it's more efficient that loading the full SMS config.
func (*Realm) HistoricalCodesIssued ¶ added in v0.9.0
HistoricalCodesIssued returns a slice of the historical codes issued for this realm by date descending.
func (*Realm) ListAudits ¶ added in v0.16.0
func (r *Realm) ListAudits(db *Database, p *pagination.PageParams, scopes ...Scope) ([]*AuditEntry, *pagination.Paginator, error)
ListAudits returns the list audit events which match the given criteria.
func (*Realm) ListAuthorizedApps ¶ added in v0.4.0
func (r *Realm) ListAuthorizedApps(db *Database, p *pagination.PageParams, scopes ...Scope) ([]*AuthorizedApp, *pagination.Paginator, error)
func (*Realm) ListChaffEvents ¶ added in v0.24.0
func (r *Realm) ListChaffEvents(db *Database) ([]*RealmChaffEvent, error)
ListChaffEvents returns the chaff events for the realm, ordered by date.
func (*Realm) ListMemberships ¶ added in v0.19.0
func (r *Realm) ListMemberships(db *Database, p *pagination.PageParams, scopes ...Scope) ([]*Membership, *pagination.Paginator, error)
ListMemberships lists the realm's memberships.
func (*Realm) ListMobileApps ¶ added in v0.10.0
func (r *Realm) ListMobileApps(db *Database, p *pagination.PageParams, scopes ...Scope) ([]*MobileApp, *pagination.Paginator, error)
ListMobileApps gets all the mobile apps for the realm.
func (*Realm) ListSMSSigningKeys ¶ added in v0.21.0
func (r *Realm) ListSMSSigningKeys(db *Database) ([]*SMSSigningKey, error)
ListSMSSigningKeys returns the non-deleted signing keys for a realm ordered by created_at desc.
func (*Realm) ListSigningKeys ¶ added in v0.5.0
func (r *Realm) ListSigningKeys(db *Database) ([]*SigningKey, error)
ListSigningKeys returns the non-deleted signing keys for a realm ordered by created_at desc.
func (*Realm) MembershipPermissionMap ¶ added in v0.19.0
MembershipPermissionMap returns a map where the key is the ID of a user and the value is the permissions for that user.
func (*Realm) QuotaKey ¶ added in v0.12.1
QuotaKey returns the unique and consistent key to use for storing quota data for this realm, given the provided HMAC key.
func (*Realm) RecordChaffEvent ¶ added in v0.24.0
RecordChaffEvent records that the realm received a chaff event on the given date. This is not a counter, but a boolean: chaff was either received or it wasn't. This is used to help server operators identify if an app is not sending chaff requests.
func (*Realm) RenderWelcomeMessage ¶ added in v0.9.0
RenderWelcomeMessage message renders the realm's welcome message.
func (*Realm) ResetSMSTextTemplates ¶ added in v0.32.0
func (r *Realm) ResetSMSTextTemplates()
ResetSMSTextTemplates will update all of the templates based on the ENX Redirect setting
func (*Realm) SMSConfig ¶
SMSConfig returns the SMS configuration for this realm, if one exists. If the realm is configured to use the system SMS configuration, that configuration is preferred.
func (*Realm) SMSErrorStats ¶ added in v1.1.0
func (r *Realm) SMSErrorStats(db *Database) (SMSErrorStats, error)
SMSErrorStats returns the sms error stats for this realm.
func (*Realm) SMSErrorStatsCached ¶ added in v1.1.0
func (r *Realm) SMSErrorStatsCached(ctx context.Context, db *Database, cacher cache.Cacher) (SMSErrorStats, error)
SMSErrorStatsCached is stats, but cached.
func (*Realm) SMSProvider ¶ added in v0.3.0
SMSProvider returns the SMS provider for the realm. If no sms configuration exists, it returns nil. If any errors occur creating the provider, they are returned.
func (*Realm) SMSTemplateExpansionMax ¶ added in v0.32.0
SMSTemplateExpansionMax returns database.SMSTemplateExpansionMax. Convenance for utilizing in HTML templates.
func (*Realm) SMSTemplateMaxLength ¶ added in v0.32.0
SMSTemplateMaxLength returns database.SMSTemplateMaxLength. Convenance for utilizing in HTML templates.
func (*Realm) SetActiveSMSSigningKey ¶ added in v0.21.0
SetActiveSMSSigningKey sets a specific signing key to active=true for the realm, and transactionally sets all other signing keys to inactive. It accepts the database primary key ID but returns the KID of the now-active key.
func (*Realm) SetActiveSigningKey ¶ added in v0.5.0
SetActiveSigningKey sets a specific signing key to active=true for the realm, and transactionally sets all other signing keys to inactive. It accepts the database primary key ID but returns the KID of the now-active key.
func (*Realm) Stats ¶ added in v0.8.0
func (r *Realm) Stats(db *Database) (RealmStats, error)
Stats returns the usage statistics for this realm. If no stats exist, returns an empty array.
func (*Realm) StatsCached ¶ added in v0.19.0
func (r *Realm) StatsCached(ctx context.Context, db *Database, cacher cache.Cacher) (RealmStats, error)
StatsCached is stats, but cached.
func (*Realm) UserStats ¶ added in v0.17.1
func (r *Realm) UserStats(db *Database) (RealmUserStats, error)
UserStats returns the stats by user.
func (*Realm) UserStatsCached ¶ added in v0.19.0
func (r *Realm) UserStatsCached(ctx context.Context, db *Database, cacher cache.Cacher) (RealmUserStats, error)
UserStatsCached is stats, but cached.
func (*Realm) ValidTestType ¶ added in v0.4.0
ValidTestType returns true if the given test type string is valid for this realm, false otherwise.
type RealmChaffEvent ¶ added in v0.24.0
type RealmChaffEvent struct { // RealmID is the realm for which the chaff request existed. RealmID uint // Date is the UTC date (truncated to midnight) for which one or more chaff // request existed. Date time.Time // Present indicates whether the chaff event was present. Present bool }
RealmChaffEvent is a record that indicates a realm received a chaff event on the given date.
type RealmManagedKey ¶ added in v0.21.0
type RealmManagedKey interface { ManagedKey SetRealmID(id uint) }
RealmManagedKey indicates that this key is owned by a realm.
type RealmStat ¶ added in v0.17.1
type RealmStat struct { Date time.Time `gorm:"column:date; type:date; not null;"` RealmID uint `gorm:"column:realm_id; type:integer; not null;"` // CodesIssued is the total number of codes issued. CodesClaimed are // successful claims. CodesInvalid are codes that have failed to claim // (expired or not found). This includes UserReportsIssued and // UserReportsClaimed. CodesIssued uint `gorm:"column:codes_issued; type:integer; not null; default:0;"` CodesClaimed uint `gorm:"column:codes_claimed; type:integer; not null; default:0;"` CodesInvalid uint `gorm:"column:codes_invalid; type:integer; not null; default:0;"` // CodesInvalidByOS is an array where the index is the controller.OperatingSystem enums. CodesInvalidByOS pq.Int64Array `gorm:"column:codes_invalid_by_os; type:bigint[];"` // UserReportsIssued is the specific number of codes that were issued because // the user initiated a self-report request. These numbers are also included // in the sum of codes issued and codes claimed. UserReportsIssued uint `gorm:"column:user_reports_issued; type:integer; not null; default:0;"` UserReportsClaimed uint `gorm:"column:user_reports_claimed; type:integer; not null; default:0;"` // TokensClaimed is the number of tokens exchanged for a certificate. // TokensInvalid is the number of tokens which failed to exchange due to // a user error. This includes UserReportTokensClaimed. TokensClaimed uint `gorm:"column:tokens_claimed; type:integer; not null; default:0;"` TokensInvalid uint `gorm:"column:tokens_invalid; type:integer; not null; default:0;"` // UserReportTokensClaimed is the number of tokens claimed that represent a user // initiated report. This sum is also included in tokens claimed. UserReportTokensClaimed uint `gorm:"column:user_report_tokens_claimed; type:integer; not null; default:0;"` // CodeClaimAgeDistribution shows a distribution of time from code issue to claim. // Buckets are: 1m, 5m, 15m, 30m, 1h, 2h, 3h, 6h, 12h, 24h, >24h CodeClaimAgeDistribution pq.Int32Array `gorm:"column:code_claim_age_distribution; type:int[];"` // CodeClaimMeanAge tracks the average age to claim a code. CodeClaimMeanAge DurationSeconds `gorm:"column:code_claim_mean_age; type:bigint; not null; default: 0;"` }
RealmStat represents statistics related to a user in the database.
func (*RealmStat) CodeClaimAgeDistributionAsStrings ¶ added in v0.23.0
CodeClaimAgeDistributionAsStrings returns CodeClaimAgeDistribution as []string instead of []int32. Useful for serialization.
type RealmStats ¶ added in v0.8.0
type RealmStats []*RealmStat
RealmStats represents a logical collection of stats of a realm.
func (RealmStats) MarshalCSV ¶ added in v0.17.1
func (s RealmStats) MarshalCSV() ([]byte, error)
MarshalCSV returns bytes in CSV format.
func (RealmStats) MarshalJSON ¶ added in v0.17.1
func (s RealmStats) MarshalJSON() ([]byte, error)
MarshalJSON is a custom JSON marshaller.
func (*RealmStats) UnmarshalJSON ¶ added in v0.17.1
func (s *RealmStats) UnmarshalJSON(b []byte) error
type RealmUserStat ¶ added in v0.17.1
type RealmUserStat struct { Date time.Time RealmID uint UserID uint Name string Email string CodesIssued uint }
RealmUserStat is an interim data structure representing a single date/user statistic. It does not correspond to a single database table, but is rather a join across multiple tables.
type RealmUserStats ¶ added in v0.12.1
type RealmUserStats []*RealmUserStat
RealmUserStats is a grouping collection of RealmUserStat.
func (RealmUserStats) MarshalCSV ¶ added in v0.17.1
func (s RealmUserStats) MarshalCSV() ([]byte, error)
MarshalCSV returns bytes in CSV format.
func (RealmUserStats) MarshalJSON ¶ added in v0.17.1
func (s RealmUserStats) MarshalJSON() ([]byte, error)
MarshalJSON is a custom JSON marshaller.
func (*RealmUserStats) UnmarshalJSON ¶ added in v0.17.1
func (s *RealmUserStats) UnmarshalJSON(b []byte) error
type SMSConfig ¶
type SMSConfig struct { gorm.Model Errorable // SMS Config belongs to exactly one realm. RealmID uint // ProviderType is the SMS provider type - it's used to determine the // underlying configuration. ProviderType sms.ProviderType `gorm:"type:varchar(100)"` // Twilio configuration options. TwilioAccountSid string `gorm:"type:varchar(250)"` // E.164 format telephone number or // Twilio messaging service identifier see: https://support.twilio.com/hc/en-us/articles/223134387-What-is-a-Message-SID- TwilioFromNumber string `gorm:"type:varchar(255)"` // TwilioAuthToken is encrypted/decrypted automatically by callbacks. The // cache fields exist as optimizations. TwilioAuthToken string `gorm:"type:varchar(250)" json:"-"` // ignored by zap's JSON formatter TwilioAuthTokenPlaintextCache string `gorm:"-"` TwilioAuthTokenCiphertextCache string `gorm:"-"` // IsSystem determines if this is a system-level SMS configuration. There can // only be one system-level SMS configuration. IsSystem bool `gorm:"type:bool; not null; default:false;"` }
SMSConfig represents and SMS configuration.
type SMSErrorStat ¶ added in v1.1.0
type SMSErrorStat struct { Date time.Time `gorm:"column:date; type:date;"` RealmID uint `gorm:"column:realm_id; type:int;"` ErrorCode string `gorm:"column:error_code; type:text;"` Quantity uint `gorm:"column:quantity; type:int;"` }
SMSErrorStat represents statistics related to a user in the database.
type SMSErrorStats ¶ added in v1.1.0
type SMSErrorStats []*SMSErrorStat
SMSErrorStats is a collection of external issuer stats.
func (SMSErrorStats) MarshalCSV ¶ added in v1.1.0
func (s SMSErrorStats) MarshalCSV() ([]byte, error)
MarshalCSV returns bytes in CSV format.
func (SMSErrorStats) MarshalJSON ¶ added in v1.1.0
func (s SMSErrorStats) MarshalJSON() ([]byte, error)
MarshalJSON is a custom JSON marshaller.
func (*SMSErrorStats) UnmarshalJSON ¶ added in v1.1.0
func (s *SMSErrorStats) UnmarshalJSON(b []byte) error
type SMSFromNumber ¶ added in v0.19.0
type SMSFromNumber struct { Errorable ID uint `gorm:"primary_key;" json:"id,omitempty"` Label string `gorm:"column:label;" json:"label"` Value string `gorm:"column:value;" json:"value"` }
SMSFromNumber represents a source number which can send SMS messages. The table only contains the system SMS from numbers.
func (*SMSFromNumber) BeforeSave ¶ added in v0.19.0
func (s *SMSFromNumber) BeforeSave(tx *gorm.DB) error
type SMSSigningKey ¶ added in v0.21.0
type SMSSigningKey struct { gorm.Model Errorable // A signing key belongs to exactly one realm. RealmID uint // Reference to an exact version of a key in the KMS KeyID string Active bool }
SMSSigningKey represents a reference to a KMS backed signing key version for SMS payload signing.
func (*SMSSigningKey) AuditDisplay ¶ added in v0.21.0
func (s *SMSSigningKey) AuditDisplay() string
AuditDisplay is how the signing key will be displayed in audit entries.
func (*SMSSigningKey) AuditID ¶ added in v0.21.0
func (s *SMSSigningKey) AuditID() string
AuditID is how the signing key is stored in the audit entry.
func (*SMSSigningKey) GetKID ¶ added in v0.21.0
func (s *SMSSigningKey) GetKID() string
GetKID returns the 'kid' field value to use in signing JWTs.
func (*SMSSigningKey) IsActive ¶ added in v0.21.0
func (s *SMSSigningKey) IsActive() bool
func (*SMSSigningKey) ManagedKeyID ¶ added in v0.21.0
func (s *SMSSigningKey) ManagedKeyID() string
func (*SMSSigningKey) Purpose ¶ added in v0.21.0
func (s *SMSSigningKey) Purpose() string
func (*SMSSigningKey) SetActive ¶ added in v0.21.0
func (s *SMSSigningKey) SetActive(active bool)
func (*SMSSigningKey) SetManagedKeyID ¶ added in v0.21.0
func (s *SMSSigningKey) SetManagedKeyID(keyID string)
func (*SMSSigningKey) SetRealmID ¶ added in v0.21.0
func (s *SMSSigningKey) SetRealmID(id uint)
func (*SMSSigningKey) Table ¶ added in v0.21.0
func (s *SMSSigningKey) Table() string
type Scope ¶ added in v0.16.0
Scope is a type alias to a gorm scope. It exists to reduce duplicate and function length. Note this is an ALIAS. It is NOT a new type.
func InConsumableSecretOrder ¶ added in v0.27.0
func InConsumableSecretOrder() Scope
InConsumableSecretOrder is a scope that orders secrets in the order in which they should be consumed.
func OnlySystemAdmins ¶ added in v0.16.0
func OnlySystemAdmins() Scope
OnlySystemAdmins returns a scope that restricts the query to system admins. It's only applicable to functions that query User.
func Unscoped ¶ added in v0.27.0
func Unscoped() Scope
Unscoped returns an unscoped database (for finding soft-deleted records and clearing other scopes).
func WithAppOS ¶ added in v0.17.1
WithAppOS returns a scope that for querying MobileApps by Operating System type.
func WithAuditRealmID ¶ added in v0.17.0
WithAuditRealmID returns a scope that adds querying for Audit events by realm. The provided ID is expected to be stringable (int, uint, string).
func WithAuditTime ¶ added in v0.17.0
WithAuditTime returns a scope that adds querying for Audit events by time.
func WithAuthorizedAppSearch ¶ added in v0.16.0
WithAuthorizedAppSearch returns a scope that adds querying for API keys by name and preview, case-insensitive. It's only applicable to functions that query AuthorizedApp.
func WithAuthorizedAppType ¶ added in v0.21.0
func WithAuthorizedAppType(typ APIKeyType) Scope
WithAuthorizedAppType returns a scope that filters by the given type.
func WithMobileAppSearch ¶ added in v0.16.0
WithMobileAppSearch returns a scope that adds querying for mobile apps by name, case-insensitive. It's only applicable to functions that query MobileApp.
func WithPermissionSearch ¶ added in v0.19.1
func WithPermissionSearch(p rbac.Permission) Scope
WithPermissionSearch searches for memberships which have the given permission.
func WithRealmAutoKeyRotationEnabled ¶ added in v0.20.0
WithRealmAutoKeyRotationEnabled filters by realms which have the auto key rotation enabled/disabled depending on the boolean.
func WithRealmSearch ¶ added in v0.16.0
WithRealmSearch returns a scope that adds querying for realms by name. It's only applicable to functions that query Realm.
func WithUserSearch ¶ added in v0.16.0
WithUserSearch returns a scope that adds querying for users by email and name, case-insensitive. It's only applicable to functions that query User.
func WithoutAuditTest ¶ added in v0.17.0
func WithoutAuditTest() Scope
WithoutAuditTest excludes audit entries related to test entries created from SystemTest.
func WithoutPermissionSearch ¶ added in v0.19.1
func WithoutPermissionSearch(p rbac.Permission) Scope
WithoutPermissionSearch searches for memberships which do not have the given permission.
type Secret ¶ added in v0.27.0
type Secret struct { Errorable // ID is the primary key of the secret. ID uint // Type is the type of secret. Type SecretType // Reference is the pointer to the secret in the secret manager. Reference string // Active is a boolean indicating whether this secret is active. Active bool // CreatedAt, UpdatedAt, and DeletedAt are the timestamps. CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time }
Secret represents the reference to a secret in an upstream secret manager. It exists to facilitate rotation and auditing.
func (*Secret) AuditDisplay ¶ added in v0.27.0
type SecretResolver ¶ added in v0.27.0
type SecretResolver struct {
// contains filtered or unexported fields
}
func NewSecretResolver ¶ added in v0.27.0
func NewSecretResolver() *SecretResolver
NewSecretResolver makes a new secret resolver using the provided database and secret manager instance.
func (*SecretResolver) ClearCaches ¶ added in v0.27.0
func (r *SecretResolver) ClearCaches()
ClearCaches purges all cached data from the references and values cache.
func (*SecretResolver) Resolve ¶ added in v0.27.0
func (r *SecretResolver) Resolve(ctx context.Context, db *Database, sm secrets.SecretManager, typ SecretType) ([][]byte, error)
Resolve resolves all secrets for the provided database secret type to their upstream secret manager values. The mappings of database values to references are cached for a short duration, and the mappings of references to secret values are cached for a very long time (since secret versions are immutable).
func (*SecretResolver) ResolveReferences ¶ added in v0.27.0
func (r *SecretResolver) ResolveReferences(db *Database, typ SecretType) ([]string, error)
ResolveReferences resolves the database references for the given secret type, handling caching where appropriate.
func (*SecretResolver) ResolveValue ¶ added in v0.27.0
func (r *SecretResolver) ResolveValue(ctx context.Context, sm secrets.SecretManager, ref string) ([]byte, error)
ResolveValue resolves a single secret, taking caching into account.
type SigningKey ¶ added in v0.5.0
type SigningKey struct { gorm.Model Errorable // A signing key belongs to exactly one realm. RealmID uint `gorm:"index:realm"` // Reference to an exact version of a key in the KMS KeyID string Active bool }
SigningKey represents a reference to a KMS backed signing key version for verification certificate signing.
func (*SigningKey) AuditDisplay ¶ added in v0.21.0
func (s *SigningKey) AuditDisplay() string
AuditDisplay is how the signing key will be displayed in audit entries.
func (*SigningKey) AuditID ¶ added in v0.21.0
func (s *SigningKey) AuditID() string
AuditID is how the signing key is stored in the audit entry.
func (*SigningKey) GetKID ¶ added in v0.5.0
func (s *SigningKey) GetKID() string
GetKID returns the 'kid' field value to use in signing JWTs.
func (*SigningKey) IsActive ¶ added in v0.21.0
func (s *SigningKey) IsActive() bool
func (*SigningKey) ManagedKeyID ¶ added in v0.21.0
func (s *SigningKey) ManagedKeyID() string
func (*SigningKey) Purpose ¶ added in v0.21.0
func (s *SigningKey) Purpose() string
func (*SigningKey) SetActive ¶ added in v0.21.0
func (s *SigningKey) SetActive(active bool)
func (*SigningKey) SetManagedKeyID ¶ added in v0.21.0
func (s *SigningKey) SetManagedKeyID(keyID string)
func (*SigningKey) SetRealmID ¶ added in v0.21.0
func (s *SigningKey) SetRealmID(id uint)
func (*SigningKey) Table ¶ added in v0.21.0
func (s *SigningKey) Table() string
type Subject ¶
Subject represents the data that is used in the 'sub' field of the token JWT.
func ParseSubject ¶
func (*Subject) SymptomInterval ¶
type TestInstance ¶ added in v0.17.1
type TestInstance struct {
// contains filtered or unexported fields
}
TestInstance is a wrapper around the Docker-based database instance.
func MustTestInstance ¶ added in v0.17.1
func MustTestInstance() *TestInstance
MustTestInstance is NewTestInstance, except it prints errors to stderr and calls os.Exit when finished. Callers can call Close or MustClose().
func NewTestInstance ¶ added in v0.17.1
func NewTestInstance() (*TestInstance, error)
NewTestInstance creates a new Docker-based database instance. It also creates an initial database, runs the migrations, and sets that database as a template to be cloned by future tests.
This should not be used outside of testing, but it is exposed in the package so it can be shared with other packages. It should be called and instantiated in TestMain.
All database tests can be skipped by running `go test -short` or by setting the `SKIP_DATABASE_TESTS` environment variable.
func (*TestInstance) Close ¶ added in v0.17.1
func (i *TestInstance) Close() (retErr error)
Close terminates the test database instance, cleaning up any resources.
func (*TestInstance) MustClose ¶ added in v0.17.1
func (i *TestInstance) MustClose() error
MustClose is like Close except it prints the error to stderr and calls os.Exit.
func (*TestInstance) NewDatabase ¶ added in v0.17.1
func (i *TestInstance) NewDatabase(tb testing.TB, cacher cache.Cacher, opts ...UtilOption) (*Database, *Config)
NewDatabase creates a new database suitable for use in testing. It returns an established database connection and the configuration.
type TestType ¶ added in v0.4.0
type TestType int16
TestType is a test type in the database.
const ( TestTypeConfirmed TestType TestTypeLikely TestTypeNegative TestTypeUserReport )
type Token ¶
type Token struct { gorm.Model // Tokens belong to one realm. RealmID uint TokenID string `gorm:"type:varchar(200); unique_index"` TestType string `gorm:"type:varchar(20)"` SymptomDate *time.Time TestDate *time.Time Used bool `gorm:"default:false"` ExpiresAt time.Time }
Token represents an issued "long term" from a validated verification code.
func (*Token) FormatSymptomDate ¶
FormatSymptomDate returns YYYY-MM-DD formatted symptom date, or "" if nil.
func (*Token) FormatTestDate ¶ added in v0.14.0
FormatTestDate returns YYYY-MM-DD formatted test date, or "" if nil.
type TokenSigningKey ¶ added in v0.20.0
type TokenSigningKey struct { Errorable // ID is the database auto-incrementing integer of the key. ID uint64 // KeyVersionID is the full name of the signing key version. KeyVersionID string // UUID is the uuid of the key. This is used as the `kid` header value in // JWTs. UUID string `gorm:"column:uuid; default:null;"` // IsActive returns true if this signing key is the active one, false // otherwise. There's a database-level constraint that only one row can have // this value as true, so there is guaranteed to be exactly one active key at // a time. IsActive bool // CreatedAt is when the key was created and added to the system. UpdatedAt is // when the key was last updated, which includes marking it as inactive. CreatedAt time.Time UpdatedAt time.Time }
TokenSigningKey represents a collection of references to a KMS-backed signing key version for verification token signing. It is also used to track rotation schedules.
func (*TokenSigningKey) AuditDisplay ¶ added in v0.20.0
func (k *TokenSigningKey) AuditDisplay() string
AuditDisplay is how the token signing key will be displayed in audit entries.
func (*TokenSigningKey) AuditID ¶ added in v0.20.0
func (k *TokenSigningKey) AuditID() string
AuditID is how the token signing key is stored in the audit entry.
type TranslationSyncResult ¶ added in v0.30.0
type User ¶
type User struct { gorm.Model Errorable Email string `gorm:"type:varchar(250);unique_index"` Name string `gorm:"type:varchar(100)"` SystemAdmin bool `gorm:"column:system_admin; default:false;"` LastRevokeCheck time.Time LastPasswordChange time.Time }
User represents a user of the system
func (*User) AddToRealm ¶ added in v0.19.0
func (u *User) AddToRealm(db *Database, r *Realm, permissions rbac.Permission, actor Auditable) error
AddToRealm adds the current user to the realm with the given permissions. If a record already exists, the permissions are overwritten with the new permissions.
func (*User) AuditDisplay ¶ added in v0.11.0
AuditDisplay is how the user will be displayed in audit entries.
func (*User) BeforeSave ¶ added in v0.4.0
BeforeSave runs validations. If there are errors, the save fails.
func (*User) DeleteFromRealm ¶ added in v0.19.0
DeleteFromRealm removes this user from the given realm. If the user does not exist in the realm, no action is taken.
func (*User) FindMembership ¶ added in v0.19.0
func (u *User) FindMembership(db *Database, realmID interface{}) (*Membership, error)
FindMembership finds the corresponding membership for the given realm ID, if one exists. If not does not exist, an error is returned that satisfies IsNotFound.
func (*User) ListMemberships ¶ added in v0.19.0
func (u *User) ListMemberships(db *Database) ([]*Membership, error)
ListMemberships lists the memberships for this user. Use ListMembershipsCached where possible.
func (*User) PasswordAgeString ¶ added in v0.9.0
PasswordAgeString displays the age of the password in friendly text.
func (*User) PasswordChanged ¶ added in v0.10.0
PasswordChanged returns password change time or account creation time if unset.
func (*User) SelectFirstMembership ¶ added in v0.19.0
func (u *User) SelectFirstMembership(db *Database) (*Membership, error)
SelectFirstMembership selects the first memberships for this user.
type UserReport ¶ added in v0.25.0
type UserReport struct { Errorable // ID is an auto-increment primary key ID uint // PhoneHash is the base64 encoded HMAC of the phone number used to create a user report PhoneHash string `json:"-"` // unique // Nonce is the random data that must be presented when verifying a verification code attached to this user report Nonce string // NonceRequired indicates if this is request requires a nonce, some do not if issued by a PHA web site for example. NonceRequired bool // CodeClaimed is set to true when the associated code is claimed. This is needed // since the verification code itself will be cleaned up before this record. CodeClaimed bool CreatedAt time.Time UpdatedAt time.Time }
UserReport is used to de-duplicate phone numbers for user-initiated reporting.
func (*UserReport) BeforeSave ¶ added in v0.25.0
func (ur *UserReport) BeforeSave(tx *gorm.DB) error
BeforeSave validates the structure of the UserReport.
type UserStat ¶ added in v0.18.0
type UserStat struct { Date time.Time `gorm:"date; not null;"` UserID uint `gorm:"user_id; not null;"` RealmID uint `gorm:"realm_id; default:0;"` CodesIssued uint `gorm:"codes_issued; default:0;"` // Non-database fields, these are added via the stats lookup using the join // table. UserName string `gorm:"-"` UserEmail string `gorm:"-"` }
UserStat represents a single-date statistic for a user.
type UserStats ¶ added in v0.3.0
type UserStats []*UserStat
UserStats represents a logical collection of stats for a user.
func (UserStats) MarshalCSV ¶ added in v0.18.0
MarshalCSV returns bytes in CSV format.
func (UserStats) MarshalJSON ¶ added in v0.18.0
MarshalJSON is a custom JSON marshaller.
func (*UserStats) UnmarshalJSON ¶ added in v0.18.0
type UtilOption ¶ added in v0.23.0
UtilOption is used as optional configuration to the database setup.
func WithKeyManager ¶ added in v0.23.0
func WithKeyManager(mcfg *keys.Config, manager keys.KeyManager) UtilOption
WithKeyManager alters the key manager.
func WithSecretManager ¶ added in v0.23.0
func WithSecretManager(mcfg *secrets.Config, manager secrets.SecretManager) UtilOption
WithSecretManager alters the secret manager.
func WithSigningKeyManager ¶ added in v0.23.0
func WithSigningKeyManager(mcfg *keys.Config, manager keys.SigningKeyManager) UtilOption
WithSigningKeyManager alters the signing key manager.
type VerificationCode ¶
type VerificationCode struct { gorm.Model Errorable RealmID uint // VerificationCodes belong to exactly one realm when issued. Code string `gorm:"type:varchar(512)"` LongCode string `gorm:"type:varchar(512)"` UUID string `gorm:"type:uuid;default:null"` Claimed bool `gorm:"default:false"` TestType string `gorm:"type:varchar(20)"` SymptomDate *time.Time TestDate *time.Time ExpiresAt time.Time LongExpiresAt time.Time UserReportID *uint // These are used in building a user report Nonce []byte `gorm:"-"` PhoneNumber string `gorm:"-"` NonceRequired bool `gorm:"-"` // IssuingUserID is the ID of the user in the database that created this // verification code. This is only populated if the code was created via the // UI. IssuingUserID uint `gorm:"column:issuing_user_id; type:integer;"` // IssuingAppID is the ID of the app in the database that created this // verification code. This is only populated if the code was created via the // API. IssuingAppID uint `gorm:"column:issuing_app_id; type:integer;"` // IssuingExternalID is an optional ID to an external system that created this // verification code. This is only populated if the code was created via the // API AND the API caller supplied it in the request. This ID has no meaning // in this system. It can be up to 255 characters in length. IssuingExternalID string `gorm:"column:issuing_external_id; type:varchar(255);"` }
VerificationCode represents a verification code in the database.
func (*VerificationCode) BeforeSave ¶ added in v0.17.1
func (v *VerificationCode) BeforeSave(tx *gorm.DB) error
BeforeSave is used by callbacks.
func (*VerificationCode) FormatSymptomDate ¶
func (v *VerificationCode) FormatSymptomDate() string
FormatSymptomDate returns YYYY-MM-DD formatted test date, or "" if nil.
func (*VerificationCode) HasLongExpiration ¶ added in v0.7.0
func (v *VerificationCode) HasLongExpiration() bool
func (*VerificationCode) IsExpired ¶
func (v *VerificationCode) IsExpired() bool
IsExpired returns true if a verification code has expired.
func (*VerificationCode) Validate ¶
func (v *VerificationCode) Validate(realm *Realm) error
Validate validates a verification code before save.
Source Files ¶
- audit_entry.go
- auditable.go
- authorized_app.go
- authorized_app_stats.go
- bulk_permission.go
- composite_stats.go
- config.go
- countries.go
- database.go
- database_logger.go
- database_util.go
- duration.go
- dynamic_translation.go
- email_config.go
- errors.go
- external_issuer_stats.go
- key_server_stats.go
- lock.go
- managed_key.go
- membership.go
- metrics.go
- migrations.go
- mobile_app.go
- pagination.go
- realm.go
- realm_chaff_event.go
- realm_stats.go
- realm_user_stats.go
- scopes.go
- secret.go
- secretresolver.go
- signing_key.go
- sms_config.go
- sms_error_stats.go
- sms_from_number.go
- sms_signing_key.go
- system.go
- token.go
- token_signing_keys.go
- user.go
- user_report.go
- user_stats.go
- vercode.go