Skip to content
Snippets Groups Projects
Commit e0457c2f authored by Gabriel Zachmann's avatar Gabriel Zachmann
Browse files

add comments

parent 7a0671f0
No related branches found
No related tags found
No related merge requests found
Showing
with 71 additions and 5 deletions
......@@ -152,6 +152,7 @@ type pollingConf struct {
PollingInterval int64 `yaml:"polling_interval"`
}
// DBConf is type for holding configuration for a db
type DBConf struct {
Hosts []string `yaml:"hosts"`
User string `yaml:"user"`
......@@ -194,6 +195,7 @@ type ProviderConf struct {
AudienceRequestParameter string `yaml:"audience_request_parameter"`
}
// ServiceOperatorConf is type holding the configuration for the service operator of this mytoken instance
type ServiceOperatorConf struct {
Name string `yaml:"name"`
Homepage string `yaml:"homepage"`
......
......@@ -14,6 +14,7 @@ import (
_ "github.com/go-sql-driver/mysql"
)
// NewFromConfig creates a new Cluster from the passed config.DBConf
func NewFromConfig(conf config.DBConf) *Cluster {
c := newCluster(len(conf.Hosts))
c.conf = &conf
......@@ -32,6 +33,7 @@ func newCluster(size int) *Cluster {
return c
}
// Cluster is a type for holding a db cluster
type Cluster struct {
active chan *node
down chan *node
......@@ -54,6 +56,7 @@ func (n *node) close() {
}
}
// AddNodes adds the nodes specified for this Cluster to the cluster
func (c *Cluster) AddNodes() {
for _, host := range c.conf.Hosts {
if err := c.AddNode(host); err != nil {
......@@ -62,6 +65,7 @@ func (c *Cluster) AddNodes() {
}
}
// AddNode adds the passed host a a db node to the cluster
func (c *Cluster) AddNode(host string) error {
log.WithField("host", host).Debug("Adding node to db cluster")
dsn := fmt.Sprintf("%s:%s@%s(%s)/%s?parseTime=true", c.conf.User, c.conf.GetPassword(), "tcp", host, c.conf.DB)
......@@ -125,6 +129,7 @@ func (c *Cluster) checkNodesDown() bool {
return false
}
// Close closes the cluster
func (c *Cluster) Close() {
c.stop <- struct{}{}
for {
......
package dbmigrate
// Commands is a type for holding sql commands that should run before and after a version update
type Commands struct {
Before []string `yaml:"before"`
After []string `yaml:"after"`
}
// VersionCommands is type holding the Commands that are related to a mytoken version
type VersionCommands map[string]Commands
// Migrate holds the VersionCommands for mytoken. These commands are used to migrate the database between mytoken versions.
var Migrate = VersionCommands{
"0.2.0": {Before: v0_2_0_Before},
}
......@@ -99,6 +99,7 @@ func DeleteAuthFlowInfoByState(tx *sqlx.Tx, state *state.State) error {
})
}
// UpdateTokenInfoByState updates the stored AuthFlowInfo for the given state
func UpdateTokenInfoByState(tx *sqlx.Tx, state *state.State, r restrictions.Restrictions, c, sc api.Capabilities) error {
return db.RunWithinTransaction(tx, func(tx *sqlx.Tx) error {
_, err := tx.Exec(`UPDATE AuthInfo SET restrictions=?, capabilities=?, subtoken_capabilities=? WHERE state_h=?`, r, c, sc, state)
......
......@@ -8,6 +8,7 @@ import (
const stateLen = 16
const consentCodeLen = 8
// NewConsentCode creates a new ConsentCode
func NewConsentCode(info Info) *ConsentCode {
return &ConsentCode{
r: utils.RandASCIIString(consentCodeLen),
......@@ -15,6 +16,7 @@ func NewConsentCode(info Info) *ConsentCode {
}
}
// ParseConsentCode parses a string into a ConsentCode
func ParseConsentCode(cc string) *ConsentCode {
return &ConsentCode{
r: cc[:len(cc)-infoAsciiLen],
......@@ -23,6 +25,7 @@ func ParseConsentCode(cc string) *ConsentCode {
}
}
// ConsentCode is type for the code used for giving consent to mytoken
type ConsentCode struct {
r string
encodedInfo string
......@@ -37,6 +40,7 @@ func (c *ConsentCode) String() string {
return c.public
}
// GetState returns the state linked to a ConsentCode
func (c *ConsentCode) GetState() string {
if c.state == "" {
c.state = hashUtils.HMACSHA512Str([]byte("state"), []byte(c.r))[:stateLen] + c.encodedInfo
......
......@@ -11,18 +11,21 @@ import (
"github.com/oidc-mytoken/server/internal/utils/hashUtils"
)
// State is a type for the oidc state
type State struct {
state string
hash string
pollingCode string
}
// NewState creates a new State from a state string
func NewState(state string) *State {
return &State{
state: state,
}
}
// Hash returns the hash for this State
func (s *State) Hash() string {
if s.hash == "" {
s.hash = hashUtils.SHA512Str([]byte(s.state))
......@@ -30,6 +33,7 @@ func (s *State) Hash() string {
return s.hash
}
// PollingCode returns the polling code for this State
func (s *State) PollingCode() string {
if s.pollingCode == "" {
s.pollingCode = hashUtils.HMACSHA512Str([]byte("polling_code"), []byte(s.state))[:config.Get().Features.Polling.Len]
......@@ -38,6 +42,7 @@ func (s *State) PollingCode() string {
return s.pollingCode
}
// State returns the state string for this State
func (s State) State() string {
return s.state
}
......
......@@ -5,6 +5,7 @@ import (
pkgModel "github.com/oidc-mytoken/server/shared/model"
)
// Info is a type for holding the information encoded in a State
type Info struct {
Native bool
ResponseType pkgModel.ResponseType
......@@ -12,6 +13,7 @@ type Info struct {
const infoAsciiLen = 2
// Encode encodes the Info into a string
func (i Info) Encode() string {
fe := singleasciiencode.NewFlagEncoder()
fe.Set("native", i.Native)
......@@ -20,6 +22,7 @@ func (i Info) Encode() string {
return string([]byte{flags, responseType})
}
// Decode decodes the Info from a string
func (i *Info) Decode(s string) {
length := len(s)
if length < infoAsciiLen {
......@@ -31,12 +34,14 @@ func (i *Info) Decode(s string) {
i.Native, _ = flags.Get("native")
}
// CreateState creates a new State and ConsentCode from the passed Info
func CreateState(info Info) (*State, *ConsentCode) {
consentCode := NewConsentCode(info)
s := consentCode.GetState()
return NewState(s), consentCode
}
// Parse parses a State and returns the encoded Info
func (s *State) Parse() (info Info) {
info.Decode(s.State())
return
......
......@@ -9,14 +9,17 @@ import (
"github.com/oidc-mytoken/server/shared/utils/unixtime"
)
// EventHistory is type for multiple EventEntry
type EventHistory []EventEntry
// EventEntry represents a mytoken event
type EventEntry struct {
api.EventEntry `json:",inline"`
MTID mtid.MTID `db:"MT_id" json:"-"`
Time unixtime.UnixTime `db:"time" json:"time"`
}
// GetEventHistory returns the stored EventHistory for a mytoken
func GetEventHistory(tx *sqlx.Tx, id mtid.MTID) (history EventHistory, err error) {
err = db.RunWithinTransaction(tx, func(tx *sqlx.Tx) error {
return tx.Select(&history, `SELECT MT_id, event, time, comment, ip, user_agent FROM EventHistory WHERE MT_id=?`, id)
......
......@@ -35,6 +35,7 @@ type MytokenEntry struct {
networkData api.ClientMetaData
}
// InitRefreshToken links a refresh token to this MytokenEntry
func (ste *MytokenEntry) InitRefreshToken(rt string) error {
ste.refreshToken = rt
ste.encryptionKey = cryptUtils.RandomBytes(32)
......@@ -55,6 +56,7 @@ func (ste *MytokenEntry) InitRefreshToken(rt string) error {
return nil
}
// SetRefreshToken updates the refresh token for this MytokenEntry
func (ste *MytokenEntry) SetRefreshToken(rtID uint64, key []byte) error {
ste.encryptionKey = key
jwt, err := ste.Token.ToJWT()
......
......@@ -12,6 +12,7 @@ import (
"github.com/oidc-mytoken/server/shared/mytoken/rotation"
)
// ParseError parses the passed error for a sql.ErrNoRows
func ParseError(err error) (bool, error) {
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
......
......@@ -34,25 +34,29 @@ func (ste *MytokenEntry) Root() bool {
return !ste.RootID.HashValid()
}
func GetUserID(tx *sqlx.Tx, tokenID mtid.MTID) (uid int64, err error) {
// getUserID returns the user id linked to a mytoken
func getUserID(tx *sqlx.Tx, tokenID mtid.MTID) (uid int64, err error) {
err = db.RunWithinTransaction(tx, func(tx *sqlx.Tx) error {
return tx.Get(&uid, `SELECT user_id FROM MTokens WHERE id=? ORDER BY name`, tokenID)
})
return
}
// AllTokens returns information about all mytokens for the user linked to the passed mytoken
func AllTokens(tx *sqlx.Tx, tokenID mtid.MTID) (trees []MytokenEntryTree, err error) {
err = db.RunWithinTransaction(tx, func(tx *sqlx.Tx) error {
uid, e := GetUserID(tx, tokenID)
uid, e := getUserID(tx, tokenID)
if e != nil {
return e
}
trees, err = AllTokensForUser(tx, uid)
trees, err = allTokensForUser(tx, uid)
return err
})
return
}
func AllTokensForUser(tx *sqlx.Tx, uid int64) ([]MytokenEntryTree, error) {
// allTokensForUser returns information about all mytoken for the passed user
func allTokensForUser(tx *sqlx.Tx, uid int64) ([]MytokenEntryTree, error) {
var tokens []MytokenEntry
if err := db.RunWithinTransaction(tx, func(tx *sqlx.Tx) error {
return tx.Select(&tokens, `SELECT id, parent_id, root_id, name, created, ip_created AS ip FROM MTokens WHERE user_id=?`, uid)
......@@ -70,6 +74,7 @@ func subtokens(tx *sqlx.Tx, rootID mtid.MTID) ([]MytokenEntry, error) {
return tokens, err
}
// TokenSubTree returns information about all subtokens for the passed mytoken
func TokenSubTree(tx *sqlx.Tx, tokenID mtid.MTID) (MytokenEntryTree, error) {
var tokens []MytokenEntry
var root MytokenEntry
......
......@@ -27,6 +27,7 @@ func UpdateRefreshToken(tx *sqlx.Tx, tokenID mtid.MTID, newRT, jwt string) error
})
}
// GetEncryptionKey returns the encryption key and its id for a mytoken
func GetEncryptionKey(tx *sqlx.Tx, tokenID mtid.MTID, jwt string) ([]byte, uint64, error) {
var key []byte
var rtID uint64
......
......@@ -13,6 +13,7 @@ import (
"golang.org/x/mod/semver"
)
// SetVersionBefore sets that the before db migration commands for the passed version were executed
func SetVersionBefore(tx *sqlx.Tx, version string) error {
return db.RunWithinTransaction(tx, func(tx *sqlx.Tx) error {
_, err := tx.Exec(`INSERT INTO version (version, bef) VALUES(?, current_timestamp()) ON DUPLICATE KEY UPDATE bef=current_timestamp()`, version)
......@@ -20,6 +21,7 @@ func SetVersionBefore(tx *sqlx.Tx, version string) error {
})
}
// SetVersionAfter sets that the after db migration commands for the passed version were executed
func SetVersionAfter(tx *sqlx.Tx, version string) error {
return db.RunWithinTransaction(tx, func(tx *sqlx.Tx) error {
_, err := tx.Exec(`INSERT INTO version (version, aft) VALUES(?, current_timestamp()) ON DUPLICATE KEY UPDATE aft=current_timestamp()`, version)
......@@ -27,21 +29,29 @@ func SetVersionAfter(tx *sqlx.Tx, version string) error {
})
}
// UpdateTimes is a type for checking if the db migration commands for different mytoken version have been executed
type UpdateTimes struct {
Version string
Before mysql.NullTime `db:"bef"`
After mysql.NullTime `db:"aft"`
}
// DBVersionState describes the version state of the db
type DBVersionState []UpdateTimes
func (state DBVersionState) Len() int { return len(state) }
// Len returns the len of DBVersionState
func (state DBVersionState) Len() int { return len(state) }
// Swap swaps to elements of DBVersionState
func (state DBVersionState) Swap(i, j int) { state[i], state[j] = state[j], state[i] }
// Less checks if a version is less than another
func (state DBVersionState) Less(i, j int) bool {
a, b := state[i].Version, state[j].Version
return semver.Compare(a, b) < 0
}
// Sort sorts this DBVersionState by the version
func (state DBVersionState) Sort() {
sort.Sort(state)
}
......@@ -74,6 +84,7 @@ func (state DBVersionState) dBHasVersion(v string, cmds dbmigrate.Commands) bool
return ok
}
// GetVersionState returns the DBVersionState
func GetVersionState(tx *sqlx.Tx) (state DBVersionState, err error) {
err = db.RunWithinTransaction(tx, func(tx *sqlx.Tx) error {
return tx.Select(&state, `SELECT version, bef, aft FROM version`)
......
......@@ -5,11 +5,13 @@ import (
"github.com/oidc-mytoken/server/shared/utils"
)
// WebCapability is type for representing api.Capability in the consent screen
type WebCapability struct {
api.Capability
intClass *int
}
// WebCapabilities creates a slice of WebCapability from api.Capabilities
func WebCapabilities(cc api.Capabilities) (wc []WebCapability) {
for _, c := range cc {
wc = append(wc, WebCapability{c, nil})
......@@ -57,10 +59,12 @@ func (c WebCapability) getDangerLevel() int {
return c.getIntClass()
}
// ColorClass returns the html class for coloring this Capability
func (c WebCapability) ColorClass() string {
return textColorByDanger(c.getDangerLevel())
}
// CapabilityLevel returns a string describing the power of this capability
func (c WebCapability) CapabilityLevel() string {
intClass := c.getIntClass()
switch intClass {
......@@ -74,6 +78,7 @@ func (c WebCapability) CapabilityLevel() string {
return ""
}
// IsCreateMT checks if this WebCapability is api.CapabilityCreateMT
func (c WebCapability) IsCreateMT() bool {
return c.Name == api.CapabilityCreateMT.Name
}
......@@ -9,6 +9,7 @@ import (
"github.com/oidc-mytoken/server/shared/utils/unixtime"
)
// WebRestrictions a type for representing restrictions.Restrictions in the consent screen
type WebRestrictions struct {
restrictions.Restrictions
timeClass *int
......@@ -18,6 +19,7 @@ type WebRestrictions struct {
usagesClass *bool
}
// Text returns a textual (json) representation of this WebRestrictions
func (r WebRestrictions) Text() string {
data, _ := json.Marshal(r.Restrictions)
fmt.Println(string(data))
......@@ -110,6 +112,7 @@ func (r WebRestrictions) getUsageClass() bool {
return u
}
// TimeColorClass returns the html class for coloring the time dimension
func (r WebRestrictions) TimeColorClass() string {
intClass := r.getTimeClass()
switch intClass {
......@@ -124,6 +127,7 @@ func (r WebRestrictions) TimeColorClass() string {
}
}
// TimeDescription returns a string describing the state of the time dimension
func (r WebRestrictions) TimeDescription() string {
intClass := r.getTimeClass()
switch intClass {
......@@ -138,6 +142,7 @@ func (r WebRestrictions) TimeDescription() string {
}
}
// ScopeColorClass returns the html class for coloring the scope dimension
func (r WebRestrictions) ScopeColorClass() string {
if r.getScopeClass() {
return "text-success"
......@@ -145,6 +150,7 @@ func (r WebRestrictions) ScopeColorClass() string {
return "text-warning"
}
// ScopeDescription returns a string describing the state of the scope dimension
func (r WebRestrictions) ScopeDescription() string {
if r.getScopeClass() {
return "This token has restrictions for scopes."
......
......@@ -65,6 +65,7 @@ func (r *OIDCFlowRequest) UnmarshalJSON(data []byte) error {
return nil
}
// ToAuthCodeFlowRequest creates a AuthCodeFlowRequest from the OIDCFlowRequest
func (r OIDCFlowRequest) ToAuthCodeFlowRequest() AuthCodeFlowRequest {
return AuthCodeFlowRequest{
OIDCFlowRequest: r,
......
......@@ -5,6 +5,7 @@ import (
mytoken "github.com/oidc-mytoken/server/shared/mytoken/pkg"
)
// TokeninfoIntrospectResponse is type for responses to tokeninfo introspect requests
type TokeninfoIntrospectResponse struct {
api.TokeninfoIntrospectResponse `json:",inline"`
Token mytoken.UsedMytoken `json:"token"`
......
......@@ -4,11 +4,13 @@ import (
"github.com/oidc-mytoken/server/internal/db/dbrepo/eventrepo"
)
// TokeninfoHistoryResponse is type for responses to tokeninfo history requests
type TokeninfoHistoryResponse struct {
// un update check api.TokeninfoHistoryResponse
EventHistory eventrepo.EventHistory `json:"events"`
}
// NewTokeninfoHistoryResponse creates a new TokeninfoHistoryResponse
func NewTokeninfoHistoryResponse(h eventrepo.EventHistory) TokeninfoHistoryResponse {
return TokeninfoHistoryResponse{EventHistory: h}
}
......@@ -4,11 +4,13 @@ import (
"github.com/oidc-mytoken/server/internal/db/dbrepo/mytokenrepo/tree"
)
// TokeninfoListResponse is type for responses to tokeninfo list requests
type TokeninfoListResponse struct {
// un update check api.TokeninfoListResponse
Tokens []tree.MytokenEntryTree `json:"mytokens"`
}
// NewTokeninfoListResponse creates a new TokeninfoListResponse
func NewTokeninfoListResponse(l []tree.MytokenEntryTree) TokeninfoListResponse {
return TokeninfoListResponse{Tokens: l}
}
......@@ -6,6 +6,7 @@ import (
"github.com/oidc-mytoken/server/shared/mytoken/token"
)
// TokenInfoRequest is a type for holding a request to the tokeninfo endpoint
type TokenInfoRequest struct {
api.TokenInfoRequest `json:",inline"`
Action model.TokeninfoAction `json:"action"`
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment