123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284 |
- package access
- import (
- "bytes"
- "crypto/sha256"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "sort"
- "strings"
- "sync"
- "time"
- "devt.de/krotik/common/datautil"
- "devt.de/krotik/common/errorutil"
- "devt.de/krotik/common/stringutil"
- )
- type ACLTable interface {
-
- Close() error
-
- GroupNames() ([]string, error)
-
- UserNames() ([]string, error)
-
- GroupsOfUser(name string) ([]string, error)
-
- AddPermission(group, resource string, permission *Rights) error
-
- Permissions(group string) (map[string]string, error)
-
- ClearPermissions(group string) error
-
- IsPermitted(user, resource string, request *Rights) (bool, string, error)
-
- AddGroup(name string) error
-
- RemoveGroup(name string) error
-
- AddUserToGroup(name string, group string) error
-
- RemoveUserFromGroup(name string, group string) error
-
- GetConfig() (map[string]interface{}, error)
-
- String() string
- }
- type Group struct {
- Name string
- ResourceAccessAbs map[string]*Rights
- ResourceAccessPre map[string]*Rights
- }
- func (g *Group) ClearResourceAccess() {
- g.ResourceAccessAbs = make(map[string]*Rights)
- g.ResourceAccessPre = make(map[string]*Rights)
- }
- func (g *Group) AddResourceAccess(res string, r *Rights) error {
- if strings.HasSuffix(res, "*") {
- pre := res[:len(res)-1]
- if _, ok := g.ResourceAccessPre[pre]; ok {
- return fmt.Errorf("Resource access wildcard for %v registered twice", res)
- }
- g.ResourceAccessPre[pre] = r
- } else {
- if _, ok := g.ResourceAccessAbs[res]; ok {
- return fmt.Errorf("Resource access for %v registered twice", res)
- }
- g.ResourceAccessAbs[res] = r
- }
- return nil
- }
- func (g *Group) IsPermitted(resource string, request *Rights) (bool, string) {
-
- if r, ok := g.ResourceAccessAbs[resource]; ok {
- if r.IsAllowed(request) {
- return true, fmt.Sprintf("Group %v has specific access to %v with %v", g.Name, resource, r.String())
- }
- }
-
- for pre, r := range g.ResourceAccessPre {
- if strings.HasPrefix(resource, pre) && r.IsAllowed(request) {
- return true, fmt.Sprintf("Group %v has general access to %v with %v", g.Name, pre, r.String())
- }
- }
- return false, ""
- }
- func (g *Group) String() string {
- var buf bytes.Buffer
- buf.WriteString(fmt.Sprintf("Group: %v\n====\n", g.Name))
-
- longest := 0
- for n := range g.ResourceAccessAbs {
- if len(n) > longest {
- longest = len(n)
- }
- }
- for n := range g.ResourceAccessPre {
- if len(n) > longest {
- longest = len(n)
- }
- }
- addResourceMap := func(m map[string]*Rights) {
- res := make([]string, 0, len(m))
- for n := range m {
- res = append(res, n)
- }
- sort.Strings(res)
- for _, n := range res {
- buf.WriteString(fmt.Sprintf("%-"+fmt.Sprint(longest)+"v : %v\n",
- n, m[n]))
- }
- }
- addResourceMap(g.ResourceAccessAbs)
- addResourceMap(g.ResourceAccessPre)
- return buf.String()
- }
- type Rights struct {
- Create bool
- Read bool
- Update bool
- Delete bool
- }
- func RightsFromString(rights string) (*Rights, error) {
- var ret *Rights
- var c, r, u, d bool
- var err error
- if len(rights) != 4 {
- return nil, fmt.Errorf("Rigths string must be 4 characters")
- }
- rights = strings.ToLower(rights)
- parseChar := func(got byte, positive, desc string) (bool, error) {
- if string(got) == positive {
- return true, nil
- } else if string(got) == "-" {
- return false, nil
- }
- return false, fmt.Errorf("%v permission in rights string must be either '%v' or '-'", desc, positive)
- }
- if c, err = parseChar(rights[0], "c", "Create"); err == nil {
- if r, err = parseChar(rights[1], "r", "Read"); err == nil {
- if u, err = parseChar(rights[2], "u", "Update"); err == nil {
- d, err = parseChar(rights[3], "d", "Delete")
- }
- }
- }
- if err == nil {
- ret = &Rights{Create: c, Read: r, Update: u, Delete: d}
- }
- return ret, err
- }
- func (r *Rights) IsAllowed(request *Rights) bool {
- if request.Create && request.Create != r.Create {
- return false
- } else if request.Read && request.Read != r.Read {
- return false
- } else if request.Update && request.Update != r.Update {
- return false
- } else if request.Delete && request.Delete != r.Delete {
- return false
- }
- return true
- }
- func (r *Rights) String() string {
- ret := []string{"-", "-", "-", "-"}
- if r.Create {
- ret[0] = "C"
- }
- if r.Read {
- ret[1] = "R"
- }
- if r.Update {
- ret[2] = "U"
- }
- if r.Delete {
- ret[3] = "D"
- }
- return strings.Join(ret, "")
- }
- type MemoryACLTable struct {
- PermissionCache *datautil.MapCache
- Users map[string]map[string]*Group
- Groups map[string]*Group
- }
- func NewMemoryACLTable() ACLTable {
- return &MemoryACLTable{datautil.NewMapCache(300, 0),
- make(map[string]map[string]*Group), make(map[string]*Group)}
- }
- func NewMemoryACLTableFromConfig(config map[string]interface{}) (ACLTable, error) {
-
- v, err := json.Marshal(config)
- if err == nil {
- err = json.Unmarshal(v, &config)
- if err == nil {
- usersData, ok := config["users"]
- if !ok {
- return nil, fmt.Errorf("Entry 'users' is missing from ACL table config")
- }
- users, ok := usersData.(map[string]interface{})
- if !ok {
- return nil, fmt.Errorf("Entry 'users' is not of the expected format")
- }
- groupsData, ok := config["groups"]
- if !ok {
- return nil, fmt.Errorf("Entry 'groups' is missing from ACL table config")
- }
- groups, ok := groupsData.(map[string]interface{})
- if !ok {
- return nil, fmt.Errorf("Entry 'groups' is not of the expected format")
- }
- tab := NewMemoryACLTable()
-
- for g, res := range groups {
- err = tab.AddGroup(g)
- if _, ok := res.(map[string]interface{}); !ok {
- return nil, fmt.Errorf("Entries in 'groups' are not of the expected format")
- }
- for r, p := range res.(map[string]interface{}) {
- var rights *Rights
- rights, err = RightsFromString(fmt.Sprint(p))
- if err == nil {
- err = tab.AddPermission(g, r, rights)
- }
- if err != nil {
- err = fmt.Errorf("Error adding resource %v of group %v: %v",
- r, g, err.Error())
- break
- }
- }
- if err != nil {
- break
- }
- }
-
- if err == nil {
- for u, gs := range users {
- if _, ok := gs.([]interface{}); !ok {
- return nil, fmt.Errorf("Entries in 'users' are not of the expected format")
- }
- for _, g := range gs.([]interface{}) {
- if err = tab.AddUserToGroup(u, fmt.Sprint(g)); err != nil {
- err = fmt.Errorf("Error adding user %v to group %v: %v",
- u, g, err.Error())
- break
- }
- }
- if err != nil {
- break
- }
- }
- }
- if err == nil {
- return tab, nil
- }
- }
- }
- return nil, err
- }
- func (t *MemoryACLTable) Close() error {
-
- return nil
- }
- func (t *MemoryACLTable) GroupNames() ([]string, error) {
- var ret []string
- if t != nil {
- for n := range t.Groups {
- ret = append(ret, n)
- }
- sort.Strings(ret)
- }
- return ret, nil
- }
- func (t *MemoryACLTable) UserNames() ([]string, error) {
- var ret []string
- if t != nil {
- for n := range t.Users {
- ret = append(ret, n)
- }
- sort.Strings(ret)
- }
- return ret, nil
- }
- func (t *MemoryACLTable) GroupsOfUser(name string) ([]string, error) {
- var ret []string
- var err error
- if ug, ok := t.Users[name]; ok {
- for n := range ug {
- ret = append(ret, n)
- }
- sort.Strings(ret)
- } else {
- err = fmt.Errorf("Unknown user: %v", name)
- }
- return ret, err
- }
- func (t *MemoryACLTable) AddPermission(group, resource string, permission *Rights) error {
- g, ok := t.Groups[group]
- if !ok {
- return fmt.Errorf("Group %v does not exist", group)
- }
- t.invalidatePermCache()
- return g.AddResourceAccess(resource, permission)
- }
- func (t *MemoryACLTable) Permissions(group string) (map[string]string, error) {
- if _, ok := t.Groups[group]; !ok {
- return nil, fmt.Errorf("Group %v does not exist", group)
- }
- c, _ := t.GetConfig()
- return c["groups"].(map[string]map[string]string)[group], nil
- }
- func (t *MemoryACLTable) ClearPermissions(group string) error {
- g, ok := t.Groups[group]
- if !ok {
- return fmt.Errorf("Group %v does not exist", group)
- }
- t.invalidatePermCache()
- g.ClearResourceAccess()
- return nil
- }
- func (t *MemoryACLTable) invalidatePermCache() {
- t.PermissionCache.Clear()
- }
- func (t *MemoryACLTable) IsPermitted(user, resource string, request *Rights) (bool, string, error) {
- var res bool
- var err error
- var reason string
-
- if res, ok := t.PermissionCache.Get(fmt.Sprint([]string{user, resource, request.String()})); ok {
- return res.(bool), "Permission was stored in the cache", err
- }
- if ug, ok := t.Users[user]; ok {
-
- for _, g := range ug {
- if ok, okReason := g.IsPermitted(resource, request); ok {
- res = true
- reason = okReason
- break
- }
- }
-
- t.PermissionCache.Put(fmt.Sprint([]string{user, resource, request.String()}), res)
- } else {
- err = fmt.Errorf("Unknown user: %v", user)
- }
- return res, reason, err
- }
- func (t *MemoryACLTable) AddGroup(name string) error {
- if _, ok := t.Groups[name]; ok {
- return fmt.Errorf("Group %v added twice", name)
- }
- t.invalidatePermCache()
- g := &Group{name, make(map[string]*Rights), make(map[string]*Rights)}
- t.Groups[g.Name] = g
- return nil
- }
- func (t *MemoryACLTable) RemoveGroup(name string) error {
- if _, ok := t.Groups[name]; !ok {
- return fmt.Errorf("Group %v does not exist", name)
- }
- t.invalidatePermCache()
- delete(t.Groups, name)
- for gname, gm := range t.Users {
- delete(gm, name)
- if len(gm) == 0 {
-
- delete(t.Users, gname)
- }
- }
- return nil
- }
- func (t *MemoryACLTable) AddUserToGroup(name string, group string) error {
- g, ok := t.Groups[group]
- if !ok {
- return fmt.Errorf("Group %v does not exist", group)
- }
- t.invalidatePermCache()
- if l, ok := t.Users[name]; ok {
- if _, ok := l[group]; !ok {
- l[group] = g
- }
- } else {
- t.Users[name] = map[string]*Group{
- group: g,
- }
- }
- return nil
- }
- func (t *MemoryACLTable) RemoveUserFromGroup(name string, group string) error {
- var err error
- u, ok := t.Users[name]
- if !ok {
- return fmt.Errorf("User %v does not exist", name)
- }
- t.invalidatePermCache()
- if _, ok := u[group]; ok {
- delete(u, group)
- } else {
- err = fmt.Errorf("User %v is not in group %v", name, group)
- }
- return err
- }
- func (t *MemoryACLTable) String() string {
- var buf bytes.Buffer
- buf.WriteString("ACLTable\n")
- buf.WriteString("========\n")
- buf.WriteString("Users:\n")
- usernames, _ := t.UserNames()
- for _, u := range usernames {
- g, err := t.GroupsOfUser(u)
- errorutil.AssertOk(err)
- buf.WriteString(fmt.Sprintf("%v : %v\n", u, strings.Join(g, ", ")))
- }
- groupnames, _ := t.GroupNames()
- for _, g := range groupnames {
- buf.WriteString("\n")
- buf.WriteString(t.Groups[g].String())
- }
- return buf.String()
- }
- func (t *MemoryACLTable) GetConfig() (map[string]interface{}, error) {
- data := make(map[string]interface{})
- users := make(map[string][]string)
- data["users"] = users
- usernames, _ := t.UserNames()
- for _, u := range usernames {
- g, err := t.GroupsOfUser(u)
- errorutil.AssertOk(err)
- users[u] = g
- }
- groups := make(map[string]map[string]string)
- data["groups"] = groups
- groupnames, _ := t.GroupNames()
- for _, g := range groupnames {
- group := t.Groups[g]
- resources := make(map[string]string)
- groups[g] = resources
- for res, rights := range group.ResourceAccessAbs {
- resources[res] = rights.String()
- }
- for res, rights := range group.ResourceAccessPre {
- resources[res+"*"] = rights.String()
- }
- }
- return data, nil
- }
- var PersistedACLTableErrRetries = 10
- var watchSleep = time.Sleep
- var (
- ErrClosed = errors.New("ACL table was closed")
- )
- type PersistedACLTable struct {
- table ACLTable
- tableLock *sync.RWMutex
- interval time.Duration
- filename string
- SyncError error
- shutdown chan bool
- }
- func NewPersistedACLTable(filename string, interval time.Duration) (ACLTable, error) {
- var ret *PersistedACLTable
- ptable := &PersistedACLTable{nil, &sync.RWMutex{}, interval, filename, nil, nil}
- err := ptable.start()
- if err == nil {
- ret = ptable
- }
- return ret, err
- }
- func (t *PersistedACLTable) start() error {
-
-
- err := t.sync(true)
- if err == nil {
-
- t.shutdown = make(chan bool)
- go t.watch()
- }
- return err
- }
- func (t *PersistedACLTable) watch() {
- err := t.SyncError
- errCnt := 0
- defer func() {
- t.shutdown <- true
- }()
- for t.SyncError != ErrClosed {
-
- watchSleep(t.interval)
-
- t.tableLock.Lock()
-
- if err = t.sync(true); err != nil && t.SyncError != ErrClosed {
-
- err = fmt.Errorf("Could not sync ACL table config from disk: %v",
- err.Error())
- errCnt++
- } else {
-
- errCnt = 0
- }
-
- if t.SyncError != ErrClosed {
- t.SyncError = err
- }
- if errCnt == PersistedACLTableErrRetries {
-
-
-
- t.sync(false)
- }
- t.tableLock.Unlock()
- }
- }
- func (t *PersistedACLTable) Close() error {
- var err error
- t.tableLock.Lock()
- if t.SyncError != nil {
-
- err = t.SyncError
- }
-
- t.SyncError = ErrClosed
- t.tableLock.Unlock()
-
- if t.shutdown != nil {
- <-t.shutdown
- t.shutdown = nil
- }
- return err
- }
- func (t *PersistedACLTable) sync(checkFile bool) error {
- var checksumFile, checksumMemory string
- stringMemoryTable := func() ([]byte, error) {
- tableconfig, _ := t.table.GetConfig()
- return json.MarshalIndent(tableconfig, "", " ")
- }
- writeMemoryTable := func() error {
- res, err := stringMemoryTable()
- if err == nil {
- err = ioutil.WriteFile(t.filename, res, 0666)
- }
- return err
- }
- readMemoryTable := func() (map[string]interface{}, error) {
- var conf map[string]interface{}
- res, err := ioutil.ReadFile(t.filename)
- if err == nil {
- err = json.Unmarshal(stringutil.StripCStyleComments(res), &conf)
- }
- return conf, err
- }
-
- file, err := os.OpenFile(t.filename, os.O_RDONLY, 0660)
- if err != nil {
- if os.IsNotExist(err) {
-
- err = nil
- }
-
- checksumFile = ""
- } else {
- hashFactory := sha256.New()
- if _, err = io.Copy(hashFactory, file); err == nil {
-
- checksumFile = fmt.Sprintf("%x", hashFactory.Sum(nil))
- }
- file.Close()
- }
- if err == nil {
-
-
- if t.table != nil {
- var mtString []byte
- if mtString, err = stringMemoryTable(); err == nil {
- hashFactory := sha256.New()
- hashFactory.Write(mtString)
- checksumMemory = fmt.Sprintf("%x", hashFactory.Sum(nil))
- }
- } else {
- checksumMemory = ""
- }
- }
- if err == nil {
-
- if checkFile {
-
- if checksumFile == "" {
-
- t.table = NewMemoryACLTable()
- err = writeMemoryTable()
- } else if checksumFile != checksumMemory {
- var conf map[string]interface{}
- if conf, err = readMemoryTable(); err == nil {
- t.table, err = NewMemoryACLTableFromConfig(conf)
- }
- }
- } else {
-
- if checksumMemory == "" {
-
- t.table = NewMemoryACLTable()
- err = writeMemoryTable()
- } else if checksumFile != checksumMemory {
- err = writeMemoryTable()
- }
- }
- }
- return err
- }
- func (t *PersistedACLTable) GroupNames() ([]string, error) {
- t.tableLock.RLock()
- defer t.tableLock.RUnlock()
- if t.SyncError != nil {
- return nil, t.SyncError
- }
- return t.table.GroupNames()
- }
- func (t *PersistedACLTable) UserNames() ([]string, error) {
- t.tableLock.RLock()
- defer t.tableLock.RUnlock()
- if t.SyncError != nil {
- return nil, t.SyncError
- }
- return t.table.UserNames()
- }
- func (t *PersistedACLTable) GroupsOfUser(name string) ([]string, error) {
- t.tableLock.RLock()
- defer t.tableLock.RUnlock()
- if t.SyncError != nil {
- return nil, t.SyncError
- }
- return t.table.GroupsOfUser(name)
- }
- func (t *PersistedACLTable) AddPermission(group, resource string, permission *Rights) error {
- t.tableLock.Lock()
- defer t.tableLock.Unlock()
- if t.SyncError != nil {
- return t.SyncError
- }
- err := t.table.AddPermission(group, resource, permission)
- if err == nil {
-
- err = t.sync(false)
- }
- return err
- }
- func (t *PersistedACLTable) Permissions(group string) (map[string]string, error) {
- t.tableLock.RLock()
- defer t.tableLock.RUnlock()
- if t.SyncError != nil {
- return nil, t.SyncError
- }
- return t.table.Permissions(group)
- }
- func (t *PersistedACLTable) ClearPermissions(group string) error {
- t.tableLock.Lock()
- defer t.tableLock.Unlock()
- if t.SyncError != nil {
- return t.SyncError
- }
- t.table.ClearPermissions(group)
- return t.sync(false)
- }
- func (t *PersistedACLTable) IsPermitted(user, resource string, request *Rights) (bool, string, error) {
- t.tableLock.RLock()
- defer t.tableLock.RUnlock()
- if t.SyncError != nil {
- return false, "", t.SyncError
- }
- return t.table.IsPermitted(user, resource, request)
- }
- func (t *PersistedACLTable) AddGroup(name string) error {
- t.tableLock.Lock()
- defer t.tableLock.Unlock()
- if t.SyncError != nil {
- return t.SyncError
- }
- err := t.table.AddGroup(name)
- if err == nil {
-
- err = t.sync(false)
- }
- return err
- }
- func (t *PersistedACLTable) RemoveGroup(name string) error {
- t.tableLock.Lock()
- defer t.tableLock.Unlock()
- if t.SyncError != nil {
- return t.SyncError
- }
- err := t.table.RemoveGroup(name)
- if err == nil {
-
- err = t.sync(false)
- }
- return err
- }
- func (t *PersistedACLTable) AddUserToGroup(name string, group string) error {
- t.tableLock.Lock()
- defer t.tableLock.Unlock()
- if t.SyncError != nil {
- return t.SyncError
- }
- err := t.table.AddUserToGroup(name, group)
- if err == nil {
-
- err = t.sync(false)
- }
- return err
- }
- func (t *PersistedACLTable) RemoveUserFromGroup(name string, group string) error {
- t.tableLock.Lock()
- defer t.tableLock.Unlock()
- if t.SyncError != nil {
- return t.SyncError
- }
- err := t.table.RemoveUserFromGroup(name, group)
- if err == nil {
-
- err = t.sync(false)
- }
- return err
- }
- func (t *PersistedACLTable) GetConfig() (map[string]interface{}, error) {
- t.tableLock.RLock()
- defer t.tableLock.RUnlock()
- if t.SyncError != nil {
- return nil, t.SyncError
- }
- return t.table.GetConfig()
- }
- func (t *PersistedACLTable) String() string {
- t.tableLock.RLock()
- defer t.tableLock.RUnlock()
- return t.table.String()
- }
|